โ– humdrum codex / soft
1.4 KB raw
 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
// lib/api.ts โ€” shared helpers for route handlers. Error shape matches the kit:
// { error: { code, message } } with a matching HTTP status.

import { ZodError } from "zod";
import { AuthError } from "./auth";

export function ok(data: unknown, init?: ResponseInit): Response {
  return Response.json(data, init);
}

export function apiError(code: string, message: string, status: number): Response {
  return Response.json({ error: { code, message } }, { status });
}

type Handler = (req: Request, ctx: { params: Promise<Record<string, string>> }) => Promise<Response>;

// Wrap a handler so thrown ZodError/AuthError/Error become clean JSON responses.
export function withErrors(handler: Handler): Handler {
  return async (req, ctx) => {
    try {
      return await handler(req, ctx);
    } catch (err) {
      if (err instanceof ZodError) {
        return apiError("invalid_input", "Validation failed", 400);
      }
      if (err instanceof AuthError) {
        return apiError("unauthorized", err.message, err.status);
      }
      const message = err instanceof Error ? err.message : "Unknown error";
      return apiError("internal_error", message, 500);
    }
  };
}

export async function parseJson<T>(req: Request, schema: { parse(v: unknown): T }): Promise<T> {
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    throw new ZodError([]);
  }
  return schema.parse(body);
}