生命周期函数
有的时候,我们希望在存储之前干点什么,比如把用户的密码进行 Hash 一下。这个时候就需要用到生命周期函数了。
生命周期函数有哪些?有哪些种类?
支持的生命周期函数如下
(1)
beforeBulkCreate(instances, options)
beforeBulkDestroy(options)
beforeBulkUpdate(options)
(2)
beforeValidate(instance, options)
(-)
validate
(3)
afterValidate(instance, options)
- or -
validationFailed(instance, options, error)
(4)
beforeCreate(instance, options)
beforeDestroy(instance, options)
beforeUpdate(instance, options)
beforeSave(instance, options)
beforeUpsert(values, options)
(-)
create
destroy
update
(5)
afterCreate(instance, options)
afterDestroy(instance, options)
afterUpdate(instance, options)
afterSave(instance, options)
afterUpsert(created, options)
(6)
afterBulkCreate(instances, options)
afterBulkDestroy(options)
afterBulkUpdate(options)
这些周期函数分为全局的与模型级别的。
全局级别
const sequelize = new Sequelize(..., {
define: {
hooks: {
beforeCreate: () => {
// Do stuff
}
}
}
});
模型级别
const Project = sequelize.define('project', {}, {
hooks: {
beforeCreate: () => {
// Do other stuff
}
}
});
定义生命周期的三种方式
1.options
const Project = sequelize.define('project', {}, {
hooks: {
beforeCreate: () => {
// Do other stuff
}
}
});
const sequelize = new Sequelize(..., {
define: {
hooks: {
beforeCreate: () => {
// Do stuff
}
}
}
});
2.调用对应的方法
sequelize.afterValidate('xxx', () => {....})
User.afterValidate('myHookAfter', (user, options) => {
user.username = 'Toni';
});
3.调用 addHook
sequelize.addHook('xxx', () => {....})
User.addHook('afterValidate', 'notifyUsers', () => {....})
命名生命周期函数
取一个叫 notifyUsers 的名字
User.afterValidate('myHookAfter', (user, options) => {
user.username = 'Toni';
});
User.addHook('afterValidate', 'notifyUsers', () => {....})
移除生命周期函数
只有被命名了的生命周期函数才可移除
Book.removeHook('afterValidate', 'notifyUsers');
当前内容版权归 nodelover.me 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 nodelover.me .