Typed client
Make a client from the type of a route table with @senrijs/senri/client
Pass the type of a route table (typeof routes) to the client, and paths, parameters, the query, the body and the response are typed. The client only reads the server's types, so the server code does not go into the client bundle.
import { } from "@senrijs/senri/client";
import type { } from "./routes.ts";
const = <>("https://example.com", {
: () => ({ : `Bearer ${()}` }), // a function is called for each call
});
const = await ("GET /users/:id", { : { : "1" } });
if (.) {
.data;} else if (. === 404) {
.error;}
await ("POST /users", { : { : "a" } }); // the body has the schema's input typeWhat is sent
- Call it with the same string as the table key
paramsare encoded into the pathqueryvalues are turned into strings (arrays repeat the key)bodyis sent as JSON.FormData,URLSearchParams,Blob, bytes and streams are sent as is
The result
It returns { ok, status, data, error, response }. A status other than 2xx does not throw (only network errors and broken JSON throw).
- The body is read by Content-Type: JSON becomes a value,
text/*a string, anything else aBlob - The type of
datais the handler's return value after JSON (aDatebecomes astring). With anendpoint({ response })schema, it is that schema's output type
Types per status
When a handler returns c.json(body, status) or c.text(body, status) with a status, the result is typed per status. Schemas in endpoint({ responses: { 404: schema } }) work the same way.
- 2xx (such as
c.json(body, 201)) goes into the successfuldata c.json(body)without a status counts as 200. A status set withc.status()is not kept in the type- Responses from
onError, middleware andnotFoundare not in the type: theirerrorisunknown
Call without a server
You can replace fetch.
import { } from "@senrijs/senri/client";
const = <typeof >("http://localhost", { : () => .() });In tests, testClient(), which also handles cookies, is handier.
Options
Prop
Type