0

I am currently developing API server using node.js and express.js. I want to know information about how long does each api take to response. For that, I am using response-time to get time taken.

app.use(responseTime(function(req, res, time) {
  var log = {
    "date" : new Date(),
    "os" : req.headers['user-agent'],                 
    "requestUrl" : req.originalUrl,
    "ipAddress" : req.ip,
    "requestMethod" : req.method,
    "statusCode" : res.statusCode,
    "statusMessage" : "",
    "timeTaken" : Math.floor(time),
    "data" : JSON.stringify(req.body)
  };
  // save log data
}));

For every API response, I use json method for error i.e. res.status(400).json({message: 'Something'}).

How can I retrive that json error message inside responseTime function?

Khay
  • 1,530
  • 13
  • 28

2 Answers2

2

Unfortunately, I don't think this is possible with this middleware. The response-time middleware stops timing just before the headers are sent (using onHeaders) which I believe is before the body is set on the response object. I'm not even sure if the body is ever set on the response object.

You could try using something like mung, in combination with `response-time?

MrWillihog
  • 2,586
  • 19
  • 17
1

The reason you can't access like that is because the response body is never set on the response object. Instead it is streamed directly to the client. So you'll have to manually collect the response body into the response object.

The easiest solution would be to always pass the body(error json in your case) into a custom field inside response object. For example in your route, add something like this:

get('/myErrorRoute', function(req, res, next) {
  var errJson = {message: 'Something'};
  res.myCustomField = errJson;
  res.status(400).json(errJson);
});

Then access it in your middleware like this:

app.use(responseTime(function(req, res, time) {
  var log = {
    "date" : new Date(),
    "os" : req.headers['user-agent'],                 
    "requestUrl" : req.originalUrl,
    "ipAddress" : req.ip,
    "requestMethod" : req.method,
    "statusCode" : res.statusCode,
    "statusMessage" : "",
    "timeTaken" : Math.floor(time),
    "data" : JSON.stringify(req.body)
  };
  // acces your custom field
  console.log(res.myCustomField);
}));

Or if you are daring, monkey patch the json() method to do so. example here