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'
6 import { HttpMethod, HttpStatusCode } from '@shared/core-utils'
8 // Syntactic sugar to avoid try/catch in express controllers
9 // Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
11 export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler
13 function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
14 return (req: Request, res: Response, next: NextFunction) => {
15 if (Array.isArray(fun) === true) {
16 return eachSeries(fun as RequestHandler[], (f, cb) => {
17 Promise.resolve(f(req, res, err => cb(err)))
18 .catch(err => next(err))
22 return Promise.resolve((fun as RequestHandler)(req, res, next))
23 .catch(err => next(err))
27 function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
28 return (req: Request, res: Response, next: NextFunction) => {
29 return Promise.resolve(
30 retryTransactionWrapper(fun, req, res, next)
31 ).catch(err => next(err))
35 // ---------------------------------------------------------------------------
39 asyncRetryTransactionMiddleware