Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 75 lines · 2.8 KiB · at 2e2b18f

import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable, wrapSync, asRecord } 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@]+$/;type User = { name: string; email: string; age: Option<number> };// Validation failures stay a tagged error until the edge turns them into a Response.type FieldError = { kind: "invalid_field"; field: string };const invalidField = (field: string): FieldError => ({ kind: "invalid_field", field });const toResponse = (e: FieldError): Response => ({ status: 422, body: { error: "invalid_field", field: e.field } });const contentType = (headers: Record<string, string>): Option<string> =>  fromNullable(Object.entries(headers).find(([k]) => k.toLowerCase() === "content-type")).map(([, v]) => v);const isJson = (ct: Option<string>): boolean =>  match (ct) {    Some(v) => typeof v === "string" && v.split(";")[0].trim().toLowerCase() === "application/json",    None => false,  };const asObject = (data: unknown): Option<Record<string, unknown>> => asRecord(data);const parseAge = (v: Option<unknown>): Result<Option<number>, FieldError> =>  match (v) {    None => Ok(None),    Some(a) => typeof a === "number" && Number.isInteger(a) && a >= 0 && a <= 150 ? Ok(Some(a)) : Err(invalidField("age")),  };const parseUser = (obj: Record<string, unknown>): Result<User, FieldError> => {  const name = obj.name;  if (typeof name !== "string" || name.trim() === "") {    return Err(invalidField("name"));  }  const email = obj.email;  if (typeof email !== "string" || !EMAIL.test(email)) {    return Err(invalidField("email"));  }  return parseAge(fromNullable(obj.age)).map((age) => ({ name: name.trim(), email, age }));};const created = (user: User, nextId: () => string): Response => {  const base: Record<string, unknown> = { id: nextId(), name: user.name, email: user.email };  return {    status: 201,    body: match (user.age) {      Some(a) => ({ ...base, age: a }),      None => base,    },  };};const fromBody = (raw: string, nextId: () => string): Response =>  match (wrapSync(JSON.parse)(raw)) {    Err(_e) => ({ status: 400, body: { error: "invalid_json" } }),    Ok(data) => match (asObject(data)) {      None => toResponse(invalidField("body")),      Some(obj) => match (parseUser(obj)) {        Ok(user) => created(user, nextId),        Err(e) => toResponse(e),      },    },  };export const handleCreateUser = (req: Request, nextId: () => string): Response =>  req.method !== "POST"    ? { status: 405, body: { error: "method_not_allowed" } }    : !isJson(contentType(req.headers))      ? { status: 415, body: { error: "unsupported_media_type" } }      : fromBody(req.body, nextId);