2

I need to build a restify middleware that operates on the body of the response that a handler produced. It seems that anything I pass to server.use is called before the handler.

I tried calling next() and then checking the res object, but was unsuccessful.

Also, this answer might be what I seek, but I don't really need to use the router nor do I know how to do it.

Community
  • 1
  • 1
Bruno Brant
  • 8,226
  • 7
  • 45
  • 90

1 Answers1

3

You could use a formatter.

I don't think using a middleware will work. Restify ignores middleware once it finds a proper route handler (.get .put .post etc). You could use a formatter instead. http://restify.com/#content-negotiation

When you make a restify server you can specify formatters. These are invoked after a route handler calls res.send(). This will allow you to manipulate the body before sending it back.

var server = restify.createServer({
  formatters: {
    'application/foo': function formatFoo(req, res, body, cb) {
         // body is what was sent with the response, you can edit it here.
         // You finish processing by calling cb(null, body).  
         // Just be sure that you body is properly stringified.
         // See the restify docs above for more information.
    }
  }
});
carchase
  • 493
  • 6
  • 18
  • It's there a way to call the default formatter from within a custom one? – Bruno Brant May 14 '17 at 05:26
  • I don't think so. The example formatter provided in the docs is the default formatter, so you could just append your custom logic to that one. – carchase May 14 '17 at 16:37