PeerTube/server/middlewares/async.ts

39 lines
1.4 KiB
TypeScript
Raw Normal View History

import { eachSeries } from 'async'
2017-11-27 17:30:46 +01:00
import { NextFunction, Request, RequestHandler, Response } from 'express'
2018-06-13 14:27:40 +02:00
import { retryTransactionWrapper } from '../helpers/database-utils'
2019-07-24 15:48:47 +02:00
import { ValidationChain } from 'express-validator'
2017-10-25 11:55:06 +02:00
// Syntactic sugar to avoid try/catch in express controllers
// Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
2017-11-27 17:30:46 +01:00
2019-07-24 15:48:47 +02:00
export type RequestPromiseHandler = ValidationChain | ((req: Request, res: Response, next: NextFunction) => Promise<any>)
2017-11-27 17:30:46 +01:00
function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
2017-10-25 11:55:06 +02:00
return (req: Request, res: Response, next: NextFunction) => {
if (Array.isArray(fun) === true) {
return eachSeries(fun as RequestHandler[], (f, cb) => {
Promise.resolve(f(req, res, cb))
2018-02-14 15:33:49 +01:00
.catch(err => next(err))
}, next)
}
return Promise.resolve((fun as RequestHandler)(req, res, next))
2018-02-14 15:33:49 +01:00
.catch(err => next(err))
2017-10-25 11:55:06 +02:00
}
}
2019-07-24 15:48:47 +02:00
function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
2018-06-13 14:27:40 +02:00
return (req: Request, res: Response, next: NextFunction) => {
return Promise.resolve(
retryTransactionWrapper(fun, req, res, next)
).catch(err => next(err))
}
}
2017-10-25 11:55:06 +02:00
// ---------------------------------------------------------------------------
export {
2018-06-13 14:27:40 +02:00
asyncMiddleware,
asyncRetryTransactionMiddleware
2017-10-25 11:55:06 +02:00
}