-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathrequest-middleware.ts
59 lines (54 loc) · 1.55 KB
/
request-middleware.ts
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
import {
RequestHandler, Request, Response, NextFunction
} from 'express';
import Joi from 'joi';
import BadRequest from '../errors/bad-request';
import logger from '../logger';
/**
* Helper to get message from Joi
* @param error Error form Joi
* @returns Message from Joi, if available
*/
const getMessageFromJoiError = (error: Joi.ValidationError): string | undefined => {
if (!error.details && error.message) {
return error.message;
}
return error.details && error.details.length > 0 && error.details[0].message
? `PATH: [${error.details[0].path}] ;; MESSAGE: ${error.details[0].message}` : undefined;
};
interface HandlerOptions {
validation?: {
body?: Joi.ObjectSchema
}
};
/**
* This router wrapper catches any error from async await
* and throws it to the default express error handler,
* instead of crashing the app
* @param handler Request handler to check for error
*/
export const requestMiddleware = (
handler: RequestHandler,
options?: HandlerOptions,
): RequestHandler => async (req: Request, res: Response, next: NextFunction) => {
if (options?.validation?.body) {
const { error } = options?.validation?.body.validate(req.body);
if (error != null) {
next(new BadRequest(getMessageFromJoiError(error)));
return;
}
}
try {
handler(req, res, next);
} catch (err) {
if (process.env.NODE_ENV === 'development') {
logger.log({
level: 'error',
message: 'Error in request handler',
error: err
});
}
next(err);
};
};
export default requestMiddleware;