This repository has been archived by the owner on Jan 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
getExpressMiddleware.js
90 lines (73 loc) · 2.86 KB
/
getExpressMiddleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Removes ":", heading/trailing / and replaces / by _ in a given route name
function sanitize(routeName) {
return routeName.replace(/:/g, "").replace(/^\/|\/$/g, "").replace(/\//g, "_");
}
// Extracts a route name from the request or response
function findRouteName(req, res) {
// Did we get a hardcoded name, or should we figure one out?
if (res.locals && res.locals.statsdUrlKey) {
return res.locals.statsdUrlKey;
}
if (req.route && req.route.path) {
var routeName = req.route.path;
if (Object.prototype.toString.call(routeName) === '[object RegExp]') {
routeName = routeName.source;
}
if (req.baseUrl) {
routeName = req.baseUrl + routeName;
} else if (routeName === '/') {
routeName = 'root';
}
if (req.params) {
Object.keys(req.params).forEach(function(key) {
if (req.params[key] === '') return;
routeName = routeName.replace(req.params[key], ':' + key);
});
}
// Appends the HTTP method
return req.method + '_' + sanitize(routeName);
}
}
/*
* Return express middleware that measures overall performance.
*
* The `prefix` defaults to `''` (but is currently mandatory). The
* `options`-argument is optional.
* * You can set `timeByUrl`, that add a timer per URL template (ex:
* `/api/:username/:thingie`). This can be changed run-time by setting
* `res.locals.statsdUrlKey`.
* * Add a `function(client, startTime, req, res)` in `onResponseEnd` that
* will be called at the very end.
*/
function factory(parentClient) {
return function (prefix, options) {
options = options || {};
var client = parentClient.getChildClient(prefix || '');
var timeByUrl = options.timeByUrl || false;
var notFoundRouteName = options.notFoundRouteName || 'unknown_express_route';
var onResponseEnd = options.onResponseEnd || undefined;
return function (req, res, next) {
var startTime = new Date();
// Shadow end request
var end = res.end;
res.end = function () {
res.end = end;
end.apply(res, arguments);
var urlPrefix = '';
// Time by URL?
if (timeByUrl) {
urlPrefix += '.';
urlPrefix += findRouteName(req, res) || notFoundRouteName;
client.increment('response_code' + urlPrefix + '.' + res.statusCode);
}
client.increment('response_code.' + res.statusCode);
client.timing('response_time' + urlPrefix, startTime);
if (onResponseEnd) {
onResponseEnd(client, startTime, req, res);
}
};
next();
};
};
}
module.exports = factory;