Skip to main content
Module

x/cav/dom.ts>client

A server framework for Deno
Go to Latest
function client
import { client } from "https://deno.land/x/cav@0.2.0-alpha.4/dom.ts";

Constructs a new Client function tied to the base URL. The provided set of serializers will be used everywhere that data is de/serialized when using this client, including web sockets.

If the type parameter provided is a Router, Endpoint, or SocketEndpoint, the returned Client's type will be tailored to match the inputs and outputs expected by that handler.

The Client is a function wrapped in a getter Proxy. Each property access will return a new Client, extending the URL of the original Client; the periods translate to path dividers and the property keys are path segments.

Extended example:

// server.ts -------------------------------------------

import {
  router,
  endpoint,
  serve,
} from "https://deno.land/x/cav/mod.ts";

export type Main = typeof main;

const main = router({
  api: {
    v1: {
      // GET /api/v1/hello -> `123` (application/json)
      hello: endpoint(() => 123),
    },
    v2: {
      // GET /api/v2/hello?name=$name -> `$name` (text/plain)
      hello: endpoint({
        query: (q: { name: string }) => q,
        resolve: (x) => x.query.name,
      }),
    },
  },
});

serve(main, { port: 8080 });

// client.ts ---------------------------------------------

import { client } from "https://deno.land/x/cav/mod.ts";
import type { Main } from "../server.ts";

const main = client<Main>("http://localhost:8080");

const v1 = main.api.v1.hello;
// Type: (x: ClientArg) => Promise<number>

const v2 = main.api.v2.hello;
// Type: (x: ClientArg<{ name: string }>) => Promise<string>

console.log(await v1());
console.log(await main.api.v1.hello());
// Output: [123, Response] (for both)

console.log(await v2({ query: { name: "world" } }))
// Output: ["world", Response]

console.log(await v2({ query: {} }));
// IDE error: Missing "name: string" on query
// Output: [undefined, Response]

await main.not.found();
// Throws: HttpError("404 not found", { status: 404 })

Type Parameters

optional
T extends ClientType = null

Parameters

optional
baseUrl = [UNSUPPORTED]
optional
baseSerializers: Serializers