Skip to content

Instantly share code, notes, and snippets.

@mickhansen
Last active December 15, 2015 19:19
Show Gist options
  • Save mickhansen/5310863 to your computer and use it in GitHub Desktop.
Save mickhansen/5310863 to your computer and use it in GitHub Desktop.
A proposal for API design of Hooks in Sequelize
// The primary reason why hooks is not plug and play is the need for asynchronicity
// This is my proposal on how we might implement this
// It's written as kind of pseudo code with knowledge of sequelize internals
// To keep the method signatures easier to understand, i propose that all hook callbacks are called with the current model as context (if available), parameters are arguments with the final arguments being a next callback
// The hooks would then be able to be chained via the next callbacks, ala middleware
var User = sequelize.define('User', {
// fields
}, {
// instanceMethods, etc
hooks: {
beforeCreate: [
function(values, next) {
// Do stuff before creating
},
],
afterCreate: function(values, next) {
// Do stuff before creating
}
}
});
User.hook('beforeUpdate', function (values, next) {
// Do stuff before updating
});
User.hook('beforeDestroy', function (next) {
// Do stuff before destroying
});
User.hook('beforeDestroy', function (next) {
// Do other stuff before destroying
});
// An indefinite amount of hooks for the same hook should be able to be defined.
// Internally:
DAOFactory.create = function(values) {
var emitter = new CustomEventEmitter();
DAOFactory.evaulateHooks('beforeCreate', values, function () {
var model = this.build(values);
model.save().proxy(emitter);
});
return emitter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment