import type { ZodType, z } from "zod";
import { HttpError } from "./errors";

export async function parseJson<TSchema extends ZodType>(
  req: Request,
  schema: TSchema,
): Promise<z.infer<TSchema>> {
  let json: unknown;
  try {
    json = await req.json();
  } catch {
    throw new HttpError("Invalid JSON", { status: 400, code: "INVALID_JSON" });
  }
  return schema.parse(json);
}
