Skip to content

Commit

Permalink
fix(timer): measures time taken more accurately (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcus Gartner authored Jul 15, 2019
1 parent 312cef3 commit 0f6131b
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ exports.register = (server, options, next) => {

server.ext('onPostAuth', (request, reply) => {
let startTime;
let timeDiff;

const routeSettings = request.route.settings.plugins.rateLimit;

request.plugins['hapi-rate-limiter'] = { rate: null };
Expand All @@ -76,13 +78,22 @@ exports.register = (server, options, next) => {
rate.reset = Math.floor(new Date().getTime() / 1000) + ttl;
request.plugins['hapi-rate-limiter'].rate = rate;

if (options.timer) {
timeDiff = process.hrtime(startTime);
}

if (remaining < 0) {
return reply(options.overLimitError(rate));
}

return reply.continue();
})
.catch((err) => {

if (options.timer) {
timeDiff = process.hrtime(startTime);
}

// If the Redis call failed, call the onRedisError function,
// then continue with the request.
if (options.onRedisError) {
Expand All @@ -93,8 +104,7 @@ exports.register = (server, options, next) => {
})
.finally(() => {
if (options.timer) {
const diff = process.hrtime(startTime);
const milliseconds = diff[0] * MS_PER_SECOND + diff[1] / NS_PER_MS;
const milliseconds = timeDiff[0] * MS_PER_SECOND + timeDiff[1] / NS_PER_MS;

options.timer(milliseconds);
}
Expand Down

0 comments on commit 0f6131b

Please sign in to comment.