diff options
Diffstat (limited to 'server/middlewares/async.ts')
-rw-r--r-- | server/middlewares/async.ts | 19 |
1 files changed, 12 insertions, 7 deletions
diff --git a/server/middlewares/async.ts b/server/middlewares/async.ts index 9d0193536..7e131257d 100644 --- a/server/middlewares/async.ts +++ b/server/middlewares/async.ts | |||
@@ -1,21 +1,26 @@ | |||
1 | import { eachSeries } from 'async' | 1 | import Bluebird from 'bluebird' |
2 | import { NextFunction, Request, RequestHandler, Response } from 'express' | 2 | import { NextFunction, Request, RequestHandler, Response } from 'express' |
3 | import { ValidationChain } from 'express-validator' | 3 | import { ValidationChain } from 'express-validator' |
4 | import { ExpressPromiseHandler } from '@server/types/express-handler' | 4 | import { ExpressPromiseHandler } from '@server/types/express-handler' |
5 | import { retryTransactionWrapper } from '../helpers/database-utils' | 5 | import { retryTransactionWrapper } from '../helpers/database-utils' |
6 | 6 | ||
7 | // Syntactic sugar to avoid try/catch in express controllers | 7 | // Syntactic sugar to avoid try/catch in express controllers/middlewares |
8 | // Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016 | ||
9 | 8 | ||
10 | export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler | 9 | export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler |
11 | 10 | ||
12 | function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) { | 11 | function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) { |
13 | return (req: Request, res: Response, next: NextFunction) => { | 12 | return (req: Request, res: Response, next: NextFunction) => { |
14 | if (Array.isArray(fun) === true) { | 13 | if (Array.isArray(fun) === true) { |
15 | return eachSeries(fun as RequestHandler[], (f, cb) => { | 14 | return Bluebird.each(fun as RequestPromiseHandler[], f => { |
16 | Promise.resolve(f(req, res, err => cb(err))) | 15 | return new Promise<void>((resolve, reject) => { |
17 | .catch(err => next(err)) | 16 | return asyncMiddleware(f)(req, res, err => { |
18 | }, next) | 17 | if (err) return reject(err) |
18 | |||
19 | return resolve() | ||
20 | }) | ||
21 | }) | ||
22 | }).then(() => next()) | ||
23 | .catch(err => next(err)) | ||
19 | } | 24 | } |
20 | 25 | ||
21 | return Promise.resolve((fun as RequestHandler)(req, res, next)) | 26 | return Promise.resolve((fun as RequestHandler)(req, res, next)) |