aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/app/api/v1/utils/handler.ts
blob: 84847d71bace4d62520719589c6ac0bad6f6e98d (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import { NextRequest } from "next/server";
import {
  createContextFromRequest,
  createTrcpClientFromCtx,
} from "@/server/api/client";
import { TRPCError } from "@trpc/server";
import { z, ZodError } from "zod";

import { Context } from "@hoarder/trpc";

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;
  }
}

interface ErrorMessage {
  path: (string | number)[];
  message: string;
}

function formatZodError(error: ZodError): string {
  if (!error.issues) {
    return error.message || "An unknown error occurred";
  }

  const errors: ErrorMessage[] = error.issues.map((issue) => ({
    path: issue.path,
    message: issue.message,
  }));

  const formattedErrors = errors.map((err) => {
    const path = err.path.join(".");
    return path ? `${path}: ${err.message}` : err.message;
  });

  return `${formattedErrors.join(", ")}`;
}

export interface TrpcAPIRequest<SearchParamsT, BodyType> {
  ctx: Context;
  api: ReturnType<typeof createTrcpClientFromCtx>;
  searchParams: SearchParamsT extends z.ZodTypeAny
    ? z.infer<SearchParamsT>
    : undefined;
  body: BodyType extends z.ZodTypeAny
    ? z.infer<BodyType> | undefined
    : undefined;
}

type SchemaType<T> = T extends z.ZodTypeAny
  ? z.infer<T> | undefined
  : undefined;

export async function buildHandler<
  SearchParamsT extends z.ZodTypeAny | undefined,
  BodyT extends z.ZodTypeAny | undefined,
  InputT extends TrpcAPIRequest<SearchParamsT, BodyT>,
>({
  req,
  handler,
  searchParamsSchema,
  bodySchema,
}: {
  req: NextRequest;
  handler: (req: InputT) => Promise<{ status: number; resp?: object }>;
  searchParamsSchema?: SearchParamsT | undefined;
  bodySchema?: BodyT | undefined;
}) {
  try {
    const ctx = await createContextFromRequest(req);
    const api = createTrcpClientFromCtx(ctx);

    let searchParams: SchemaType<SearchParamsT> | undefined = undefined;
    if (searchParamsSchema !== undefined) {
      searchParams = searchParamsSchema.parse(
        Object.fromEntries(req.nextUrl.searchParams.entries()),
      ) as SchemaType<SearchParamsT>;
    }

    let body: SchemaType<BodyT> | undefined = undefined;
    if (bodySchema) {
      if (req.headers.get("Content-Type") !== "application/json") {
        throw new TRPCError({
          code: "BAD_REQUEST",
          message: "Content-Type must be application/json",
        });
      }

      let bodyJson = undefined;
      try {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        bodyJson = await req.json();
      } catch (e) {
        throw new TRPCError({
          code: "BAD_REQUEST",
          message: `Invalid JSON: ${(e as Error).message}`,
        });
      }
      body = bodySchema.parse(bodyJson) as SchemaType<BodyT>;
    }

    const { status, resp } = await handler({
      ctx,
      api,
      searchParams,
      body,
    } as InputT);

    return new Response(resp ? JSON.stringify(resp) : null, {
      status,
      headers: {
        "Content-Type": "application/json",
      },
    });
  } catch (e) {
    if (e instanceof ZodError) {
      return new Response(
        JSON.stringify({ code: "ParseError", message: formatZodError(e) }),
        {
          status: 400,
          headers: {
            "Content-Type": "application/json",
          },
        },
      );
    }
    if (e instanceof TRPCError) {
      let message = e.message;
      if (e.cause instanceof ZodError) {
        message = formatZodError(e.cause);
      }
      return new Response(JSON.stringify({ code: e.code, error: message }), {
        status: trpcCodeToHttpCode(e.code),
        headers: {
          "Content-Type": "application/json",
        },
      });
    } else {
      const error = e as Error;
      console.error(
        `Unexpected error in: ${req.method} ${req.nextUrl.pathname}:\n${error.stack}`,
      );
      return new Response(JSON.stringify({ code: "UnknownError" }), {
        status: 500,
        headers: {
          "Content-Type": "application/json",
        },
      });
    }
  }
}