— loopback, keen.io, node.js, javascript — 1 min read
I've been experimenting with LoopBack recently, using it to prototype an API. It really is quite amazing how quickly you can get a full-fledged API up and running with LoopBack. Just follow the getting started guide and you’ll see what I mean.
After getting a pretty decent API up and running, I began testing a few different ways of logging API requests. I still haven't quite settled on the way that I want to do this yet, but one issue that I did encounter was trying to get the response time of the call from expressjs/response-time.
Response-time is a great, little Node.js module that automatically adds an X-Response-Time header to your responses to indicate the time in milliseconds that the request took.
The issue that I was running into was that I could not figure out how to properly get to that header in the LoopBack afterRemote method that I was using to log requests. Thanks to an SO user, however, I was able to eventually get to what I wanted. The key was that the response wasn't available when I was trying to log the query -I needed to use the res.on('finish')
event to get the response headers.
1var Keen = require("keen-js");23module.exports = function (myModel) {4 myModel.afterRemote("*", function (ctx, affectedModelInstance, next) {5 // Listen to the finish event of the response to wait6 // for the response to be available7 ctx.res.on("finish", function () {8 var client = new Keen({9 projectId: "keenprojectid",10 writeKey: "keenwritekey",11 });1213 var queryEvent = {14 ip: ctx.req.ip,15 baseUrl: ctx.req.baseUrl,16 url: ctx.req.url,17 route: ctx.req.route,18 query: ctx.req.query,19 method: ctx.methodString,20 // Here's the header that I wanted to grab21 responseTime: Number(ctx.res._headers["x-response-time"]),22 keen: {23 timestamp: new Date().toISOString(),24 },25 };2627 client.addEvent("queries", queryEvent, function (err, res) {28 if (err) {29 console.log(err);30 } else {31 console.log(res);32 }33 });34 });3536 // Don't forget to call next37 next();38 });39};