Skip to Content
Senri

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.

client.ts
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;
data: {
    id: string;
    name: string;
}
} else if (. === 404) { .error;
error: {
    message: string;
}
} await ("POST /users", { : { : "a" } }); // the body has the schema's input type

What is sent

  • Call it with the same string as the table key
  • params are encoded into the path
  • query values are turned into strings (arrays repeat the key)
  • body is 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 a Blob
  • The type of data is the handler's return value after JSON (a Date becomes a string). With an endpoint({ 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 successful data
  • c.json(body) without a status counts as 200. A status set with c.status() is not kept in the type
  • Responses from onError, middleware and notFound are not in the type: their error is unknown

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

On this page