Installation
npm i @cuple/client
NOTE: @cuple/client and @cuple/server versions have to match
Create a client
We need to tell Cuple about the server's location.
Every request goes to one path (usually /rpc) and names the route.
Routes with .path() are also plain REST endpoints for other clients.
// cuple.ts
import { createClient } from "@cuple/client";
import type { routes } from "../backend/src/app";
export const client = createClient<typeof routes>({
path: "http://localhost:8080/rpc",
});
Use it like a fetch
import { fetchCuple } from "@cuple/client";
async function getPost(id: number) {
// Keeps success; any other result throws.
const { post } = await fetchCuple(client.getPost.get, { params: { id } }).thenKeepSuccess();
return post;
}
async function findPost(id: number) {
// Like fetch, every response resolves, typed. Keep the ones you handle.
const res = await fetchCuple(client.getPost.get, { params: { id } }).thenKeep([
"success",
"post-not-found",
]);
return res.result === "post-not-found" ? null : res.post;
}
See Handling results.
Why it works this way
There's no code generator because type inference does the job: the client's types are inferred from typeof routes, so they're the server's own types. A monorepo, where the client imports them directly, is the intended setup.
One RPC path follows from that. The client has only types, and the URL isn't in them (types are erased at runtime anyway). Importing the routes value would bundle the server into the client. Routes without .path() have no URL of their own anyway.