-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
76 lines (67 loc) · 1.95 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
'use strict';
const name = 'ERROR_FLYNN_URL'
, os = require('os')
, Slack = require('slack-node')
, isEmpty = require('is-empty')
;
module.exports = function flynn(url, opt) {
url = url || process.env[name];
if (!url) {
throw new TypeError(`Error Flynn requires parameter 'url' or env. variable ${name}`);
}
if (opt && typeof opt !== 'object') {
throw new TypeError(`'opt' cannot be a ${typeof opt}`);
}
const slack = new Slack();
slack.setWebhook(url);
return function middleware(err, req, res, next) {
if (typeof opt.skip === 'function' && opt.skip(err, req, res)) {
return next(err);
}
err.status = err.status || 500;
let attachment = Object.assign({}, {
author_name: req.headers.host,
color: (err.status < 500) ? 'warning' : 'danger',
fallback: err.message,
fields: [{
title: 'HTTP Status',
value: err.status,
short: true
}, {
title: 'Path',
value: req.url,
short: true
}, {
title: 'Environment',
value: req.app.get('env'),
short: true
}, {
title: `CPU Load (${os.cpus().length} cores)`,
value: os.loadavg().map(load => rnd(load)).join(' – '),
short: true
}],
mrkdwn_in: ['text'],
title: err.message,
text: [
['Call Stack', err.stack],
['Query String', req.query],
['Request Body', req.body]
].map(data => codeBlock(data[0], data[1])).join('')
}, opt);
slack.webhook({ attachments: [attachment] }, function(error, response) {
if (error) console.error(error);
});
next(err);
};
}
// nicely formatted string for Slack
function codeBlock(title, code) {
if (isEmpty(code)) return '';
code = (typeof code == 'string') ? code.trim() : JSON.stringify(code, null, 2);
const t = '```';
return `_${title}_${t}${code}${t}\n`;
}
// round to two decimals
function rnd(val) {
return Math.round(val * 100) / 100;
}