Skip to content

Instantly share code, notes, and snippets.

@omartrigui
Created May 9, 2016 19:47
Show Gist options
  • Save omartrigui/cbc4e1c90e13d619cf9753aa610c7a46 to your computer and use it in GitHub Desktop.
Save omartrigui/cbc4e1c90e13d619cf9753aa610c7a46 to your computer and use it in GitHub Desktop.
var aop = function(schema) {
schema.aop = [];
var executePre = function(functions, index, context, next) {
if (functions.length == index) {
next();
} else {
functions[index](context, function() {
executePre(functions, index + 1, context, next);
});
}
};
var executePost = function(functions, index, context, doc) {
if (functions.length !== index) {
functions[index](context, function() {
executePost(functions, index + 1, context, doc);
});
}
};
var execute = function(method, pre, post){
if(pre){
schema.pre(method, function(next) {
executePre(pre, 0, this, next);
});
}
if(post){
schema.post(method, function(doc) {
executePost(post, 0, this, doc);
});
}
};
schema.runAOP = function() {
for (var i = 0; i < schema.aop.length; i++) {
var aop = {
method: schema.aop[i].method || 'save',
pre: schema.aop[i].pre || false,
post: schema.aop[i].post || false
};
execute(aop.method, aop.pre, aop.post);
}
};
};
module.exports = aop;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment