2017-11-27 07:44:51 -06:00
|
|
|
import { eachSeries } from 'async'
|
2017-11-27 10:30:46 -06:00
|
|
|
import { NextFunction, Request, RequestHandler, Response } from 'express'
|
2019-07-24 08:48:47 -05:00
|
|
|
import { ValidationChain } from 'express-validator'
|
2021-02-03 02:33:05 -06:00
|
|
|
import { ExpressPromiseHandler } from '@server/types/express'
|
|
|
|
import { retryTransactionWrapper } from '../helpers/database-utils'
|
2017-10-25 04:55:06 -05:00
|
|
|
|
|
|
|
// Syntactic sugar to avoid try/catch in express controllers
|
|
|
|
// Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
|
2017-11-27 10:30:46 -06:00
|
|
|
|
2021-02-03 02:33:05 -06:00
|
|
|
export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler
|
2017-11-27 10:30:46 -06:00
|
|
|
|
|
|
|
function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
|
2017-10-25 04:55:06 -05:00
|
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
2017-11-27 07:44:51 -06:00
|
|
|
if (Array.isArray(fun) === true) {
|
|
|
|
return eachSeries(fun as RequestHandler[], (f, cb) => {
|
2021-04-12 09:35:04 -05:00
|
|
|
Promise.resolve(f(req, res, err => cb(err)))
|
2018-02-14 08:33:49 -06:00
|
|
|
.catch(err => next(err))
|
2017-11-27 07:44:51 -06:00
|
|
|
}, next)
|
|
|
|
}
|
|
|
|
|
|
|
|
return Promise.resolve((fun as RequestHandler)(req, res, next))
|
2018-02-14 08:33:49 -06:00
|
|
|
.catch(err => next(err))
|
2017-10-25 04:55:06 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-24 08:48:47 -05:00
|
|
|
function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
|
2018-06-13 07:27:40 -05:00
|
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
|
|
|
return Promise.resolve(
|
|
|
|
retryTransactionWrapper(fun, req, res, next)
|
|
|
|
).catch(err => next(err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-25 04:55:06 -05:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
2018-06-13 07:27:40 -05:00
|
|
|
asyncMiddleware,
|
|
|
|
asyncRetryTransactionMiddleware
|
2017-10-25 04:55:06 -05:00
|
|
|
}
|