aboutsummaryrefslogtreecommitdiffstats
path: root/packages/api/middlewares/trpcAdapter.ts
blob: 6bb4a7903f90f4c285987ba063f2fe6bb35a7e33 (plain) (blame)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { TRPCError } from "@trpc/server";
import { createMiddleware } from "hono/factory";
import { HTTPException } from "hono/http-exception";

function trpcCodeToHttpCode(code: TRPCError["code"]) {
  switch (code) {
    case "BAD_REQUEST":
    case "PARSE_ERROR":
      return 400;
    case "UNAUTHORIZED":
      return 401;
    case "FORBIDDEN":
      return 403;
    case "NOT_FOUND":
      return 404;
    case "METHOD_NOT_SUPPORTED":
      return 405;
    case "TIMEOUT":
      return 408;
    case "PAYLOAD_TOO_LARGE":
      return 413;
    case "INTERNAL_SERVER_ERROR":
      return 500;
    default:
      return 500;
  }
}

const trpcAdapter = createMiddleware(async (c, next) => {
  await next();
  const e = c.error;
  if (e instanceof TRPCError) {
    const code = trpcCodeToHttpCode(e.code);
    throw new HTTPException(code, {
      message: e.message,
      cause: e.cause,
    });
  }
});

export default trpcAdapter;