]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/async.ts
Add/update OpenRC service script (#2012)
[github/Chocobozzz/PeerTube.git] / server / middlewares / async.ts
CommitLineData
4e50b6a1 1import { eachSeries } from 'async'
a2431b7d 2import { NextFunction, Request, RequestHandler, Response } from 'express'
90d4bb81 3import { retryTransactionWrapper } from '../helpers/database-utils'
523990db 4import { ValidationChain } from 'express-validator'
eb080476
C
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
a2431b7d 8
523990db 9export type RequestPromiseHandler = ValidationChain | ((req: Request, res: Response, next: NextFunction) => Promise<any>)
a2431b7d
C
10
11function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
eb080476 12 return (req: Request, res: Response, next: NextFunction) => {
4e50b6a1
C
13 if (Array.isArray(fun) === true) {
14 return eachSeries(fun as RequestHandler[], (f, cb) => {
15 Promise.resolve(f(req, res, cb))
e3a682a8 16 .catch(err => next(err))
4e50b6a1
C
17 }, next)
18 }
19
20 return Promise.resolve((fun as RequestHandler)(req, res, next))
e3a682a8 21 .catch(err => next(err))
eb080476
C
22 }
23}
24
523990db 25function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
90d4bb81
C
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
eb080476
C
33// ---------------------------------------------------------------------------
34
35export {
90d4bb81
C
36 asyncMiddleware,
37 asyncRetryTransactionMiddleware
eb080476 38}