Server functions

Your function signature is the contract.

2 MIN READView Markdown ↗

Every exported function in a *.api.ts file is an endpoint. It runs on Bun, on the server, never on the device.

TypeScript
import { Database } from 'bun:sqlite'
import { ApiError, caller } from 'arkapi/server'

interface Todo {
  id: number
  title: string
}

const db = new Database('app.db')
db.run('create table if not exists todos (id integer primary key, device_id text, title text)')

export function listTodos(): Todo[] {
  return db.query<Todo, [string]>('select id, title from todos where device_id = ?').all(caller().deviceId)
}

export function addTodo(title: string): number {
  if (!title.trim()) throw new ApiError('BAD_REQUEST', 'Add a title')
  return Number(db.run('insert into todos (device_id, title) values (?, ?)', [caller().deviceId, title]).lastInsertRowid)
}

Types that cross the wire#

string, number, boolean, arrays, interfaces, unions with null, Record<string, T>, and void as a return type. Optional and default parameters work when they come last. Date, Map, classes, any and functions do not cross the wire; send timestamps as numbers and maps as records. Generate stops with unsupported type and names the parameter.

Interfaces you define in the api file appear in the generated client with the same names, so the screen uses Todo too.

Validation#

Before a function runs, the server checks the arguments against its signature. addTodo(42) fails with 400 and args[0]: expected string, got number, and addTodo never runs.

Queries and mutations#

A function whose name starts with get, list, find, search, count, has, is or load, followed by an uppercase letter or the end of the name (getMessages, isOnline; not getaway), is a query. Everything else is a mutation. Queries can back live data; after every mutation, live queries are re-run and changed results reach every screen.

Who is calling#

caller().deviceId is a stable id of the calling device. Use it to keep data per device. It is sent by the app, so it identifies a device; it does not prove who the person is. online() lists the devices connected right now.

State#

Keep state in SQLite. app.db lives in the app's own directory and survives deploys and restarts. Module-level variables start over on every deploy. Bun APIs, fetch and npm packages all work; packages are bundled on deploy.

Tab to navigate results · Enter to open · Esc to close