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

Write handlers

Add handlers that read and change a luna's data, return results and answer calls over HTTP.

A handler is a function that callers run on one luna. Queries read the luna’s data, and every other handler may change it.

Add a handler

Handlers are returned from handlers. Each one is made with h, which takes the handler’s spec and the function to run.

import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string(), done: t.bool() }) },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      return ctx.db.items.insert({ text, done: false });
    }),
  }),
});

The function gets ctx, the luna it runs on, and the arguments. A handler’s name starts with a lowercase letter.

Read with a query

Give a handler query: true to make it read only. A query that tries to write fails.

all: h({ query: true }, (ctx) => ctx.db.items.find({ orderBy: "id" })),

Apps can subscribe to a query and get its new result whenever the data it read changes.

To let a read copy answer when the luna is busy, set how far behind the answer may be.

all: h({ query: { maxStale: "1s" } }, (ctx) => ctx.db.items.find({ orderBy: "id" })),

Change data

A handler without query may write. Its writes are kept together when it returns, and the caller gets its answer only once they are stored.

If the handler throws, every write it made is undone.

check: h({ args: { item: t.int() } }, (ctx, { item }) => {
  ctx.db.items.update({ where: { id: item }, set: { done: true } });
}),

Await without surprises

A handler may be async. The code between two awaits runs without anything else in between, but another call to the same luna may run while a handler awaits.

Give a handler exclusive: true when nothing else may run on the luna until it finishes.

clear: h({ exclusive: true }, async (ctx) => {
  await ctx.call(Archive, { id: ctx.key.id }).keep({ items: ctx.db.items.find() });
  ctx.db.items.delete({});
}),

Return a value

What a handler returns is sent to the caller as JSON. A handler that returns nothing answers null.

Declare returns to have Luna check the result before it is sent.

count: h({ query: true, returns: t.int() }, (ctx) => ctx.db.items.count()),

Refuse calls to lunas that do not exist

A call to a new key normally creates the luna. Give a handler requires: "exists" to refuse calls to a luna that has never been written to.

rename: h({ args: { name: t.string() }, requires: "exists" }, (ctx, { name }) => {
  // ...
}),

Those calls fail with NotFound.

Other handler options

h takes more options, each covered with its feature. Handler spec lists them all.

Option Feature
shared One run of a query for every app watching it with the same arguments
durable Runs that survive crashes and can wait for minutes or months
route An HTTP address of your choosing, with t.request() for the raw request
description A note kept with the handler

Use the context

ctx holds the luna’s data and what is known about the call. These are the members most handlers use, and ctx lists the rest.

Field Holds
ctx.key The luna’s key
ctx.db The luna’s tables
ctx.isNew True until the luna first keeps a write
ctx.caller Who made the call
ctx.env The environment’s secrets
ctx.deadline When the call must answer by, in milliseconds since 1970
ctx.now() The current time, in milliseconds since 1970
ctx.uuid() A new UUID

Call a handler over HTTP

Send a POST to the luna’s URL and the handler’s name, with the arguments as a JSON object.

curl -X POST "$LUNA_URL/List/groceries/add" \
  -H "luna-key: $LUNA_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text":"milk"}'

A handler that succeeds answers 200 with its result as the body. These headers change how a call runs.

Header Does
luna-timeout-ms Sets how long the call may take, in milliseconds, in place of the default 60 seconds
idempotency-key Runs a retried write once and returns the first result again
luna-read Lets a query take a read copy, with max-stale=<MS>, or insist on the latest data, with latest. at-least=<POSITION> asks for a copy that holds the writes up to a position ctx.position() returned

Next steps

Was this page helpful?