-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
92 lines (77 loc) · 2.46 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
83
84
85
86
87
88
89
90
91
92
const defaultsDeep = require('lodash/defaultsDeep');
const Counter = require('passthrough-counter');
const Loggable = require('./lib/loggable');
const defaultOptions = require('./lib/options');
const utils = require('./lib/utils');
const httpProxy = require('./lib/proxies/http').proxy;
const httpsProxy = require('./lib/proxies/https').proxy;
const { EVENT } = Loggable;
function buildRiviere(options = {}) {
const {
errors = {},
logger,
inbound,
outbound,
traceHeaderName,
headersRegex,
headerValueCallback,
hostFieldName
} = defaultsDeep(options, defaultOptions(options));
const loggable = new Loggable(options);
if (outbound.enabled) {
const handler = options.adapter.requestProxy({
level: outbound.level,
logger,
traceHeaderName,
opts: {
headersRegex,
bodyKeys: options.bodyKeys,
bodyKeysRegex: options.bodyKeysRegex,
bodyKeysCallback: options.bodyKeysCallback,
hostFieldName,
headerValueCallback,
...outbound
}
});
httpProxy(handler);
if (outbound.https) {
httpsProxy(handler);
}
}
return async function riviere(ctx, next) {
ctx.state.riviereStartedAt = new Date().getTime();
if (inbound.enabled && inbound.request.enabled) {
utils.safeExec(() => loggable.emit(EVENT.INBOUND_REQUEST, { ctx }), logger);
}
try {
await next();
} catch (err) {
if (errors.enabled) {
utils.safeExec(() => loggable.emit(EVENT.UNEXPECTED_ERROR, { ctx, err }), logger);
}
if (typeof errors.callback === 'function') {
await errors.callback(err, ctx);
}
} finally {
if (inbound.enabled) {
const length = ctx.response.length;
let counter;
if (!length && ctx.body && ctx.body.readable) {
ctx.body = ctx.body.pipe((counter = Counter())).on('error', ctx.onerror);
}
const res = ctx.res;
res.once('finish', responseFinished);
res.once('close', responseFinished);
function responseFinished(event) {
res.removeListener('finish', responseFinished);
res.removeListener('close', responseFinished);
ctx.state.calculatedContentLength = counter ? counter.length : length;
//Fire event to write log
utils.safeExec(() => loggable.emit(EVENT.OUTBOUND_RESPONSE, { ctx }), logger);
}
}
}
};
}
buildRiviere.riviere = buildRiviere;
module.exports = buildRiviere;