UNPKG

librato-express

Version:

Middleware for expressjs to send metrics to Librato.

72 lines (59 loc) 2.04 kB
/** * Created by Dmitry on 11/17/2014. */ /** * Express middleware functions. Use these to hook into URL routes. * @type {{use: Function, routeCount: Function, routeTiming: Function}} */ module.exports = function ( Metrics ) { return { routeCount : function ( options, filter ) { var counter = new Metrics.Counter(options); var filterFnc = getFilterWrapper(filter); return function (req, res, next) { counter.increment(1, filterFnc ? filterFnc(req) : null); if ( next ) next(); } }, routeTiming : function ( options, filter ) { var timing = new Metrics.Timing(options); var filterFnc = getFilterWrapper(filter); return function (req, res, next) { if (req._librato_express) { req._librato_express = Date.now(); } var _send = res.send; res.send = function () { res.send = _send; res.send.apply(this, arguments); timing.measure(req._librato_express, filterFnc ? filterFnc(req) : null); }; if ( next ) next(); } } }; }; // ========================================================== // Helper functions // ========================================================== function getFilterWrapper (filter) { var type = typeof filter; if (type === 'string') { return function (req) { return _default_filter(filter.match(/(\w+)/g), req); } } else if (type === 'function') { return filter; } else if (!!filter) { throw new Error('Invalid librato-express filter'); } } function _default_filter ( filter, req ) { var res = req[ filter[0] ]; for(var i = 1, len = filter.length; i < len; i++) { res = res[ filter[i] ]; } return res; }