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.
specHandlerSpec
What the handler takes and how it runs.
HandlerSpecrun(ctx, input) => R | Promise<R> | AsyncGenerator
The code. input holds the key fields and the arguments in one object.
(ctx, input) => R | Promise<R> | AsyncGeneratorReturns a Handler, with spec and run as given.
HandlerSpec
args?Record<string, Ty> | t.request()
The arguments, checked before run starts. t.request() takes the raw HTTP request instead.
Record<string, Ty> | t.request(){}returns?Ty
The result's type, checked before the result is sent. Without it, any JSON.
Tyerrors?Record<string, Ty>
The errors the handler may fail with, by code, each with the type of its data.
Record<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.
boolean | { maxStale: number | string }falseshared?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.
booleanfalseexclusive?boolean
No other handler starts on the luna until this one finishes.
booleanfalserequires?"exists"
Refuses calls to a luna that has no stored data yet, with NotFound.
"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.
booleanfalseroute?string | RouteSpec
An HTTP method and path that also reach the handler, such as "GET /lists/:id".
string | RouteSpecdescription?string
What the handler does. Kept with the app, and given no other meaning.
stringRouteSpec
The long form of route. Serve HTTP routes covers each field.
pathstring
A method (GET, POST, PUT, PATCH or DELETE) and a path with :params and an optional trailing *.
stringauth?"none" | "token" | "publishable"
Who may call the route.
"none" | "token" | "publishable""publishable" for a public type, "token" for a private onecors?{ origins: string[]; credentials?: boolean; headers?: string[]; exposeHeaders?: string[]; maxAge?: number | string }
Browsers on other sites that may read the answers.
{ 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.
{ limit: number; window: number | string; per?: "ip" | "credential" }errors?Record<string, number>
The HTTP status for each declared error code. Others answer 422.
Record<string, number>key?Record<string, string>
Where key fields not in the path come from: "query:<NAME>", "header:<NAME>" or "param:<NAME>".
Record<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
argsfail the call withInvalid. Unknown fields are refused, and an optional argument may be left out ornull. - A result that does not match
returnsfails the call withInternal, and so doesctx.failwith a code that is not inerrors. - 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 anHttpErrorwhen the status is 400 or above. - An
async function*handler streams what it yields. Through a route each value goes out as it comes, andsse()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 });
}
}),