Hooks are not working
I have a model. And Added Hooks Before Save and After Create They Are both not instantiating uuid of my AccessModel. import { Column, DataType, BelongsTo, Table, BeforeCreate, BeforeValidate, AfterCreate, BeforeSave } from 'sequelize-typescript'; import { SequelizeModelHelper } from 'src/common/helpers'; import { AccessInterface } from 'src/modules/companies/managements/staffs/employees/accesses/interfaces'; import { v4 } from 'uuid'; import { AccessModelDto, CreateAccessModelDto } from '../dto'; @Table({ tableName: 'accesses', modelName: 'AccessModel' }) export class AccessModel extends SequelizeModelHelper { @Column({ field: 'title', type: DataType.STRING // //defaultValue: '' }) title: string;
@Column({
field: 'models',
type: DataType.JSONB
// //defaultValue: []
})
models: CreateAccessModelDto[];
@Column({
field: 'division_ids',
type: DataType.ARRAY(DataType.INTEGER)
// //defaultValue: []
})
divisionIds: number[] = [];
@Column({
field: 'department_ids',
type: DataType.ARRAY(DataType.INTEGER)
// //defaultValue: []
})
departmentIds: number[] = [];
@Column({
field: 'company_ids',
type: DataType.ARRAY(DataType.INTEGER)
// //defaultValue: []
})
companyIds: number[];
@Column({
field: 'asset_tree_ids',
type: DataType.ARRAY(DataType.INTEGER)
// //defaultValue: []
})
assetTreeIds: number[];
@Column({
field: 'employee_ids',
type: DataType.ARRAY(DataType.INTEGER)
// //defaultValue: []
})
employeeIds: number[];
@Column({
field: 'is_active',
type: DataType.BOOLEAN
// //defaultValue: true
})
isActive: boolean;
@BeforeSave
static async setUuid(instance: AccessModel) {
console.log(true);
if (!instance.uuid) {
instance.uuid = v4();
}
}
constructor(entity?: Partial<AccessModel>) {
super();
Object.assign(this, entity);
}
} And The Error is SequelizeValidationError: notNull Violation: AccessModel.uuid cannot be null
You need to explicitly define your uuid field something like this:
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4, // you should use "defaultValue: UUDV4" instead if your database doesn't have native UUID support
primaryKey: true,
allowNull: false,
},
If you set up your uuid field to use UUDV4 as the default value, I'm not sure if you'd still need this @BeforeSave hook as Sequelize will automatically generate a UUID if one isn't provided when creating a new instance.
No that is not the case if i attach default property to the column decorator after receiving entity record from database, in a case when don't select uuid attribute it will define uuid property to the entity