Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 58 lines · 2.3 KiB · at 9ba9e6b

// Plausible bug: the object check forgets that arrays are objects, so `[]` is reported as a bad name instead of a bad body.import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable, wrapSync } from "@tsus/runtime/boundary";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 isJson = (headers: Record<string, string>): boolean =>  match (fromNullable(Object.entries(headers).find(([k]) => k.toLowerCase() === "content-type"))) {    Some(e) => e[1].split(";")[0].trim().toLowerCase() === "application/json",    None => false,  };const ageOf = (v: Option<unknown>): Result<Option<number>, Response> =>  match (v) {    None => Ok(None),    Some(a) => typeof a === "number" && Number.isInteger(a) && a >= 0 && a <= 150 ? Ok(Some(a)) : Err(invalidField("age")),  };const build = (obj: Record<string, unknown>, nextId: () => string): Response => {  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");  }  return match (ageOf(fromNullable(obj.age))) {    Err(r) => r,    Ok(age) => ({      status: 201,      body: match (age) {        Some(a) => ({ id: nextId(), name: name.trim(), email, age: a }),        None => ({ id: nextId(), name: name.trim(), email }),      },    }),  };};const fromBody = (raw: string, nextId: () => string): Response =>  match (wrapSync(JSON.parse)(raw)) {    Err(_e) => ({ status: 400, body: { error: "invalid_json" } }),    Ok(data) => match (fromNullable(data)) {      Some(d) => typeof d === "object" ? build(d as Record<string, unknown>, nextId) : invalidField("body"),      None => invalidField("body"),    },  };export const handleCreateUser = (req: Request, nextId: () => string): Response =>  req.method !== "POST"    ? { status: 405, body: { error: "method_not_allowed" } }    : !isJson(req.headers)      ? { status: 415, body: { error: "unsupported_media_type" } }      : fromBody(req.body, nextId);