Optimize async middleware

Avoid using bluebird, a simple for/await is enought
pull/6128/head
Chocobozzz 2023-11-30 09:53:52 +01:00
parent 9e0efe45ff
commit eba9528391
No known key found for this signature in database
GPG Key ID: 583A612D890159BE
1 changed files with 14 additions and 10 deletions

View File

@ -1,4 +1,3 @@
import Bluebird from 'bluebird'
import { NextFunction, Request, RequestHandler, Response } from 'express'
import { ValidationChain } from 'express-validator'
import { ExpressPromiseHandler } from '@server/types/express-handler.js'
@ -9,22 +8,27 @@ import { retryTransactionWrapper } from '../helpers/database-utils.js'
export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler
function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
return (req: Request, res: Response, next: NextFunction) => {
if (Array.isArray(fun) === true) {
return Bluebird.each(fun as RequestPromiseHandler[], f => {
return new Promise<void>((resolve, reject) => {
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 {
for (const f of (fun as RequestPromiseHandler[])) {
await new Promise<void>((resolve, reject) => {
return asyncMiddleware(f)(req, res, err => {
if (err) return reject(err)
return resolve()
})
})
}).then(() => next())
.catch(err => next(err))
}
}
return Promise.resolve((fun as RequestHandler)(req, res, next))
.catch(err => next(err))
next()
} catch (err) {
next(err)
}
}
}