hapijs

Introducing hapi-response-time

hapi-response-time plugin will help in measuring the time taken by any api endpoint to generate the response & can be handy while debugging.

Introducing hapi-response-time
hapi-response-time


In the last post, we had discussed about the quick way of creating REST APIs with HapiJS; I am very much delighted to introduce the hapi-response-time plugin.

This plugin will help in measuring the time taken by any api endpoint to generate the response and can be handy from the debugging point of view.

To set it up, you would need to install it as dependency and register the plugin in the server initialization.

Adding Dependency

npm i -S hapi-response-time

Installation

server.register(require('hapi-response-time'), err => { 
    if(err) { 
        throw err;
    }
});

And now, all the requests will have the following headers:

x-req-start → 1484305451729
x-res-end → 1484305451738
x-response-time → 9

The plugin is available on github to see into: https://github.com/pankajpatel/hapi-response-time

To test it out, you can use following code:

'use strict';

const Hapi = require('@hapi/hapi');

const server = Hapi.server();

try {
    server.register({
        plugin: require('../index')
    });

    server.route([
        {
            method: 'GET',
            path: '/john',
            handler: (req, h) => h.response('Hello John!'),
        }, {
            method: 'GET',
            path: '/timeout',
            handler: async function (request, h) {
                await (() => new Promise(
                    resolve => setTimeout(resolve, 1000)
                ))();
                return h.response('Response after 1 second');
            }
        }
    ]);
} catch (error) {

    console.log(error);
    process.exit(1);
}

module.exports = server;

So use it in your hapijs based projects and let us know about your feedback in comments or github issue and if you like it or find it useful, please star it on github.

Star
Hey There! You have made it this far.
Would you like to subscribe via email?
You've successfully subscribed to Time to Hack!
Close