Skip to content

Instantly share code, notes, and snippets.

@formula1
Created March 9, 2015 19:23
Show Gist options
  • Save formula1/4edfbca5b5de86f07b44 to your computer and use it in GitHub Desktop.
Save formula1/4edfbca5b5de86f07b44 to your computer and use it in GitHub Desktop.
Middleware for waterline
var async = require("async");
function MIDDLEWARE_FN(type,time){
return function(values,next){
async.series(this.middleware[type][time],function(fn,next){
fn(values,next);
},function(err){
cb(err,values);
});
};
}
var MIDDLEWARE_TYPES = [
"validate",
"create",
"update",
"destroy"
];
var MIDDLEWARE_TIMINGS = [
"before",
"after"
];
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function stdExtend(schema){
schema.middleware = {};
MIDDLEWARE_TIMINGS.forEach(function(time){
schema[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+" "+time+
" is not a function"
);
}
this[type][time].push(fn);
};
});
MIDDLEWARE_TYPES.forEach(function(type){
schema.middleware[type] = {};
MIDDLEWARE_TIMINGS.forEach(function(time){
var dLabel = time+capitalizeFirstLetter(type);
schema.middleware[type][time] = !schema[dLabel]?[]:
!Array.isArray(schema[dLabel])?[schema[dLabel]]:
schema[dLabel];
schema.middleware[type][time].forEach(function(fn,i){
if(typeof fn != "function"){
throw new Error(
"callback["+i+"] supplied for "+
time+" "+type+
" is not a function"
);
}
});
schema[dLabel] = MIDDLEWARE_FN(type,time);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment