Skip to content

Commit

Permalink
Add addHeader option that adds X-Response-Time header
Browse files Browse the repository at this point in the history
  • Loading branch information
phil-r committed May 17, 2019
1 parent c466af0 commit 5f8e89a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
});
```

Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand Down
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 5f8e89a

Please sign in to comment.