Add the Typed API Client
A fetch client with structured errors, end-to-end route types from Hono, streaming and sane TanStack Query defaults.
Install
npm i @dapplelight/signet-lib @tanstack/react-queryCreate a plain client
import { createApiClient } from "@dapplelight/signet-lib/api"
import { Transaction } from "@dapplelight/signet-payments"
export const api = createApiClient({
baseUrl: "/api",
onAuthError: () => { window.location.href = "/login" },
})
const rows = await api.get<Transaction[]>("/transactions")Or type it from the server
import { zValidator } from "@dapplelight/signet-server/http/validate"
import { Hono } from "hono"
import { NoteInput, save } from "./notes"
export const app = new Hono()
.post("/api/notes", zValidator("json", NoteInput), (c) => c.json(save(c.req.valid("json")), 201))
export type AppType = typeof appimport { hc } from "hono/client"
import { createRpcClient } from "@dapplelight/signet-lib/api"
import type { AppType } from "../server/app"
export const api = createRpcClient(hc<AppType>, {
baseUrl: "/",
timeoutMs: 10_000,
onAuthError: () => { window.location.href = "/login" },
})
const note = await (await api.api.notes.$post({ json: { title: "Hi" } })).json()Show field errors
import { ApiError } from "@dapplelight/signet-lib/api"
import { api } from "./api"
export async function submit(
json: { title: string },
setFieldErrors: (errors: Record<string, string[]>) => void,
) {
try {
await api.api.notes.$post({ json })
} catch (e) {
if (e instanceof ApiError && e.code === "VALIDATION_FAILED") setFieldErrors(e.details?.fieldErrors ?? {})
}
}Map error codes to copy
import { DEFAULT_ERROR_COPY, errorCopy, type ErrorCode, type ErrorCopy } from "@dapplelight/signet-lib/api"
import type { AppErrorCode } from "./codes"
export const COPY = {
...DEFAULT_ERROR_COPY,
RATE_LIMITED: { title: "Easy there", detail: "Search again shortly.", action: "wait" },
} satisfies Record<ErrorCode | AppErrorCode, ErrorCopy>
export function describe(err: { code: string }) {
const { title, detail } = errorCopy(err.code, COPY)
return `${title}: ${detail}`
}Read a stream
import { readSseJson } from "@dapplelight/signet-lib/api"
import type { UIMessage, UIMessageChunk } from "ai"
import { api } from "./api"
export async function send(messages: UIMessage[], append: (delta: string) => void) {
const res = await api.api.chat.$post({ json: { messages } })
for await (const chunk of readSseJson<UIMessageChunk>(res)) {
if (chunk.type === "text-delta") append(chunk.delta)
}
}Set TanStack Query defaults
import { QueryClient } from "@tanstack/react-query"
import { queryDefaults, onAuthErrorRedirect } from "@dapplelight/signet-lib/api/query-client"
export const client = new QueryClient({ defaultOptions: queryDefaults() })
onAuthErrorRedirect(client, () => { window.location.href = "/login" })