-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathServerUtils.ts
37 lines (34 loc) · 1.42 KB
/
ServerUtils.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
import { ErrorRequestHandler, NextFunction, Request, Response } from 'express';
import { ModelError } from '../openapi';
export type AsyncHandler = (req: Request, res: Response) => Promise<unknown>;
/**
* Server side utility methods.
*/
export class ServerUtils {
public static asyncMiddleware =
(fn: AsyncHandler) =>
(req: Request, res: Response, next: NextFunction): void => {
try {
Promise.resolve(fn(req, res))
.then((response) => res.json(response))
.catch((e) => {
// next(e) should do the trick, but for some reason it doesn't on the agent???
return ServerUtils.errorHandler()(e, req, res, next);
});
} catch (e) {
// next(e) should do the trick, but for some reason it doesn't on the agent???
return ServerUtils.errorHandler()(e, req, res, next);
}
};
public static errorHandler(): ErrorRequestHandler {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return (err, req, res, next) => {
const defaultErrorObject: ModelError = {
code: err.code || 0,
message: err.message || 'Unknown Error',
retriable: false,
};
return res.status(err.status || 500).json(err.body || defaultErrorObject);
};
}
}