1 import { eachSeries } from 'async'
2 import { NextFunction, Request, RequestHandler, Response } from 'express'
3 import { ValidationChain } from 'express-validator'
4 import { ExpressPromiseHandler } from '@server/types/express'
5 import { retryTransactionWrapper } from '../helpers/database-utils'
7 // Syntactic sugar to avoid try/catch in express controllers
8 // Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
10 export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler
12 function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
13 return (req: Request, res: Response, next: NextFunction) => {
14 if (Array.isArray(fun) === true) {
15 return eachSeries(fun as RequestHandler[], (f, cb) => {
16 Promise.resolve(f(req, res, err => cb(err)))
17 .catch(err => next(err))
21 return Promise.resolve((fun as RequestHandler)(req, res, next))
22 .catch(err => next(err))
26 function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
27 return (req: Request, res: Response, next: NextFunction) => {
28 return Promise.resolve(
29 retryTransactionWrapper(fun, req, res, next)
30 ).catch(err => next(err))
34 // ---------------------------------------------------------------------------
38 asyncRetryTransactionMiddleware