Search code examples
expressloopbackjsstrongloopkeen-io

Can I get to response headers in Loopback afterRemote hook?


I have a Loopback model on which I am logging requests to keen.io using the afterRemote hook. http://docs.strongloop.com/display/public/LB/Remote+hooks#Remotehooks-ctx.result

I am also using the response-time package to add the response time header to the response. https://github.com/expressjs/response-time

This is working fine, expect I cannot figure out how to get to the X-Response-Time header in the response in order to log it to keen.io.

Can I get to the response headers in any way below?

module.exports = function(Studio) {
    var isStatic = true;
    var isNotStatic = false;
    Studio.disableRemoteMethod('deleteById', isStatic); // DELETE /Studios/{id}
    Studio.disableRemoteMethod('create', isStatic); // POST /Studios
    Studio.disableRemoteMethod('upsert', isStatic); // PUT /Studios
    Studio.disableRemoteMethod('updateAll', isStatic); // POST /Studios/update
    Studio.disableRemoteMethod('updateAttributes', isNotStatic); // PUT /Studios/{id}
    Studio.disableRemoteMethod('__create__ListenNps', isNotStatic);
    Studio.disableRemoteMethod('__delete__ListenNps', isNotStatic);
    Studio.disableRemoteMethod('__destroyById__ListenNps', isNotStatic);
    Studio.disableRemoteMethod('__updateById__ListenNps', isNotStatic);

    Studio.afterRemote('*', function(ctx, affectedModelInstance, next) {
        var Keen = require('keen-js');

        var client = new Keen({
            projectId: "myid",
            writeKey: "mykey"
        });

        var queryEvent = {
            ip: ctx.req.ip,
            baseUrl: ctx.req.baseUrl,
            url: ctx.req.url,
            route: ctx.req.route,
            query: ctx.req.query,
            method: ctx.methodString,
            // response: ctx.result.???, What can I do here to get to the response headers? Specifically X-Response-Time
            keen: {
                timestamp: new Date().toISOString()
            }
        };

        client.addEvent("queries", queryEvent, function(err, res) {
            if (err) {
                console.log(err)
            } else {
                console.log(res)
            }
        });
        next();
    });
};

Solution

  • Try to use ctx.res.getHeader('X-Response-Time') method

    or

    listen the res.on('finish') event.