Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 26 lines · 1.5 KiB · at 9472e3c

// Plausible bug: `typeof data === "object"` lets null through (crash), age dropped when 0 via truthiness, header looked up case-sensitively.export type Request = { method: string; headers: Record<string, string>; body: string };export type Response = { status: number; body: Record<string, unknown> };export function handleCreateUser(req: Request, nextId: () => string): Response {  if (req.method !== "POST") return { status: 405, body: { error: "method_not_allowed" } };  const ct = req.headers["content-type"] ?? req.headers["Content-Type"] ?? "";  if (!ct.startsWith("application/json")) return { status: 415, body: { error: "unsupported_media_type" } };  let data: any;  try {    data = JSON.parse(req.body);  } catch {    return { status: 400, body: { error: "invalid_json" } };  }  if (typeof data !== "object" || Array.isArray(data)) return { status: 422, body: { error: "invalid_field", field: "body" } };  if (typeof data.name !== "string" || !data.name.trim()) return { status: 422, body: { error: "invalid_field", field: "name" } };  if (typeof data.email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {    return { status: 422, body: { error: "invalid_field", field: "email" } };  }  if (data.age != null && (!Number.isInteger(data.age) || data.age < 0 || data.age > 150)) {    return { status: 422, body: { error: "invalid_field", field: "age" } };  }  const body: Record<string, unknown> = { id: nextId(), name: data.name.trim(), email: data.email };  if (data.age) body.age = data.age;  return { status: 201, body };}