-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (69 loc) · 1.84 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
80
81
82
const http = require('http');
const chalk = require('chalk');
const originalOutReq = http.request;
const COLORS = {
ok: 'green',
error: 'red',
dot: 'yellow'
};
const SIGNS = {
arrow: '->',
ok: '✓',
error: '✘',
dot: '●'
};
function getRequestUrl(options) {
const protocol = options.protocol || 'http';
const host = options.host || options.hostname || 'localhost';
return options.href || `${protocol}//${host}${options.path}`;
}
function _defaultHandleRequest(options, req) {
const url = getRequestUrl(options);
const startTime = Number(new Date());
console.log(`${chalk.grey(`${SIGNS.arrow} ${req.method}`)} ${url}`);
req.on('response', res => {
let log = url;
let sign;
if(res.statusCode >= 300 && res.statusCode < 500){
sign = 'dot';
if(res.headers.location){
log += chalk.grey(` ${SIGNS.arrow} ${res.headers.location}`);
}
}else if(res.statusCode >= 500){
sign = 'error';
}else{
sign = 'ok';
}
const duration = Number(new Date()) - startTime;
const prefix = chalk[COLORS[sign]](`${SIGNS[sign]} ${res.statusCode}`);
console.log(`${prefix} ${log} ${chalk.grey(`${duration}ms`)}`);
});
}
function enable(params, callback) {
let handleRequest = callback;
params = params || {};
params.ignore = params.ignore || [];
if (typeof callback === 'function') {
handleRequest = callback;
} else {
handleRequest = _defaultHandleRequest;
}
http.request = function (options, cb) {
const req = originalOutReq.call(this, options, cb);
const reqUrl = getRequestUrl(options);
for (const ignored of params.ignore) {
if (typeof ignored === 'string' && reqUrl === ignored || ignored instanceof RegExp && ignored.test(reqUrl)) {
return req;
}
}
handleRequest(options, req);
return req;
};
}
function disable() {
http.request = originalOutReq;
}
module.exports = {
enable: enable,
disable: disable
};