]>
Commit | Line | Data |
---|---|---|
4e50b6a1 | 1 | import { eachSeries } from 'async' |
a2431b7d | 2 | import { NextFunction, Request, RequestHandler, Response } from 'express' |
eb080476 C |
3 | |
4 | // Syntactic sugar to avoid try/catch in express controllers | |
5 | // Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016 | |
a2431b7d C |
6 | |
7 | export type RequestPromiseHandler = (req: Request, res: Response, next: NextFunction) => Promise<any> | |
8 | ||
9 | function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) { | |
eb080476 | 10 | return (req: Request, res: Response, next: NextFunction) => { |
4e50b6a1 C |
11 | if (Array.isArray(fun) === true) { |
12 | return eachSeries(fun as RequestHandler[], (f, cb) => { | |
13 | Promise.resolve(f(req, res, cb)) | |
14 | .catch(next) | |
15 | }, next) | |
16 | } | |
17 | ||
18 | return Promise.resolve((fun as RequestHandler)(req, res, next)) | |
eb080476 C |
19 | .catch(next) |
20 | } | |
21 | } | |
22 | ||
23 | // --------------------------------------------------------------------------- | |
24 | ||
25 | export { | |
26 | asyncMiddleware | |
27 | } |