---
title: LunaHandle
description: One luna as an app sees it, with its live queries, writes, pushes, streams and queued writes.
related:
  - /sdk/create-client
  - /realtime/subscribe-to-a-query
  - /clients/call-lunas-from-typescript
---

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.

```ts app/list.ts
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

| Prop | Type | Default | Description |
| - | - | - | - |
| `query(handler, args)?` | `LiveQuery<R>` | - | A live query of a query handler. Each new result reaches its subscribers. |
| `mutate(handler, args, opts)?` | `Promise<R>` | - | Calls a handler and resolves with its result. opts is MutateOptions. |
| `read(handler, args, opts)?` | `Promise<R>` | - | Calls a handler once, without following it. opts takes timeoutMs. |
| `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. |
| `iterate(handler, args, opts)?` | `AsyncGenerator<T>` | - | Yields what a streaming handler yields, as it yields it. opts takes an AbortSignal as signal. |
| `connection()?` | `ConnectionHandle` | - | The state of the connection to this luna. |
| `enqueue(handler, args, opts)?` | `{ id: string; done: Promise<R> }` | - | Queues a write that survives restarts. opts.optimistic names an update given to createClient. |
| `on(push, fn)?` | `() => void` | - | Hears a push the luna sends its connected apps. Returns a function that stops it. |
| `stream(name, opts)?` | `StreamHandle<T>` | - | Reads one of the luna's streams as it grows. opts is StreamOptions. |

### LiveQuery

| Prop | Type | Default | Description |
| - | - | - | - |
| `get()` | `() => QueryState<R>` | - | The latest state. The same object until something changes. |
| `subscribe(fn)` | `(fn: () => void) => () => void` | - | Hears every change and keeps the query live. Returns a function that stops it. |

### QueryState

| Prop | Type | Default | Description |
| - | - | - | - |
| `status` | `"loading" \| "ready" \| "error"` | - | ready once there is data. error when the first run failed. |
| `data` | `R \| undefined` | - | The confirmed result, with pending writes laid over it. |
| `error` | `ConnectionError \| undefined` | - | The latest run's failure. data stays as it was. |
| `stale` | `boolean` | - | The connection dropped, or the result is one saved in the store, so data may be behind. |

### MutateOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `optimistic?` | `(local: LocalStore) => void` | - | Changes what queries show until the write is in. It must read and write only through local. |
| `timeoutMs?` | `number` | `callTimeoutMs` | How long to wait, including the wait to connect. |

### LocalStore

| Prop | Type | Default | Description |
| - | - | - | - |
| `get(query)` | `(query: LiveQuery<R>) => R \| undefined` | - | A query's value as of the writes before this one. undefined when it is not loaded. |
| `set(query, value)` | `(query: LiveQuery<R>, value: R) => void` | - | Replaces what a query shows while this write is pending. |
| `update(query, fn)` | `(query: LiveQuery<R>, fn: (current: R) => R) => void` | - | set from the current value. Does nothing when the query is not loaded. |

### ConnectionHandle and ConnectionStatus

| Prop | Type | Default | Description |
| - | - | - | - |
| `status()` | `() => "connecting" \| "open" \| "reconnecting" \| "closed"` | - | The connection's state now. |
| `subscribe(fn)` | `(fn: () => void) => () => void` | - | Hears each change of state and keeps the connection open. |

### StreamOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `offset?` | `string` | `"-1"` | "-1" reads from the start, "now" from the end, or an offset a read gave. |
| `limit?` | `number` | `1000` | The most entries to keep. The oldest go first. |

### StreamHandle and StreamState

`stream.get()` returns a `StreamState`, and `stream.subscribe(fn)` hears new entries and keeps reading.

| Prop | Type | Default | Description |
| - | - | - | - |
| `entries` | `readonly T[]` | - | What has been read, oldest first, at most limit of them. |
| `offset` | `string` | - | Where reading goes on from. |
| `upToDate` | `boolean` | - | The last read reached the end of the stream. |
| `error` | `ConnectionError \| undefined` | - | The last read's failure. |

## Good 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`, `Timeout` or `OutcomeUnknown` is 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 `settleMs` runs out after the write is answered. If the write fails, the update is removed and `mutate` rejects. An update that throws is dropped on its own.
- `read` goes over the connection after the writes before it, so it sees every write this client already had answered.
- A handler that answers with a `Response` gives its body to `mutate` and `read`. A status of 400 or above throws `HttpError`.
- `iterate` sends one HTTP request. Breaking out of the loop stops the handler, and an error the handler raises after it started throws a `ConnectionError`.
- `stream` reads over HTTP and never keeps the luna awake. A read refused with a status below 500, other than 429, stops reading and sets `error`.
- `enqueue` needs a `store`. Each write goes once, with its `id` as 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 until `client.resumeWrites()`.
- The `done` promise 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

```ts app/list.ts
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

```ts app/list.ts
await list.mutate(
  "add",
  { text: "milk" },
  {
    optimistic: (local) =>
      local.update(items, (old) => [...old, { id: -1, text: "milk" }]),
  },
);
```

### Read once without following

```ts app/list.ts
const now = await list.read("all", {}, { timeoutMs: 5000 });
```

### Watch the connection

```ts app/list.ts
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](/realtime/push-to-connected-apps).

```ts app/room.ts
const room = client.luna("Room", "lobby");
const stop = room.on<{ text: string }>("said", (m) => console.log(m.text));
```

### Read a stream as it grows

```ts app/room.ts
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

```ts app/list.ts
const { id, done } = list.enqueue("add", { text: "eggs" });
```

### Read a handler's Response

```ts app/board.ts
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

```ts app/room.ts
for await (const n of room.iterate<number>("count", { to: 3 })) {
  console.log(n);
}
```
