Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.8 KiB · at 358de06

Write handleCreateUser(req, nextId), an HTTP handler for creating a user. It never fails or throws: every outcome is a response { status, body } where body is a plain JSON-serializable object.

req is { method, headers, body }; headers maps header names to values and body is the raw request text. nextId() returns a fresh id; call it only when a user is actually created.

Checks, in order (the first that fails decides the response):

  1. method must be exactly "POST", else 405 { error: "method_not_allowed" }.
  2. A content-type header must be present (header names are case-insensitive) and its media type, the part before any ;, trimmed and compared case-insensitively, must be application/json. Parameters such as ; charset=utf-8 are allowed. Otherwise 415 { error: "unsupported_media_type" }.
  3. The body must parse as JSON, else 400 { error: "invalid_json" }.
  4. The parsed body must be a JSON object (not null, an array, or a primitive), else 422 { error: "invalid_field", field: "body" }.
  5. Fields, checked in this order, each failing with 422 { error: "invalid_field", field: "<name>" }:
    • name: a string that is non-empty after trimming.
    • email: a string with no whitespace, exactly one @, at least one character before the @, and a part after the @ that contains a . which is neither its first nor its last character.
    • age: optional. Missing or null means not provided. Otherwise it must be an integer number from 0 to 150 inclusive.

On success respond 201 { id, name, email } where id comes from nextId(), name is trimmed, and email is as given. Add age only when it was provided. Other fields in the request body are ignored and never echoed back. Response bodies never contain null or undefined values.