Make sure a report doesn't get deleted upon the deletion of its video
[oweals/peertube.git] / server / middlewares / async.ts
1 import { eachSeries } from 'async'
2 import { NextFunction, Request, RequestHandler, Response } from 'express'
3 import { retryTransactionWrapper } from '../helpers/database-utils'
4 import { ValidationChain } from 'express-validator'
5
6 // Syntactic sugar to avoid try/catch in express controllers
7 // Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
8
9 export type RequestPromiseHandler = ValidationChain | ((req: Request, res: Response, next: NextFunction) => Promise<any>)
10
11 function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
12   return (req: Request, res: Response, next: NextFunction) => {
13     if (Array.isArray(fun) === true) {
14       return eachSeries(fun as RequestHandler[], (f, cb) => {
15         Promise.resolve(f(req, res, cb))
16           .catch(err => next(err))
17       }, next)
18     }
19
20     return Promise.resolve((fun as RequestHandler)(req, res, next))
21       .catch(err => next(err))
22   }
23 }
24
25 function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
26   return (req: Request, res: Response, next: NextFunction) => {
27     return Promise.resolve(
28       retryTransactionWrapper(fun, req, res, next)
29     ).catch(err => next(err))
30   }
31 }
32
33 // ---------------------------------------------------------------------------
34
35 export {
36   asyncMiddleware,
37   asyncRetryTransactionMiddleware
38 }