forked from omrilotan/routes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (72 loc) · 1.33 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
77
78
79
const FIELDS = [
'body',
'cookies',
'signedCookies',
'params',
'query',
'originalUrl',
'baseUrl',
'url',
'protocol',
'secure',
'ip',
'ips',
'subdomains',
'path',
'hostname',
'fresh',
'stale',
'xhr',
];
/**
* Extract JSONable information from request
* @param {Request} request
* @return {Object}
*/
const getInfo = request => Object.keys(request.headers).reduce(
(accumulator, header) => Object.assign(
accumulator,
{ [`headers.${header}`]: request.headers[header] },
),
FIELDS.reduce(
(accumulator, item) => Object.assign(
accumulator,
{ [item]: request[item] },
),
{},
),
);
/**
* Create an Expressjs route handler
* @return {Function}
*/
module.exports = function client() {
/**
* An Expressjs route handler
* @param {Request} request
* @param {Response} response
* @return {undefined}
*/
return function route(request, response) {
const info = getInfo(request);
const keys = getKeys(
Object.keys(request.query),
info,
);
response
.status(200)
.type('txt')
.send(JSON.stringify(info, keys, 2));
};
};
function getKeys(requested, info) {
if (!requested.length) {
return null;
}
if (requested.includes('headers') || requested.includes('headers.*')) {
requested.push(
...Object.keys(info).filter(key => key.startsWith('headers.')),
);
}
return requested;
}