-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
50 lines (39 loc) · 1.2 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
var onFinished = require('on-finished');
// sets up lyticsServer listening on 5151
var lyticsServer = require('./server/server');
// set up socket from host app to 5151
var socketClient = require('./host/socket');
module.exports = function(options) {
return function (req, res, next) {
req._startAt = process.hrtime();
req._startTime = new Date;
req._remoteAddress = getIp(req);
function logRequest() {
console.log("REQ", typeof req.query);
console.log("BODY", req.body);
var stringifiedQuery = JSON.stringify(req.query);
var requestData = {
url: req.url,
method: req.method,
requestTime: req._startTime,
duration: getElapsedInMs(req._startAt),
ip: "" + getIp(req),
body: req.body,
query: stringifiedQuery
};
socketClient.emit('request:log', requestData);
}
onFinished(res, logRequest);
next();
}
function getElapsedInMs(hrTime) {
var elapsedHrTime = process.hrtime(hrTime);
return elapsedHrTime[0] * 1e9 + elapsedHrTime[1];
}
function getIp(req) {
return req.ip
|| req._remoteAddress
|| (req.connection && req.connection.remoteAddress)
|| undefined;
}
}