import { Request, Response, NextFunction, RequestHandler } from 'express'; // Express 4 does not forward a rejected promise from an async handler to the // error middleware. An async route that throws therefore never responds at all // — the request hangs until the client gives up, which reads to a user as "the // page is empty" rather than "the server failed". Wrapping the handler routes // the rejection into next(), so the error middleware can answer with a 500. // // Express 5 does this natively; drop this helper if the project ever upgrades. export function asyncRoute( handler: (req: Request, res: Response, next: NextFunction) => unknown ): RequestHandler { // Returning a promise where Express expects void is the entire point of this // wrapper, and the promise cannot reject — `.catch(next)` is the last link in // the chain. Express ignores the return value; the unit tests await it to // observe that next() was called. // eslint-disable-next-line @typescript-eslint/no-misused-promises return (req, res, next) => { // Promise.resolve also captures a synchronous throw, so both failure modes // reach the same place. return Promise.resolve() .then(() => handler(req, res, next)) .catch(next); }; }