Optimize async middleware
Avoid using bluebird, a simple for/await is enought
This commit is contained in:
parent
9e0efe45ff
commit
eba9528391
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue