-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.js
55 lines (49 loc) · 1.35 KB
/
helpers.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
const Err = (status, msg) => {
let err = new Error();
err.status = status;
err.message = msg;
return err;
};
const isFunction = (functionToCheck) => {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
};
const emptyMiddleware = (req, res, next) => {next()};
/**
* Returns the function of the first route with the specified method and route fields
* @param routes
* @param method
* @param route
* @returns {function(*, *, *)}
*/
const extractMiddleware = (routes, method, route) => {
let middleware = routes.filter(r => {
return r.method === method && r.route === route
}) || [];
if (middleware.length > 0) {
return middleware[0].function;
}
else {
return emptyMiddleware;
}
};
/**
* Checks weather there is any middleware after the current one.
* If there is - the resulting data is saved to the req.crbResult object,
* otherwise it is simply sent to the client.
*
* @param afterMiddleware
* @param data
* @param req
* @param res
* @param next
*/
const sendCrbResult = (afterMiddleware, data, req, res, next) => {
if (!afterMiddleware || afterMiddleware === emptyMiddleware) {
res.send(data);
}
else {
req.crbResult = data;
next();
}
};
module.exports = {Err, isFunction, extractMiddleware, sendCrbResult};