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

Handler spec

The h(spec, run) factory and every field of HandlerSpec, with raw request handlers and streaming handlers.

h(spec, run) declares one handler: spec says what it takes, returns and may fail with, and run is its code.

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() }) },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      ctx.db.items.insert({ text });
    }),
  }),
});

Reference

h(spec, run)

h is passed to the handlers option of defineLuna, typed for that luna type.

PropType
specHandlerSpec

What the handler takes and how it runs.

TypeHandlerSpec
run(ctx, input) => R | Promise<R> | AsyncGenerator

The code. input holds the key fields and the arguments in one object.

Type(ctx, input) => R | Promise<R> | AsyncGenerator

Returns a Handler, with spec and run as given.

HandlerSpec

PropType
args?Record<string, Ty> | t.request()

The arguments, checked before run starts. t.request() takes the raw HTTP request instead.

TypeRecord<string, Ty> | t.request()
Default{}
returns?Ty

The result's type, checked before the result is sent. Without it, any JSON.

TypeTy
errors?Record<string, Ty>

The errors the handler may fail with, by code, each with the type of its data.

TypeRecord<string, Ty>
query?boolean | { maxStale: number | string }

Makes the handler read only. With maxStale, a read copy this far behind may answer calls from outside while the luna is busy.

Typeboolean | { maxStale: number | string }
Defaultfalse
shared?boolean

For a query whose result depends only on its arguments and the luna's data: apps subscribed to the same query share one run each time the data changes.

Typeboolean
Defaultfalse
exclusive?boolean

No other handler starts on the luna until this one finishes.

Typeboolean
Defaultfalse
requires?"exists"

Refuses calls to a luna that has no stored data yet, with NotFound.

Type"exists"
durable?boolean

Each call or message starts a durable run that survives crashes and can wait with ctx.step, ctx.sleep and ctx.waitFor.

Typeboolean
Defaultfalse
route?string | RouteSpec

An HTTP method and path that also reach the handler, such as "GET /lists/:id".

Typestring | RouteSpec
description?string

What the handler does. Kept with the app, and given no other meaning.

Typestring

RouteSpec

The long form of route. Serve HTTP routes covers each field.

PropType
pathstring

A method (GET, POST, PUT, PATCH or DELETE) and a path with :params and an optional trailing *.

Typestring
auth?"none" | "token" | "publishable"

Who may call the route.

Type"none" | "token" | "publishable"
Default"publishable" for a public type, "token" for a private one
cors?{ origins: string[]; credentials?: boolean; headers?: string[]; exposeHeaders?: string[]; maxAge?: number | string }

Browsers on other sites that may read the answers.

Type{ origins: string[]; credentials?: boolean; headers?: string[]; exposeHeaders?: string[]; maxAge?: number | string }
rateLimit?{ limit: number; window: number | string; per?: "ip" | "credential" }

At most limit requests each window, per IP address by default. More are refused with 429.

Type{ limit: number; window: number | string; per?: "ip" | "credential" }
errors?Record<string, number>

The HTTP status for each declared error code. Others answer 422.

TypeRecord<string, number>
key?Record<string, string>

Where key fields not in the path come from: "query:<NAME>", "header:<NAME>" or "param:<NAME>".

TypeRecord<string, string>

Good to know

  • A handler’s name starts with a lower-case letter and holds letters, digits and _, up to 64 characters. An error code starts with a capital letter.
  • Arguments that do not match args fail the call with Invalid. Unknown fields are refused, and an optional argument may be left out or null.
  • A result that does not match returns fails the call with Internal, and so does ctx.fail with a code that is not in errors.
  • A declared error from a luna you called passes through your handler when your handler declares the same code. Otherwise it reaches your caller as Internal.
  • A query that writes fails with Internal.
  • A durable handler cannot be a query, stream, or take the raw request.
  • A handler with args: t.request() declares no other arguments. Called by name instead of through its route, its arguments arrive as a JSON body.
  • Any handler may return a web Response. A route sends it as it is. A caller through an SDK gets its body, or an HttpError when the status is 400 or above.
  • An async function* handler streams what it yields. Through a route each value goes out as it comes, and sse() gives it an id or event name. A caller that cannot stream, such as another luna, gets an array of everything yielded once the handler ends.

Examples

Check the result and refuse with an error

add: h(
  { args: { text: t.string({ maxLength: 200 }) }, returns: t.int(), errors: { Full: t.object({ limit: t.int() }) } },
  (ctx, { text }) => {
    if (ctx.db.items.count() >= 100) ctx.fail("Full", { limit: 100 });
    return ctx.db.items.insert({ text });
  },
),

Share one live query between apps

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

Refuse calls to lists that do not exist

rename: h({ args: { item: t.int(), text: t.string() }, requires: "exists" }, (ctx, { item, text }) => {
  ctx.db.items.update({ where: { id: item }, set: { text } });
}),

Take the raw request

The :id parameter fills the id key field.

hook: h({ args: t.request(), route: { path: "POST /lists/:id/hook", auth: "none" } }, async (ctx, req) => {
  if (req.headers.get("x-token") !== ctx.env.HOOK_TOKEN) return new Response("wrong token", { status: 401 });
  const { text } = (await req.json()) as { text: string };
  ctx.db.items.insert({ text });
  return new Response(null, { status: 204 });
}),

Stream server-sent events

Import sse from "luna".

progress: h({ route: "GET /lists/:id/progress" }, async function* (ctx) {
  for (const item of ctx.db.items.find({ orderBy: "id" })) {
    yield sse({ data: item, id: item.id });
  }
}),

Was this page helpful?