aboutsummaryrefslogtreecommitdiffstats
path: root/server/async.ts
blob: c88acebac2caad69b9113b31dafb5ea55443cf28 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import type { Request, Response, NextFunction, RequestHandler } from "express";
import type { ParamsDictionary, Query } from "express-serve-static-core";

export interface AsyncRequestHandler<
  P = ParamsDictionary,
  ResBody = any,
  ReqBody = any,
  ReqQuery = Query,
  Locals extends Record<string, any> = Record<string, any>
> {
  (
    req: Request<P, ResBody, ReqBody, ReqQuery, Locals>,
    res: Response<ResBody, Locals>,
    next: NextFunction,
  ): Promise<Response>;
}

export const wrap = <
  P = ParamsDictionary,
  ResBody = any,
  ReqBody = any,
  ReqQuery = Query,
  Locals extends Record<string, any> = Record<string, any>
>(handler: AsyncRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>): RequestHandler<P, ResBody, ReqBody, ReqQuery, Locals> => {
  return (req, res, next) => handler(req, res, next).catch((err) => next(err));
};