How to have a helper function for routes with the req,res object built into it. for eg. if I have send an error or success message in json I have the following lines of code
console.log(err)
data.success = false
data.type = 'e'
data.txt = "enter a valid email"
res.json data
I am planning to put this in a helper function like this
global.sendJsonErr = (msg)->
data.success = false
data.type = 'e'
data.txt = msg
res.json data
But I don't have res object in the helper function how can I can get those objects, other than passing it around. As there would be moving more repeating code I would want to take out of the route. It is more kind of macro rather than a function module. thanks
I've written custom middleware to do similar things. Something like this:
app.use(function(req, res, next) {
// Adds the sendJsonErr function to the res object, doesn't actually execute it
res.sendJsonErr = function (msg) {
// Do whatever you want, you have access to req and res in this closure
res.json(500, {txt: msg, type: 'e'})
}
// So processing can continue
next()
})
And now you can do this:
res.sendJsonErr('oh no, an error!')
See http://www.hacksparrow.com/how-to-write-midddleware-for-connect-express-js.html for more info on writing custom middleware.
I don't know exactly your use case but you may want to use a middle ware.
Some examples defined here: http://www.hacksparrow.com/how-to-write-midddleware-for-connect-express-js.html but you can have a function with req and res as argument, called at each requests.
app.use(function(req, res) {
res.end('Hello!');
});
You also have access to a third argument to pass the hand to the next middle ware:
function(req, res, next) {
if (enabled && banned.indexOf(req.connection.remoteAddress) > -1) {
res.end('Banned');
}
else { next(); }
}