-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
49 lines (43 loc) · 1.39 KB
/
handler.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
import createError from "http-errors";
export const serverError = (err, req, res, next) => {
const error = { message: "An error occurred" };
let status = 500;
if (err.statusCode) {
status = err.statusCode;
error.message = err.message;
} else if (err.status) {
status = err.status;
error.message = err.message;
} else if (err instanceof Error) {
error.message = err.message;
}
res.status(status).json(error);
};
export const notFoundError = (req, res, next) => {
const error = createError(404);
next(error);
};
export const throwForbiddenError = (permissions, req) => {
if (!req.permissions || !req.permissions.can || typeof req.permissions.can !== 'function') {
throw createError(500, 'Error in access control');
}
if (!permissions.some(permission => req.permissions.can(permission))) {
throw createError(403, `Forbidden access for role ${req.user.role}`);
}
};
export const requestHandler = (controllerClass, controller, permissions) => {
async function handler(req, res, next) {
try {
if (Array.isArray(permissions) && permissions.length > 0) {
throwForbiddenError(permissions, req);
}
const result = await controller.bind(controllerClass)(req, res, next);
if (!res.headersSent && result) {
res.status(res.locals.status || 200).json({ result });
}
} catch (e) {
next(e);
}
}
return handler;
};