Add shares forward and collection on videos/video channels
[oweals/peertube.git] / server / middlewares / async.ts
1 import { Request, Response, NextFunction, RequestHandler } from 'express'
2 import { eachSeries } from 'async'
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 function asyncMiddleware (fun: RequestHandler | RequestHandler[]) {
7   return (req: Request, res: Response, next: NextFunction) => {
8     if (Array.isArray(fun) === true) {
9       return eachSeries(fun as RequestHandler[], (f, cb) => {
10         Promise.resolve(f(req, res, cb))
11           .catch(next)
12       }, next)
13     }
14
15     return Promise.resolve((fun as RequestHandler)(req, res, next))
16       .catch(next)
17   }
18 }
19
20 // ---------------------------------------------------------------------------
21
22 export {
23   asyncMiddleware
24 }