async.ts 1.3 KB

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