2024-06-21 09:24:49 -04:00
|
|
|
import { ExpressPromiseHandler } from '@server/types/express-handler.js'
|
2017-11-27 11:30:46 -05:00
|
|
|
import { NextFunction, Request, RequestHandler, Response } from 'express'
|
2019-07-24 09:48:47 -04:00
|
|
|
import { ValidationChain } from 'express-validator'
|
2023-07-31 08:34:36 -04:00
|
|
|
import { retryTransactionWrapper } from '../helpers/database-utils.js'
|
2017-10-25 05:55:06 -04:00
|
|
|
|
2022-08-02 08:41:44 -04:00
|
|
|
// Syntactic sugar to avoid try/catch in express controllers/middlewares
|
2017-11-27 11:30:46 -05:00
|
|
|
|
2021-02-03 03:33:05 -05:00
|
|
|
export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler
|
2017-11-27 11:30:46 -05:00
|
|
|
|
|
|
|
function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
|
2023-11-30 03:53:52 -05:00
|
|
|
return async (req: Request, res: Response, next: NextFunction) => {
|
|
|
|
if (Array.isArray(fun) !== true) {
|
|
|
|
return Promise.resolve((fun as RequestHandler)(req, res, next))
|
|
|
|
.catch(err => next(err))
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2024-06-21 09:24:49 -04:00
|
|
|
for (const f of fun) {
|
2023-11-30 03:53:52 -05:00
|
|
|
await new Promise<void>((resolve, reject) => {
|
2022-08-02 08:41:44 -04:00
|
|
|
return asyncMiddleware(f)(req, res, err => {
|
|
|
|
if (err) return reject(err)
|
|
|
|
|
|
|
|
return resolve()
|
|
|
|
})
|
|
|
|
})
|
2023-11-30 03:53:52 -05:00
|
|
|
}
|
2017-11-27 08:44:51 -05:00
|
|
|
|
2023-11-30 03:53:52 -05:00
|
|
|
next()
|
|
|
|
} catch (err) {
|
|
|
|
next(err)
|
|
|
|
}
|
2017-10-25 05:55:06 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-24 09:48:47 -04:00
|
|
|
function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
|
2018-06-13 08:27:40 -04:00
|
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
|
|
|
return Promise.resolve(
|
|
|
|
retryTransactionWrapper(fun, req, res, next)
|
|
|
|
).catch(err => next(err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-25 05:55:06 -04:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
2018-06-13 08:27:40 -04:00
|
|
|
asyncMiddleware,
|
|
|
|
asyncRetryTransactionMiddleware
|
2017-10-25 05:55:06 -04:00
|
|
|
}
|