Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 42 lines · 1.8 KiB · at 83c2f03

export type Request = { method: string; headers: Record<string, string>; body: string };export type Response = { status: number; body: Record<string, unknown> };const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;const invalidField = (field: string): Response => ({ status: 422, body: { error: "invalid_field", field } });const contentType = (headers: Record<string, string>): string | undefined => {  for (const [k, v] of Object.entries(headers)) {    if (k.toLowerCase() === "content-type") return v;  }  return undefined;};/** Never throws; every outcome is a Response. */export function handleCreateUser(req: Request, nextId: () => string): Response {  if (req.method !== "POST") return { status: 405, body: { error: "method_not_allowed" } };  const ct = contentType(req.headers);  if (typeof ct !== "string" || ct.split(";")[0].trim().toLowerCase() !== "application/json") {    return { status: 415, body: { error: "unsupported_media_type" } };  }  let data: unknown;  try {    data = JSON.parse(req.body);  } catch {    return { status: 400, body: { error: "invalid_json" } };  }  if (typeof data !== "object" || data === null || Array.isArray(data)) return invalidField("body");  const obj = data as Record<string, unknown>;  const name = obj.name;  if (typeof name !== "string" || name.trim() === "") return invalidField("name");  const email = obj.email;  if (typeof email !== "string" || !EMAIL.test(email)) return invalidField("email");  const age = obj.age;  const hasAge = age !== undefined && age !== null;  if (hasAge && (typeof age !== "number" || !Number.isInteger(age) || age < 0 || age > 150)) return invalidField("age");  const body: Record<string, unknown> = { id: nextId(), name: name.trim(), email };  if (hasAge) body.age = age;  return { status: 201, body };}