LunaHandle
One luna as an app sees it, with its live queries, writes, pushes, streams and queued writes.
A LunaHandle is one luna, from client.luna(type, ...key). Pass the luna type as a type argument to check handler names, arguments and results.
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");
const items = list.query("all");
items.subscribe(() => console.log(items.get().data));
await list.mutate("add", { text: "milk" });
Reference
Methods
query(handler, args)?LiveQuery<R>
A live query of a query handler. Each new result reaches its subscribers.
LiveQuery<R>mutate(handler, args, opts)?Promise<R>
Calls a handler and resolves with its result. opts is MutateOptions.
Promise<R>read(handler, args, opts)?Promise<R>
Calls a handler once, without following it. opts takes timeoutMs.
Promise<R>response(handler, args, opts)?Promise<HttpResult>
Calls a handler that answers with a Response, and resolves with its status, headers and body. opts takes timeoutMs.
Promise<HttpResult>iterate(handler, args, opts)?AsyncGenerator<T>
Yields what a streaming handler yields, as it yields it. opts takes an AbortSignal as signal.
AsyncGenerator<T>connection()?ConnectionHandle
The state of the connection to this luna.
ConnectionHandleenqueue(handler, args, opts)?{ id: string; done: Promise<R> }
Queues a write that survives restarts. opts.optimistic names an update given to createClient.
{ id: string; done: Promise<R> }on(push, fn)?() => void
Hears a push the luna sends its connected apps. Returns a function that stops it.
() => voidstream(name, opts)?StreamHandle<T>
Reads one of the luna's streams as it grows. opts is StreamOptions.
StreamHandle<T>LiveQuery
get()() => QueryState<R>
The latest state. The same object until something changes.
() => QueryState<R>subscribe(fn)(fn: () => void) => () => void
Hears every change and keeps the query live. Returns a function that stops it.
(fn: () => void) => () => voidQueryState
status"loading" | "ready" | "error"
ready once there is data. error when the first run failed.
"loading" | "ready" | "error"dataR | undefined
The confirmed result, with pending writes laid over it.
R | undefinederrorConnectionError | undefined
The latest run's failure. data stays as it was.
ConnectionError | undefinedstaleboolean
The connection dropped, or the result is one saved in the store, so data may be behind.
booleanMutateOptions
optimistic?(local: LocalStore) => void
Changes what queries show until the write is in. It must read and write only through local.
(local: LocalStore) => voidtimeoutMs?number
How long to wait, including the wait to connect.
numbercallTimeoutMsLocalStore
get(query)(query: LiveQuery<R>) => R | undefined
A query's value as of the writes before this one. undefined when it is not loaded.
(query: LiveQuery<R>) => R | undefinedset(query, value)(query: LiveQuery<R>, value: R) => void
Replaces what a query shows while this write is pending.
(query: LiveQuery<R>, value: R) => voidupdate(query, fn)(query: LiveQuery<R>, fn: (current: R) => R) => void
set from the current value. Does nothing when the query is not loaded.
(query: LiveQuery<R>, fn: (current: R) => R) => voidConnectionHandle and ConnectionStatus
status()() => "connecting" | "open" | "reconnecting" | "closed"
The connection's state now.
() => "connecting" | "open" | "reconnecting" | "closed"subscribe(fn)(fn: () => void) => () => void
Hears each change of state and keeps the connection open.
(fn: () => void) => () => voidStreamOptions
offset?string
"-1" reads from the start, "now" from the end, or an offset a read gave.
string"-1"limit?number
The most entries to keep. The oldest go first.
number1000StreamHandle and StreamState
stream.get() returns a StreamState, and stream.subscribe(fn) hears new entries and keeps reading.
entriesreadonly T[]
What has been read, oldest first, at most limit of them.
readonly T[]offsetstring
Where reading goes on from.
stringupToDateboolean
The last read reached the end of the stream.
booleanerrorConnectionError | undefined
The last read's failure.
ConnectionError | undefinedGood to know
- Without a type argument, any handler name and arguments are accepted, and results are
any. - Everyone asking the same handler with the same arguments shares one live query, whatever order the arguments’ keys are in. A result equal to the last one does not reach subscribers.
- A query nobody subscribes to stays live and cached for
keepAliveMs, then ends. - A live query that a busy luna refuses with
Unavailable,Overloaded,TimeoutorOutcomeUnknownis asked again after 500 ms. - The writes of one connection run one at a time, in the order they were sent. A write whose connection drops fails with
Closed, and may or may not have happened. - An optimistic update stays laid over until a live result that includes the write arrives, or until
settleMsruns out after the write is answered. If the write fails, the update is removed andmutaterejects. An update that throws is dropped on its own. readgoes over the connection after the writes before it, so it sees every write this client already had answered.- A handler that answers with a
Responsegives its body tomutateandread. A status of 400 or above throwsHttpError. iteratesends one HTTP request. Breaking out of the loop stops the handler, and an error the handler raises after it started throws aConnectionError.streamreads over HTTP and never keeps the luna awake. A read refused with a status below 500, other than 429, stops reading and setserror.enqueueneeds astore. Each write goes once, with itsidas its idempotency key, after the luna’s earlier queued writes. A lost connection or a busy luna sends it again with the same key, and a handler’s failure marks it failed.- A queued write refused for its sign-in, with
Unauthorized,Unauthenticated,Forbidden,Denied, or a refusal with status 401 or 403, stops the queue untilclient.resumeWrites(). - The
donepromise of a queued write already has a rejection handler, so leaving it unawaited is safe.client.writes()shows failures.
Examples
Follow a query without a framework
const items = list.query("all");
const stop = items.subscribe(() => {
const { status, data, stale } = items.get();
if (status === "ready") render(data ?? [], stale);
});
Call stop() when the view goes away.
Show a write at once
await list.mutate(
"add",
{ text: "milk" },
{
optimistic: (local) =>
local.update(items, (old) => [...old, { id: -1, text: "milk" }]),
},
);
Read once without following
const now = await list.read("all", {}, { timeoutMs: 5000 });
Watch the connection
const conn = list.connection();
conn.subscribe(() => showOffline(conn.status() !== "open"));
Hear a push
The luna sends pushes with ctx.broadcast or conn.push. See Push to connected apps.
const room = client.luna("Room", "lobby");
const stop = room.on<{ text: string }>("said", (m) => console.log(m.text));
Read a stream as it grows
const said = room.stream<{ text: string }>("said", { offset: "now", limit: 100 });
said.subscribe(() => console.log(said.get().entries));
Queue a write that survives a restart
const { id, done } = list.enqueue("add", { text: "eggs" });
Read a handler’s Response
const board = client.luna("Board", "b1");
const res = await board.response("export", {});
console.log(res.status, res.headers.get("content-type"), res.body);
Read what a streaming handler yields
for await (const n of room.iterate<number>("count", { to: 3 })) {
console.log(n);
}