2024-05-23 09:42:14 +00:00
|
|
|
// SPDX-FileCopyrightText: 2024 John Livingston <https://www.john-livingston.fr/>
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2021-05-03 18:06:36 +00:00
|
|
|
import { eachSeries } from 'async'
|
|
|
|
import type { NextFunction, Request, RequestHandler, Response } from 'express'
|
|
|
|
|
|
|
|
// Syntactic sugar to avoid try/catch in express controllers
|
|
|
|
|
|
|
|
export type RequestPromiseHandler = ((req: Request, res: Response, next: NextFunction) => Promise<any>)
|
|
|
|
|
2024-09-07 12:49:27 +00:00
|
|
|
// type asyncMiddleWareFunction = (req: Request, res: Response, next: NextFunction) => Promise<void>
|
|
|
|
// function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]): asyncMiddleWareFunction {
|
|
|
|
// return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
|
|
// if (!Array.isArray(fun)) {
|
|
|
|
// // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
|
|
|
|
// Promise.resolve((fun as RequestHandler)(req, res, next))
|
|
|
|
// .catch(err => { next(err) })
|
|
|
|
// return
|
|
|
|
// }
|
|
|
|
|
|
|
|
// try {
|
|
|
|
// for (const f of fun) {
|
|
|
|
// await new Promise<void>((resolve, reject) => {
|
|
|
|
// // eslint-disable-next-line @typescript-eslint/no-floating-promises
|
|
|
|
// asyncMiddleware(f)(req, res, err => {
|
|
|
|
// if (err) {
|
|
|
|
// reject(err)
|
|
|
|
// return
|
|
|
|
// }
|
|
|
|
// resolve()
|
|
|
|
// })
|
|
|
|
// })
|
|
|
|
// }
|
|
|
|
|
|
|
|
// next()
|
|
|
|
// } catch (err) {
|
|
|
|
// next(err)
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
|
|
|
|
function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
|
2021-05-03 18:06:36 +00:00
|
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
|
|
|
if (Array.isArray(fun)) {
|
|
|
|
eachSeries(fun as RequestHandler[], (f, cb) => {
|
2024-09-07 12:49:27 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
|
|
|
|
Promise.resolve(f(req, res, (err: any) => {
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
|
|
cb(err)
|
|
|
|
}))
|
|
|
|
.catch(err => { next(err) })
|
2021-05-03 18:06:36 +00:00
|
|
|
}, next)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-09-07 12:49:27 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
|
2021-05-03 18:06:36 +00:00
|
|
|
Promise.resolve((fun as RequestHandler)(req, res, next))
|
2024-09-07 12:49:27 +00:00
|
|
|
.catch(err => { next(err) })
|
2021-05-03 18:06:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
asyncMiddleware
|
|
|
|
}
|