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

Check arguments with types

Declare a handler's arguments with t, so every call is checked before it reaches your code.

A handler’s arguments come from outside, so they can be anything. Declare them with t, and Luna refuses a call with the wrong arguments before your code runs.

Declare arguments

List each argument and its type under args. The handler receives them already checked, with TypeScript types to match.

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

The types

Type Accepts
t.string() Text. t.string({ maxLength: 200 }) caps its length in characters
t.int() A whole number that fits in 64 bits
t.float() Any number
t.bool() true or false
t.timestamp() Milliseconds since 1970, as a whole number
t.uuid() A UUID such as 0b4f0d7e-6a1e-4c55-9d4f-5f2c3a9b8e10
t.bytes() Bytes, written as base64
t.enum(["low", "high"]) One of the listed strings
t.array(t.string()) A list, with every item checked
t.object({ ... }) An object with exactly the fields listed
t.json() Any JSON value, unchecked

Tables have a few column types of their own, and t.request() takes the raw HTTP request in place of arguments. t lists every type. Add .describe("...") to an argument to say what it means. The text shows in your app’s OpenAPI document.

Make an argument optional

Add .optional() and the argument may be left out or sent as null. In the handler it is undefined when it was left out, and null when it was sent as null.

args: { text: t.string(), note: t.string().optional() },

Nest objects and lists

t.object and t.array hold other types. An object refuses fields it does not list.

args: {
  items: t.array(t.object({ text: t.string(), tags: t.array(t.string()) })),
},

What a caller gets for wrong arguments

A call with wrong arguments fails with 400 and the code Invalid. The message names the argument and what was wrong.

{ "error": { "code": "Invalid", "message": "input.text: missing" } }

Luna never converts a value. The string "5" is not an int, and the number 5 is not a string.

Use the TypeScript type

Infer turns a t type into the TypeScript type it accepts.

import { t, type Infer } from "luna";

export const Item = t.object({ text: t.string(), done: t.bool() });
export type Item = Infer<typeof Item>;

The same types describe keys, table columns, a handler’s returns and the data of its errors.

Next steps

Was this page helpful?