-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (65 loc) · 2.04 KB
/
index.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
'use strict';
const universalAnalytics = require('universal-analytics');
const StatsD = require('node-statsd');
let statsd;
try {
statsd = new StatsD({
host: process.env.STATSD_HOST || 'localhost',
port: process.env.STATSD_PORT || 8125,
prefix: process.env.STATSD_PREFIX || 'turbasen.',
});
} catch (err) {
console.error(err); // eslint-disable-line no-console
}
module.exports = () => (req, res, next) => {
try {
// Log to GA
const ua = universalAnalytics(process.env.GA_ID);
const requestParams = module.exports.getRequestParams(req);
ua.pageview(requestParams).send((err) => {
if (err) {
console.error(err); // eslint-disable-line no-console
}
});
// Log to statsd
statsd.increment('http.request.count');
if (req.user.type === 'token') {
const appName = req.user.app.replace(/[^a-zA-Z0-9]/g, '');
statsd.increment(`http.request.count.${appName}`.toLowerCase());
} else {
statsd.increment('http.request.count.anonymous');
}
} catch (err) {
console.error(err); // eslint-disable-line no-console
} finally {
next();
}
};
module.exports.getRequestParams = function getParams(req) {
const gaParams = {
// GA version
v: 1,
// Document Path
dp: req.path.replace(/\/$/, ''),
// Content Group 1
cg1: req.path.split('/').find(str => str.length > 0),
// Custom dimension 1: Collection
cd1: req.path.split('/').find(str => str.length > 0),
// Custom dimension 2: Query params
cd2: req.originalUrl.split('?')[1],
// Custom metric 1: RateLimit usage in percent
cm1: parseInt((100 - ((req.user.remaining / req.user.limit) * 100)), 10),
};
if (req.user.type === 'token') {
Object.assign(gaParams, {
uid: req.user.provider,
cid: req.user.provider,
an: req.user.app,
aid: req.user._id, // eslint-disable-line no-underscore-dangle
});
} else if (req.user.type === 'ip') {
// Don't add any details for anonymous users
}
return gaParams;
};
module.exports.middleware = module.exports();