-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathparseRoutes.js
161 lines (145 loc) · 4.6 KB
/
parseRoutes.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const validateFields = require('./validateFields');
const setDefaults = require('./validateFields/setDefaults').middleware;
const applyModifiers = require('./validateFields/applyModifiers').middleware;
const { handleVisibility, isVisible } = require('./visibility');
module.exports = (
{
validatePrivilege,
validateVisibility,
unwrapResponse: configUnwrapResponse,
middleware,
corsEnabled,
corsOptions,
},
service
) => {
const {
routes,
schema,
postSchema = null,
middleware: serviceMiddleware = [],
keepAlive = false,
} = service;
const app = express();
app.use(helmet());
app.disable('x-powered-by');
if (corsEnabled) {
app.options('*', cors(corsOptions));
app.use(cors(corsOptions));
}
app.use(express.json());
if (keepAlive) {
app.get('/heartbeat', (_, res) =>
res.status(200).send({ status: 'success' })
);
}
const router = new express.Router();
routes.forEach(
({
path,
method,
function: toExecute,
privilege = 'any',
ignoreBody = false,
schema: routeSchema = null,
middleware: routeMiddleware = [],
visibility,
unwrapResponse: routeUnwrapResponse,
}) => {
const unwrapResponse = routeUnwrapResponse || configUnwrapResponse;
if (ignoreBody) {
router[method](
`${path}`,
validatePrivilege(privilege),
validateVisibility(visibility),
...middleware,
...serviceMiddleware,
...routeMiddleware,
handleRequest(privilege, visibility, schema, unwrapResponse, toExecute)
);
} else if (method === 'post' && (routeSchema || postSchema || schema)) {
router[method](
`${path}`,
validatePrivilege(privilege),
validateVisibility(visibility),
...middleware,
...serviceMiddleware,
...routeMiddleware,
validateFields(routeSchema || postSchema || schema),
setDefaults(schema),
applyModifiers(service),
handleRequest(privilege, visibility, schema, unwrapResponse, toExecute)
);
} else if (method === 'put' && (routeSchema || schema)) {
router[method](
`${path}`,
validatePrivilege(privilege),
validateVisibility(visibility),
...middleware,
...serviceMiddleware,
...routeMiddleware,
validateFields(routeSchema || schema),
applyModifiers(service),
handleRequest(privilege, visibility, schema, unwrapResponse, toExecute)
);
} else {
router[method](
`${path}`,
validatePrivilege(privilege),
validateVisibility(visibility),
...middleware,
...serviceMiddleware,
...routeMiddleware,
applyModifiers(service),
handleRequest(privilege, visibility, schema, unwrapResponse, toExecute)
);
}
}
);
app.use(`/${service.basePath}`, router);
app.use('/', router);
return app;
};
const withResponse = (schema, handler, unwrapResponse) => async (req, res) => {
try {
const result = await handler(req, res);
if (!Array.isArray(result)) return res.end();
const [status, message, headers = {}] = result;
const messageWithVisibility = req.mode
? handleVisibility(req.mode, schema, unwrapResponse, message)
: message;
return res.status(status).set(headers).send(messageWithVisibility);
} catch (error) {
console.error(error);
return res
.status(error.statusCode || 500)
.send({ status: 'error', error: error.message });
}
};
const handleRequest = (privilege, visibility, schema, unwrapResponse, callback) => (req, res) =>
withResponse(schema, getHandlerForRole(privilege, visibility, callback, req), unwrapResponse)(
req,
res
);
const getHandlerForRole = (privilege, visibility, callback, req) => {
if (req.mode && !isVisible(visibility, req.mode)) {
console.error('rejecting request due to lack of visibility', visibility, req.mode);
return sendError;
}
if (typeof privilege !== 'object') {
return callback;
}
if (req.headers.role && typeof privilege[req.headers.role] === 'function') {
return privilege[req.headers.role];
}
if (typeof privilege.any === 'function') {
return privilege.any;
}
console.error('rejecting request due to lack of privilege', privilege, visibility, req.headers.role);
return sendError;
};
const sendError = (_req, res) =>
res.status(500).send({ status: 'error', error: 'internal error' });