-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
97 lines (79 loc) · 1.64 KB
/
utils.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
93
94
95
96
97
const safe = require('fast-safe-stringify');
const SonicBoom = require('sonic-boom');
function buildSafeSonicBoom(opts) {
const stream = new SonicBoom(opts);
const errorHandler = getErrorHandler(stream);
stream.on('error', errorHandler);
return stream;
}
function fromEntries (arr) {
return arr.reduce((obj, [key, val]) => ({
...obj,
[key]: val
}), {});
}
function getErrorHandler(stream) {
return function filterBrokenPipe(err) {
if (isBrokenPipe(err)) {
stream.write = noop;
stream.end = noop;
stream.flushSync = noop;
stream.destroy = noop;
return;
}
stream.removeListener('error', filterBrokenPipe)
stream.emit('error', err)
}
}
function flip(obj) {
return fromEntries(
Object.entries(obj)
.map(reverseTuple2)
);
}
function mapValues(obj, fn) {
return fromEntries(
Object.keys(obj)
.map(fn)
);
}
function reverseTuple2([a, b]) {
return [b, a];
}
function stringify(obj) {
try {
return JSON.stringify(obj);
} catch(_) {
return safe(obj);
}
}
function isError(err) {
return err instanceof Error
}
function isNullOrUndefined(value) {
return value === null || value === undefined;
}
function isBrokenPipe(err) {
return err.code === 'EPIPE';
}
function isHttpRequest(o) {
return o !== null && o.method && o.headers && o.socket;
}
function isHttpResponse(o) {
return o !== null && typeof o.setHeader === 'function';
}
function noop() {}
module.exports = {
buildSafeSonicBoom,
flip,
fromEntries,
isError,
isBrokenPipe,
isHttpRequest,
isHttpResponse,
isNullOrUndefined,
mapValues,
noop,
reverseTuple2,
stringify,
};