2
1

async.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { eachSeries } from 'async'
  2. import { NextFunction, Request, RequestHandler, Response } from 'express'
  3. import { ValidationChain } from 'express-validator'
  4. import { ExpressPromiseHandler } from '@server/types/express-handler'
  5. import { retryTransactionWrapper } from '../helpers/database-utils'
  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. export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler
  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, err => cb(err)))
  14. .catch(err => next(err))
  15. }, next)
  16. }
  17. return Promise.resolve((fun as RequestHandler)(req, res, next))
  18. .catch(err => next(err))
  19. }
  20. }
  21. function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
  22. return (req: Request, res: Response, next: NextFunction) => {
  23. return Promise.resolve(
  24. retryTransactionWrapper(fun, req, res, next)
  25. ).catch(err => next(err))
  26. }
  27. }
  28. // ---------------------------------------------------------------------------
  29. export {
  30. asyncMiddleware,
  31. asyncRetryTransactionMiddleware
  32. }