Created
July 13, 2012 00:48
-
-
Save gcmurphy/3102077 to your computer and use it in GitHub Desktop.
Using custom middleware with a express-resource
This file contains 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 resource = require('express-resource') | |
, stuff = require('./resources/stuff') // the resource being wrapped.. | |
, _ = require('underscore') | |
var inject = (function(){ | |
if (arguments.length < 2){ | |
console.log(arguments.length) | |
throw "Invalid arguments" | |
} | |
var target = arguments[0] | |
var injected = arguments[1]; | |
return function(){ | |
return injected.apply(injected, arguments) || | |
target.apply(target, arguments) | |
} | |
}) | |
// inject the middleware for all methods of the resource | |
function applyMiddleware(theResource, theMiddleware){ | |
_.each(_.keys(theResource), function(key){ | |
theResource[key] = inject(theResource[key], theMiddleware); | |
}) | |
} | |
// in the present form of 'inject' calling next() | |
// is not supported but can be simulated with | |
// return value. | |
function requiresAuthentication(req, res){ | |
if (! req.isAuthenticated()){ | |
res.redirect('/login') | |
// return value == equivalent of not calling next | |
return true | |
} | |
// undefined return value == next() | |
} | |
var app = module.exports = express.createServer(); | |
app.configure(function(){ | |
// .. other configuration | |
// apply the middleware | |
applyMiddleware(stuff, requiresAuthentication) | |
// add the resource | |
app.resource('stuff', stuff) | |
}) | |
// That's it.. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment