Expressjs - Is there a way to have helper function with req,res object

express, javascript, node.js

Solution

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.

Problem

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

Original source