0

I want to kinda override default next in Restify. E.g. now i have code like

server.post('/names', function (req, res, next) {
  names = req.params.names;
  if (!Array.isArray(names)) {
    return next(new restify.errors.BadRequestError('names field is wrong or missing'));
  }
  res.send({ code: "OK" });
  return next();
});

I want it to be just

server.post('/names', function (req, res, next) {
  names = req.params.names;
  if (!Array.isArray(names)) {
    return next(new restify.errors.BadRequestError('names field is wrong or missing'));
  }
  // Add names to DB
  return next();
});

Where next (for non-error results) is like

function next(res) {
  if (!body.hasOwnProperty("code")) {
    body["code"] = "OK";
  }
  res.send(body);
}

What is the best way to implement this?

Ximik
  • 2,435
  • 3
  • 27
  • 53
  • Your code is missing `var` keywords on every variable declaration. This is bad because without `var` everything becomes global. Double-check your code, every variable declaration without `var` is a bug waiting to happen. Tools like [jshint](http://jshint.com/) help find these mistakes. – Tomalak Apr 25 '16 at 19:16
  • Apart from that your question is unclear. Don't explain what you think the code should look like, explain what you want to achieve. – Tomalak Apr 25 '16 at 19:19
  • It's just sketch. The idea is just sending result object to the last next instead of doing res.send + next. – Ximik Apr 25 '16 at 19:22

1 Answers1

0

I think you may be looking for a handler that executes after all other handlers in the chain are done. Consider the "after" event handler. In the documentation they show an example for audit logging.

You should be able to use that same thing to update the response body as needed. The code might look something like this...

server.on('after', function (request, response, route, error) {});

Keep in mind, this still requires you to return next(); from all of the other handlers in the chain.

Mark Maruska
  • 1,210
  • 12
  • 13