This repository has been archived by the owner on Jan 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (68 loc) · 2.05 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
const {validationResult} = require("express-validator/check");
const Raven = require('raven');
let newrelic;
const handle200 = (req, res, next, data) => {
res.status(200).json(data);
};
const handle404 = (req, res, next) => {
res.status(404).json({
message: 'Not found'
});
};
const handle400 = (req, res, next, data) => {
res.status(400).json({
message: 'Bad Request',
data,
});
};
const handle500 = (req, res, next, err) => {
try {
if (raven) raven.captureException(err);
} catch (sentryErr) {
console.debug('Unable to use Sentry on error: ', err, sentryErr);
}
if (newrelicConfig.enabled) newrelic.noticeError(err);
next(err);
};
let raven;
let newrelicConfig = {};
module.exports.setupAction = ({config}) => {
const options = {
release: config.package.version,
environment: config.environment,
autoBreadcrumbs: true,
captureUnhandledRejections: true,
tags: {
platform: config.package.name,
},
};
if (!raven && config.sentry && config.sentry.enabled) {
Raven.config(config.sentry.dsn, options).install();
raven = Raven;
}
if (!newrelic && config.newrelic && config.newrelic.enabled) {
newrelicConfig = config.newrelic;
newrelic = require('newrelic');
}
};
module.exports.action = (actionFn) =>
(req, res, next) => {
if (newrelicConfig && newrelicConfig.enabled && req.route) {
newrelic.setControllerName(req.route);
}
const errors = validationResult(req);
if (!errors.isEmpty()) {
return handle400(req, res, next, errors.array());
}
return actionFn({req, res, next, raven, newrelic})
.then((data) => {
if (data === null) {
handle404(req, res, next);
} else {
handle200(req, res, next, data);
}
})
.catch((err) => {
handle500(req, res, next, err);
});
};