]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/async.ts
Prevent caption listing of private videos
[github/Chocobozzz/PeerTube.git] / server / middlewares / async.ts
CommitLineData
4e50b6a1 1import { eachSeries } from 'async'
a2431b7d 2import { NextFunction, Request, RequestHandler, Response } from 'express'
523990db 3import { ValidationChain } from 'express-validator'
ba5a8d89
C
4import { ExpressPromiseHandler } from '@server/types/express'
5import { retryTransactionWrapper } from '../helpers/database-utils'
eb080476
C
6
7// Syntactic sugar to avoid try/catch in express controllers
8// Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
a2431b7d 9
ba5a8d89 10export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler
a2431b7d
C
11
12function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
eb080476 13 return (req: Request, res: Response, next: NextFunction) => {
4e50b6a1
C
14 if (Array.isArray(fun) === true) {
15 return eachSeries(fun as RequestHandler[], (f, cb) => {
5182473f 16 Promise.resolve(f(req, res, err => cb(err)))
e3a682a8 17 .catch(err => next(err))
4e50b6a1
C
18 }, next)
19 }
20
21 return Promise.resolve((fun as RequestHandler)(req, res, next))
e3a682a8 22 .catch(err => next(err))
eb080476
C
23 }
24}
25
523990db 26function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
90d4bb81
C
27 return (req: Request, res: Response, next: NextFunction) => {
28 return Promise.resolve(
29 retryTransactionWrapper(fun, req, res, next)
30 ).catch(err => next(err))
31 }
32}
33
eb080476
C
34// ---------------------------------------------------------------------------
35
36export {
90d4bb81
C
37 asyncMiddleware,
38 asyncRetryTransactionMiddleware
eb080476 39}