ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

49 lines
1.4 KiB

  1. import { ExpressPromiseHandler } from '@server/types/express-handler.js'
  2. import { NextFunction, Request, RequestHandler, Response } from 'express'
  3. import { ValidationChain } from 'express-validator'
  4. import { retryTransactionWrapper } from '../helpers/database-utils.js'
  5. // Syntactic sugar to avoid try/catch in express controllers/middlewares
  6. export type RequestPromiseHandler = ValidationChain | ExpressPromiseHandler
  7. function asyncMiddleware (fun: RequestPromiseHandler | RequestPromiseHandler[]) {
  8. return async (req: Request, res: Response, next: NextFunction) => {
  9. if (Array.isArray(fun) !== true) {
  10. return Promise.resolve((fun as RequestHandler)(req, res, next))
  11. .catch(err => next(err))
  12. }
  13. try {
  14. for (const f of fun) {
  15. await new Promise<void>((resolve, reject) => {
  16. return asyncMiddleware(f)(req, res, err => {
  17. if (err) return reject(err)
  18. return resolve()
  19. })
  20. })
  21. }
  22. next()
  23. } catch (err) {
  24. next(err)
  25. }
  26. }
  27. }
  28. function asyncRetryTransactionMiddleware (fun: (req: Request, res: Response, next: NextFunction) => Promise<any>) {
  29. return (req: Request, res: Response, next: NextFunction) => {
  30. return Promise.resolve(
  31. retryTransactionWrapper(fun, req, res, next)
  32. ).catch(err => next(err))
  33. }
  34. }
  35. // ---------------------------------------------------------------------------
  36. export {
  37. asyncMiddleware,
  38. asyncRetryTransactionMiddleware
  39. }