@nodii/http
v0.2.0
Published
The one API response library for Nodii (S-09): ok, fail, HttpError, paginatedData and the error handler that make every REST body one shape.
Readme
@nodii/http
The one API response library for Nodii (S-09). Every REST body goes through it, so the shape is one change here and not a search across the fleet. It has TypeScript, Python (nodii-http) and Go (nodii.co/nodii-libs/go/http) ports, with shared cases in scripts/parity/http-cases.json.
import { errorHandler, fail, HttpError, notFoundHandler, ok, paginatedData } from "@nodii/http";
app.onError(errorHandler({ report: (error) => logger.error({ error }, "request failed") }));
app.notFound(notFoundHandler);
app.get("/api/v1/invoices/:invoice_id", async (c) => {
const invoice = await read(c.req.param("invoice_id"));
if (!invoice) return fail(c, "not_found", "Invoice not found.");
return ok(c, invoice);
});
app.post("/api/v1/invoices", async (c) => ok(c, await create(c), undefined, { status: 201 }));
app.get("/api/v1/invoices", async (c) => paginatedData(c, await list(c)));What it answers
| Call | Answer |
|---|---|
| ok(c, data) | 200 {"data": …} |
| ok(c, data, meta) | 200 {"data": …, "meta": …}. meta holds only next_cursor, previous_cursor, limit, total and generated_at (S09-6). |
| ok(c, data, meta, { status }) | The same with another 2xx, such as 201. |
| ok(c, null) | 204 with no body (S09-7). |
| fail(c, code, message, details?) | {"error": true, "code": …, "message": …, "details": …} |
| fail(c, code, message, details, { status }) | The same with that 4xx or 5xx. |
| throw new HttpError(status, code, message, details?) | The same, through errorHandler. |
| paginatedData(c, page) | 200 with the page from @nodii/pagination (S10-7). |
The status of fail
A code in STANDARD_CATALOGUE has its own status, so fail(c, "not_found", …) is a 404. Any other code is a 400 unless you pass { status }. Pass it whenever the failure is not a plain bad request (S09-13).
What it refuses
A wrong call is a fault in the service, so it throws HttpConfigError and the caller receives 500 internal_error:
- a code that is not lowercase
snake_case(S09-9), or a blank message; - a
metamember outside the list above; - a success status that cannot carry a body, or an error status outside 4xx and 5xx.
What the error handler does
| Thrown | Answer |
|---|---|
| HttpError | Its status, code, message and details. |
| PaginationError | Its status, code and message. |
| Hono HTTPException | Its status and the catalogue's code. A 4xx keeps its own message; a 5xx uses the catalogue's. Its own response body is ignored, so it cannot escape the envelope. |
| Anything else | 500 internal_error. The error's own message never reaches the caller (S09-11). |
report receives every failure that answers 5xx, so log there. A throw from report changes nothing.
Write only safe text in message and details: no stack trace, SQL, secret or another person's personal data (S09-11, S09-12). The library cannot check this for you.
Reading a response
The client half reads what ok and fail answered, so a caller handles one shape too (S09-5, S09-8).
import { fetchData, HttpError, orvalMutator, readResponse } from "@nodii/http";
const { data, meta } = await fetchData<Invoice[]>(`${tenantUrl}/api/v1/invoices`, {
headers: { authorization: `Bearer ${token}` },
});
// nodii-frontend: import from "@nodii/http/client", which loads only the client
// half, and export orval's `override.mutator`.
export const customFetch = orvalMutator({ fetch: authedFetch, baseUrl: apiBase });@nodii/pagination is a required peer, because the root entry imports it at runtime (for paginatedData). hono is an optional peer because the library uses only its types: the root entry's types still import it, so a service that imports @nodii/http needs hono installed (every Hono service has it). Only @nodii/http/client works without either peer: it imports neither, at runtime or in its types.
| Answer | readResponse / fetchData |
|---|---|
| A 2xx {"data": …, "meta"?: …} with a JSON content type | { data, meta? } |
| 204 or 205 | { data: null }, so name null in the type for an operation that can answer 204 |
| A 4xx or 5xx error envelope | throws HttpError with that status, code, message and details |
| A 4xx or 5xx without a valid envelope (a proxy's HTML page, no body, a code that is not snake_case, an extra member) | throws HttpError with the catalogue code and message for its status. The body's own text is never used (S09-11). |
| A 2xx that is not an envelope, or a 1xx or 3xx | throws HttpError(502, "bad_gateway") |
fetchData sends a string body as application/json unless you name a type, and does not follow a redirect unless you set redirect, so a 3xx is bad_gateway in every port. Pass { fetch } to add auth or retries. A network failure is fetch's own error, not an HttpError.
orvalMutator is for orval's httpClient: "fetch". It resolves { data, status, headers } with data the whole envelope, because the OpenAPI document describes the envelope (undefined for a 204), and it throws HttpError for every failure, so a query's error branch sees it. It reads JSON envelopes only; fetch a file download yourself.
The reader takes at most MAX_RESPONSE_BYTES (16 MiB, the same in every port). A longer body is cut off as it arrives and counts as no envelope. fetch has no timeout of its own: pass signal: AbortSignal.timeout(ms) in the init for a call that must not hang.
A number is read as JSON reads it: an integer past 2^53 rounds to the nearest float64, in every port when the value is untyped. Go keeps it exact when you decode into an int64. Send a larger ID as a string.
The client throws the same HttpError a handler throws, so a service that lets a downstream refusal propagate answers it unchanged through errorHandler. Catch it when the downstream's code means something else to your caller.
Checking a service
@nodii/doctrine-lint ships response-envelope-lint, which refuses a hand-built envelope in src/, and openapi-contract-lint, which checks a dumped OpenAPI document against S-09.
