1 import { eachSeries } from 'async'
2 import { NextFunction, Request, RequestHandler, Response } from 'express'
3 import { retryTransactionWrapper } from '../helpers/database-utils'
5 // Syntactic sugar to avoid try/catch in express controllers
6 // Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
8 export type RequestPromiseHandler = (req: Request, res: Response, next: NextFunction) => Promise<any>
10 function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
11 return (req: Request, res: Response, next: NextFunction) => {
12 if (Array.isArray(fun) === true) {
13 return eachSeries(fun as RequestHandler[], (f, cb) => {
14 Promise.resolve(f(req, res, cb))
15 .catch(err => next(err))
19 return Promise.resolve((fun as RequestHandler)(req, res, next))
20 .catch(err => next(err))
24 function asyncRetryTransactionMiddleware (fun: RequestPromiseHandler) {
25 return (req: Request, res: Response, next: NextFunction) => {
26 return Promise.resolve(
27 retryTransactionWrapper(fun, req, res, next)
28 ).catch(err => next(err))
32 // ---------------------------------------------------------------------------
36 asyncRetryTransactionMiddleware