diff --git a/README.md b/README.md index 895deae..b0a8919 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,8 @@ const initStats = require('@phil-r/stats'); const { statsMiddleware, getStats } = initStats({ endpointStats: true, complexEndpoints: ['/user/:id'], - customStats: true + customStats: true, + addHeader: true }); ``` @@ -63,6 +64,13 @@ function handler(req, res) { } ``` +##### addHeader + +Defaults to `false` + +Adds `X-Response-Time` header to all responses, can be used to replace +[`expressjs/response-time`](https://github.com/expressjs/response-time) + ## Full example Here is the example of usage in express app @@ -74,7 +82,8 @@ const initStats = require('@phil-r/stats'); const { statsMiddleware, getStats } = initStats({ endpointStats: true, complexEndpoints: ['/user/:id'], - customStats: true + customStats: true, + addHeader: true }); app.use(statsMiddleware); diff --git a/index.js b/index.js index 27656cd..33e56b4 100644 --- a/index.js +++ b/index.js @@ -73,6 +73,12 @@ function initMiddleware(opts = {}) { onHeaders(res, () => { const time = hrTimeToMs(process.hrtime(requestStart)); + if (opts.addHeader) { + if (!res.getHeader('X-Response-Time')) { + res.setHeader('X-Response-Time', `${time.toFixed(0)}ms`); + } + } + stats.totalTime += time; stats.count++; stats.averageTime = stats.totalTime / stats.count;