Мне нужно сделать новый объект из класса со значениями по умолчанию в TypeScript Class.
но пока единственный способ - использовать пользовательский метод getNewEntity()
. Это нормально или есть более правильный путь?
(используется sequelize orm)
@ObjectType()
export default class People extends Model<People> {
@Field(() => ID)
@PrimaryKey
@AutoIncrement
@Column
id: number;
@Field({ nullable : true })
@Column
name: string;
@Field({ nullable : true })
@Column
active: string;
static getNewEntity() {
let people = new People();
people.active = 'N';
return people;
}
constructor() {
super();
self.active = 'N';
}
// constructor() {
// super();
// self.active = 'N';
// }
@Resolver()
export class PeopleResolver {
@Mutation(() => Boolean)
async savePeople(
@Arg("name") name: string,
) {
People.findOneByPk(1)
.then(async people => {
if (!people) {
// if make object people with static method getNewEntity()
people = People.getNewEntity();
people.name = "Bob";
// Executing (default): INSERT INTO `people` (`id`,`name`,`active`) VALUES (DEFAULT,'Bob','N');
// it`ok!
// constructor IS Deleted
people = new People();
people.name = "Bob";
// Executing (default): INSERT INTO `people` (`id`,`name`) VALUES (DEFAULT,'Bob');
// so we have not default params active = 'N'
// constructor IS Work
people = new People();
people.name = "Bob";
// Executing (default): INSERT INTO `people` (`id`,`name`,`active`) VALUES (DEFAULT,'Bob','N);
// but if constructor is and people already exist in DB
}
else {
people.name = "Jack";
}
await people.save();
// but if constructor is work and people already exist in DB we have query TO INSERT !!!!!not to UPDATE !!!!!
// Executing (default): INSERT INTO `people` (`id`,`name`,`active`) VALUES (DEFAULT,'Jack','N);
})
}
}
// I am trying to add default value to model @Field()
@Field({ nullable : true })
@Column
active: string = 'N';
// and when people not exist it`s ok (without constructor and getNewEntity method)
people = new People();
people.name = "Bob";
await people.save();
// Executing (default): INSERT INTO `people` (`id`,`name`,`active`) VALUES (DEFAULT,'Bob','N');
// but if people already exist in DB and we uptated it
people.name = "Tom";
people.active = "Y";
await people.save();
// `UPDATE `people` SET `name`='Tom',`active`='Y' WHERE `id` = 1`
// and then updated again whitout 'people.active = "Y";'
people.name = "Jack";
await people.save();
// `UPDATE `people` SET `name`='Jack',`active`='N' WHERE `id` = 1`
// so we have autoreplacement `active='Y'` to `active='N'`
И в результате у меня есть один способ создать и обновить объект - бросить пользовательский метод getNewEntity (),
но разве это не другой путь?