async.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. // Syntactic sugar to avoid try/catch in express controllers
  6. // Thanks: https://medium.com/@Abazhenov/using-async-await-in-express-with-node-8-b8af872c0016
  7. export type RequestPromiseHandler = ValidationChain | ((req: Request, res: Response, next: NextFunction) => Promise<any>)
  8. function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
  9. return (req: Request, res: Response, next: NextFunction) => {
  10. if (Array.isArray(fun) === true) {
  11. return eachSeries(fun as RequestHandler[], (f, cb) => {
  12. Promise.resolve(f(req, res, cb))
  13. .catch(err => next(err))
  14. }, next)
  15. }
  16. return Promise.resolve((fun as RequestHandler)(req, res, next))
  17. .catch(err => next(err))
  18. }
  19. }
  20. function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
  21. return (req: Request, res: Response, next: NextFunction) => {
  22. return Promise.resolve(
  23. retryTransactionWrapper(fun, req, res, next)
  24. ).catch(err => next(err))
  25. }
  26. }
  27. // ---------------------------------------------------------------------------
  28. export {
  29. asyncMiddleware,
  30. asyncRetryTransactionMiddleware
  31. }