Global / universal hooks
Global hooks are hooks which are run for all models. They can define behaviours that you want for all your models, and are especially useful for plugins. They can be defined in two ways, which have slightly different semantics:
Default Hooks (Sequelize.options.define)
const sequelize = new Sequelize(..., {
define: {
hooks: {
beforeCreate: () => {
// Do stuff
}
}
}
});
This adds a default hook to all models, which is run if the model does not define its own beforeCreate
hook:
class User extends Model {}
User.init({}, { sequelize });
class Project extends Model {}
Project.init({}, {
hooks: {
beforeCreate: () => {
// Do other stuff
}
},
sequelize
});
User.create() // Runs the global hook
Project.create() // Runs its own hook (because the global hook is overwritten)
Permanent Hooks (Sequelize.addHook)
sequelize.addHook('beforeCreate', () => {
// Do stuff
});
This hook is always run before create, regardless of whether the model specifies its own beforeCreate
hook. Local hooks are always run before global hooks:
class User extends Model {}
User.init({}, { sequelize });
class Project extends Model {}
Project.init({}, {
hooks: {
beforeCreate: () => {
// Do other stuff
}
},
sequelize
});
User.create() // Runs the global hook
Project.create() // Runs its own hook, followed by the global hook
Permanent hooks may also be defined in Sequelize.options
:
new Sequelize(..., {
hooks: {
beforeCreate: () => {
// do stuff
}
}
});
Connection Hooks
Sequelize provides four hooks that are executed immediately before and after a database connection is obtained or released:
beforeConnect(config)
afterConnect(connection, config)
beforeDisconnect(connection)
afterDisconnect(connection)
These hooks can be useful if you need to asynchronously obtain database credentials, or need to directly access the low-level database connection after it has been created.
For example, we can asynchronously obtain a database password from a rotating token store, and mutate Sequelize's configuration object with the new credentials:
sequelize.beforeConnect((config) => {
return getAuthToken()
.then((token) => {
config.password = token;
});
});
These hooks may only be declared as a permanent global hook, as the connection pool is shared by all models.