|
| 1 | +import { Request, Response, NextFunction, Router } from 'express'; |
| 2 | +import { NOT_FOUND, OK, INTERNAL_SERVER_ERROR, getStatusText } from 'http-status-codes'; |
| 3 | + |
| 4 | +import { HttpError } from './error'; |
| 5 | +import errorHandler from './errorHandler'; |
| 6 | + |
| 7 | +// --------------------------------------------------- |
| 8 | +// -----------------Express Middleware---------------- |
| 9 | +// --------------------------------------------------- |
| 10 | + |
| 11 | +/** |
| 12 | + * An Express RequestHandler that handles the 404 Not Found error |
| 13 | + * @param _ Express Request object |
| 14 | + * @param __ Express Response object |
| 15 | + * @param next Express Next function |
| 16 | + */ |
| 17 | +const handleNotFound = (_: Request, __: Response, next: NextFunction) => { |
| 18 | + next(new HttpError(NOT_FOUND, 'Resource not found')); |
| 19 | +}; |
| 20 | + |
| 21 | +/** |
| 22 | + * An Express RequestHandler that responses error info to the client |
| 23 | + * @param err Http Error object |
| 24 | + * @param _ Express Request object |
| 25 | + * @param res Express Response object |
| 26 | + * @param __ Express Next function |
| 27 | + */ |
| 28 | +const handleErrors = (err: HttpError, _: Request, res: Response, __: NextFunction) => { |
| 29 | + errorHandler.handle(err); |
| 30 | + |
| 31 | + try { |
| 32 | + // check if status code exists |
| 33 | + getStatusText(err.code); |
| 34 | + |
| 35 | + res.status(err.code).send(err); |
| 36 | + } catch (error) { |
| 37 | + res.status(INTERNAL_SERVER_ERROR).send(err); |
| 38 | + } |
| 39 | +}; |
| 40 | + |
| 41 | +/** |
| 42 | + * An Express RequestHandler that responses OK for health checking |
| 43 | + * @param _ Express Request object |
| 44 | + * @param res Express Response object |
| 45 | + */ |
| 46 | +const handleHealthCheck = (_: Request, res: Response) => { |
| 47 | + res.status(OK).send('OK'); |
| 48 | +}; |
| 49 | + |
| 50 | +/** |
| 51 | + * An Express Middleware mounted /health endpoint for health checking |
| 52 | + */ |
| 53 | +const health = () => { |
| 54 | + const router = Router(); |
| 55 | + |
| 56 | + router.get('/health', handleHealthCheck); |
| 57 | + |
| 58 | + return router; |
| 59 | +}; |
| 60 | + |
| 61 | +export { |
| 62 | + handleNotFound, |
| 63 | + handleErrors, |
| 64 | + handleHealthCheck, |
| 65 | + |
| 66 | + health, |
| 67 | +}; |
0 commit comments