Lifecycle callbacks are functions that are automagically called before or after certain model actions. For example, we sometimes use lifecycle callbacks to automatically hash a password before creating or updating an Account
model.
Sails exposes a handful of lifecycle callbacks by default.
create
update
destroy
If you want to hash a password before saving in the database, you might use the beforeCreate
lifecycle callback.
var bcrypt = require('bcrypt');
module.exports = {
attributes: {
username: {
type: 'string',
required: true
},
password: {
type: 'string',
minLength: 6,
required: true,
columnName: 'hashed_password'
}
},
// Lifecycle Callbacks
beforeCreate: function (values, cb) {
// Hash password
bcrypt.hash(values.password, 10, function(err, hash) {
if(err) return cb(err);
values.password = hash;
//calling cb() with an argument returns an error. Useful for canceling the entire operation if some criteria fails.
cb();
});
}
};