import { NextFunction, Request, Response } from 'express'; export type AsyncHandler = (req: Request, res: Response, ...others: any) => Promise; export type AsyncHandlerNext = (req: Request, res: Response, next: NextFunction, ...others: any) => Promise; export type AsyncHandlerError = ( err: Error, req: Request, res: Response, next: NextFunction, ...others: any ) => Promise; export type AsyncMiddleware = AsyncHandler | AsyncHandlerNext | AsyncHandlerError; /** * Handles promises in routes. */ function asyncHandler(handler: AsyncMiddleware): any { if (handler.length == 2) { return function (req: Request, res: Response, next: NextFunction, ...others: any) { return Promise.resolve((handler as AsyncHandler)(req, res, ...others)).catch(next); }; } else if (handler.length == 3) { return function (req: Request, res: Response, next: NextFunction, ...others: any) { return Promise.resolve((handler as AsyncHandlerNext)(req, res, next, ...others)).catch(next); }; } else if (handler.length == 4) { return function (err: Error, req: Request, res: Response, next: NextFunction, ...others: any) { return Promise.resolve((handler as AsyncHandlerError)(err, req, res, next, ...others)).catch(next); }; } else { throw new Error(`Failed to asyncHandle() function "${handler.name}"`); } } export default asyncHandler;