Skip to content

Instantly share code, notes, and snippets.

@formula1
Created March 16, 2015 19:56
Show Gist options
  • Save formula1/5fd75e9ffdd3c3b2f660 to your computer and use it in GitHub Desktop.
Save formula1/5fd75e9ffdd3c3b2f660 to your computer and use it in GitHub Desktop.
On the fly Middleware without editing the callback array
var MIDDLEWARE_TYPES = [
"validate",
"create",
"update",
"destroy"
];
var MIDDLEWARE_TIMINGS = [
"before",
"after"
];
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function easyExtend(collection){
collection.getMiddleware = function(type){
if(!(type in collection._callbacks)) throw new Error(type+" not in the middleware");
return collection._callbacks[type];
};
MIDDLEWARE_TIMINGS.forEach(function(time){
collection[time] = function(type,fn){
if(MIDDLEWARE_TYPES.indexOf(type) === -1){
throw new Error(
"cannot add middleware not in types: "+
JSON.stringify(MIDDLEWARE_TYPES)
);
}
if(typeof fn != "function"){
throw new Error(
"callback supplied for("+
time+" "+type+
" is not a function"
);
}
collection._callbacks[time+capitalizeFirstLetter(type)].push(fn);
};
});
return collection;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment