Skip to content

Latest commit

 

History

History
58 lines (44 loc) · 2.88 KB

README.md

File metadata and controls

58 lines (44 loc) · 2.88 KB

@tupik/client

Type-safe RPC client for Tupik. createTypedClient<typeof app>() infers paths, params, inputs and response data from the app's routes, with no code generation. Includes an SSE stream parser and a WebSocket helper.

Install

npm install @tupik/client @tupik/core

Usage

import { createApp, createModule } from '@tupik/core';
import { createTypedClient, streamSse } from '@tupik/client';

const app = createApp().register(
  createModule('/users').get('/:id', { access: 'public', handler: (ctx) => ({ id: ctx.params.id, name: 'Ada' }) }),
);

// In production pass `baseUrl` of the server; here the client calls the app in-process.
const client = createTypedClient<typeof app>({
  baseUrl: 'http://localhost',
  fetch: (input, init) => app.fetch(new Request(input, init)),
});

const result = await client.get('/users/:id', { params: { id: '7' } });
if (result.ok) console.log(result.data.name); // 'Ada' (typed)
else if (result.kind === 'problem') console.log(result.error.code); // RFC 9457 problem from the API
else console.log(result.kind); // 'http', 'network', 'timeout' or 'abort'

// Server-Sent Events: parse any `text/event-stream` body.
const { body } = new Response('retry: 5000\n\nevent: tick\ndata: 1\n\n');
const onControl = (control: { id?: string; retry?: number }) => console.log(control); // { retry: 5000 }
if (body) for await (const event of streamSse(body, { onControl })) console.log(event); // { event: 'tick', data: '1' }

A frame with retry: or id: and no data dispatches no event, but the WHATWG spec still applies it: streamSse hands it to onControl, and connectSse uses it for the reconnect delay and the next Last-Event-ID. A server that sends retry: 3000 on connect no longer needs reconnect.delayMs to match.

Key API

Export Purpose
createTypedClient<typeof app>({ baseUrl, headers?, fetch? }) Typed get/post/put/patch/delete/head/options; results are { ok: true, data, response } or { ok: false, kind, error, response } with kind 'problem', 'http', 'network', 'timeout' or 'abort'
createClient(options) / TupikClient Untyped client (request(method, path, options))
RouteErrorCode<Route> / AccessProblemCode On a typed call, a kind: 'problem' result types error.code as the route's declared errors codes plus UNAUTHORIZED/FORBIDDEN/NOT_FOUND
streamSse(body, { onControl? }) Async iterator of { event, data, id?, retry? }; onControl gets { id?, retry? } of a frame without data
connectSse(url, { reconnect?, lastEventId?, signal?, fetch?, headers? }) SSE over fetch with optional reconnect: Last-Event-ID and the server retry: (with or without data)
createWebSocket(url, options?) WebSocket with an injectable constructor
createRpcProxy(client, prefix?, method?) Dynamic property-path proxy

License

MIT