1
0
Fork 0
peertube/server/middlewares/async.ts

28 lines
906 B
TypeScript
Raw Normal View History

import { eachSeries } from 'async'
2017-11-27 11:30:46 -05:00
import { NextFunction, Request, RequestHandler, Response } from 'express'
2017-10-25 05:55:06 -04: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 11:30:46 -05:00
export type RequestPromiseHandler = (req: Request, res: Response, next: NextFunction) => Promise<any>
function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
2017-10-25 05:55:06 -04: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))
.catch(next)
}, next)
}
return Promise.resolve((fun as RequestHandler)(req, res, next))
2017-10-25 05:55:06 -04:00
.catch(next)
}
}
// ---------------------------------------------------------------------------
export {
asyncMiddleware
}