]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/async.ts
534891899cab0364af5a41a0a37bf82a5b1dcf9c
[github/Chocobozzz/PeerTube.git] / server / middlewares / async.ts
1 import { eachSeries } from 'async'
2 import { NextFunction, Request, RequestHandler, Response } from 'express'
3
4 // Syntactic sugar to avoid try/catch in express controllers
5 // Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
6
7 export type RequestPromiseHandler = (req: Request, res: Response, next: NextFunction) => Promise<any>
8
9 function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
10 return (req: Request, res: Response, next: NextFunction) => {
11 if (Array.isArray(fun) === true) {
12 return eachSeries(fun as RequestHandler[], (f, cb) => {
13 Promise.resolve(f(req, res, cb))
14 .catch(next)
15 }, next)
16 }
17
18 return Promise.resolve((fun as RequestHandler)(req, res, next))
19 .catch(next)
20 }
21 }
22
23 // ---------------------------------------------------------------------------
24
25 export {
26 asyncMiddleware
27 }