Created
March 16, 2015 19:56
-
-
Save formula1/5fd75e9ffdd3c3b2f660 to your computer and use it in GitHub Desktop.
On the fly Middleware without editing the callback array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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