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