Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

createClient

Make the client an app uses to call lunas, follow live queries and queue writes, from luna/client.

createClient makes a LunaClient, which connects an app to the lunas of one environment.

import { createClient } from "luna/client";
import type { List } from "../luna/lunas/list.ts";

const client = createClient({ url: "<LUNA_URL>", key: "<LUNA_KEY>" });

const list = client.luna<typeof List>("List", "groceries");
await list.mutate("add", { text: "milk" });

Reference

createClient(options)

Returns a LunaClient. It takes one object of ClientOptions.

PropType
urlstring

The environment's URL, the LUNA_URL in .env.local.

Typestring
key?string

A publishable key. It reaches public luna types only.

Typestring
token?string

A secret token, sent as Authorization: Bearer. It reaches private luna types too. Node only, never in an app.

Typestring
headers?Record<string, string>

Extra request headers. Node only.

TypeRecord<string, string>
params?() => Record<string, string> | Promise<Record<string, string>>

Query parameters for each new connection, which onBeforeConnect reads as request.query. Asked again on every reconnect.

Type() => Record<string, string> | Promise<Record<string, string>>
keepAliveMs?number

How long a query nobody watches stays live and cached, and how long an unused connection stays open.

Typenumber
Default10000
settleMs?number

How long a confirmed write stays laid over the queries of other lunas. Queries of the write's own luna get four times as long.

Typenumber
Default1000
callTimeoutMs?number

How long a call may take, including the wait to connect.

Typenumber
Default30000
multiplex?boolean

One WebSocket for all of the client's lunas. With false, one each.

Typeboolean
Defaulttrue
store?ClientStore

Where query results and queued writes are kept between runs. Use one per account.

TypeClientStore
optimistic?Record<string, QueuedOptimistic>

Optimistic updates for queued writes, by name.

TypeRecord<string, QueuedOptimistic>

LunaClient

The methods an app calls.

PropType
luna(type, ...key)?(type: string, ...key: (string | number)[]) => LunaHandle

One luna, by its type and its key values in the order the type declares them. See LunaHandle.

Type(type: string, ...key: (string | number)[]) => LunaHandle
index(name, partition)?(name: string, partition: string | number) => IndexHandle

One partition of an index, read live. See IndexHandle.

Type(name: string, partition: string | number) => IndexHandle
writes()?() => readonly QueuedWrite[]

The queued writes that wait or failed, oldest first.

Type() => readonly QueuedWrite[]
subscribeWrites(fn)?(fn: () => void) => () => void

Hears every change to the queue. Returns a function that stops it.

Type(fn: () => void) => () => void
resumeWrites()?() => void

Sends the queue again after it stopped for a sign-in that ran out.

Type() => void
retryWrite(id)?(id: string) => void

Puts a failed write back in the queue.

Type(id: string) => void
discardWrite(id)?(id: string) => void

Drops a failed write from the queue and the store.

Type(id: string) => void
wipe()?() => Promise<void>

Empties the store and the queue. The promises of queued writes reject with Closed.

Type() => Promise<void>
close()?() => void

Closes every connection. The client cannot be used after.

Type() => void
options?ClientOptions

The options the client was made with.

TypeClientOptions

ClientStore

Text kept by key. Each method may return its value or a promise of it.

PropType
get(key)(key: string) => string | undefined

The text saved at a key.

Type(key: string) => string | undefined
set(key, value)(key: string, value: string) => void

Saves text at a key.

Type(key: string, value: string) => void
delete(key)(key: string) => void

Removes a key.

Type(key: string) => void
keys(prefix)(prefix: string) => string[]

Every key that starts with prefix.

Type(prefix: string) => string[]

webStore(prefix, storage)

Returns a ClientStore over localStorage, or any object shaped like the browser’s Storage. It saves each key as <prefix>:<key>.

PropType
prefixstring

Keeps this store's keys apart from others. Give each account its own.

Typestring
storage?Storage

Where the text goes.

TypeStorage
DefaultglobalThis.localStorage

QueuedWrite

PropType
idstring

The write's id. It is also the idempotency key the write is sent with.

Typestring
pathstring

The luna it is for, such as /List/groceries.

Typestring
handlerstring

The handler it calls.

Typestring
argsRecord<string, unknown>

The handler's arguments.

TypeRecord<string, unknown>
status"pending" | "failed"

Whether it waits to be sent or failed.

Type"pending" | "failed"
error?{ code: string; message: string }

Why it failed.

Type{ code: string; message: string }

QueuedOptimistic

type QueuedOptimistic = (
  local: LocalStore,
  write: { luna: LunaHandle; args: Record<string, unknown> },
) => void;

An optimistic update for a queued write, given by name in options.optimistic. A write queued in an earlier run keeps only that name, so the functions are given when the client starts. LocalStore is on the LunaHandle page.

Good to know

  • mutate, read, live queries and pushes travel over a WebSocket, while iterate and stream use HTTP. With multiplex, one socket carries every luna, and each luna still runs its own onBeforeConnect.
  • A browser cannot set headers on a WebSocket, so token and headers work in Node only. The publishable key goes in the address as ?key=.
  • A dropped connection reconnects on its own. The wait grows with each failed try, from 200 ms up to 15 s.
  • A luna that closes the connection itself, with code 1000 or 4000 to 4999, is not reconnected. The next use of that luna opens a new connection, and params is asked again.
  • A refused connection fails the calls that wait for it with the luna’s own error code. Live queries keep trying after a refusal with status 408, 429, or 500 and above.
  • enqueue throws Invalid when the client has no store, or when the optimistic update it names was not given here.
  • After close(), every call throws a ConnectionError with code Closed.

Examples

Call a private luna from your server

A secret token reaches private luna types. Keep it on a server.

import { createClient } from "luna/client";

const client = createClient({
  url: "<LUNA_URL>",
  token: "<SECRET_TOKEN>",
});

Send your app’s sign-in with each connection

params runs before each connection opens, so a token that was refreshed reaches onBeforeConnect.

import { createClient } from "luna/client";

const client = createClient({
  url: "<LUNA_URL>",
  key: "<LUNA_KEY>",
  params: () => ({ session: localStorage.getItem("session") ?? "" }),
});

Keep results and writes between runs

With a store, saved results show as stale until live ones arrive, and queued writes survive a restart.

import { createClient, webStore } from "luna/client";

type Item = { id: number; text: string };

const client = createClient({
  url: "<LUNA_URL>",
  key: "<LUNA_KEY>",
  store: webStore("account-42"),
  optimistic: {
    addItem: (local, { luna, args }) =>
      local.update(luna.query("all"), (items: Item[]) => [
        ...items,
        { id: -1, text: String(args.text) },
      ]),
  },
});

client.luna("List", "groceries").enqueue("add", { text: "milk" }, { optimistic: "addItem" });

Show writes that failed

import type { LunaClient } from "luna/client";

export function watchQueue(client: LunaClient) {
  return client.subscribeWrites(() => {
    for (const w of client.writes()) {
      if (w.status === "failed") console.warn(w.handler, w.error?.message);
    }
  });
}

Call client.retryWrite(id) to send a failed write again, or client.discardWrite(id) to drop it.

Clear an account’s data on sign-out

import type { LunaClient } from "luna/client";

export async function signOut(client: LunaClient) {
  await client.wipe();
  client.close();
}

Was this page helpful?