1. Pick a name

Your first functions, caller(), errors and the two state wrappers.

4 MIN READView Markdown ↗

The chat starts with a name. There are no accounts: each device picks a name, and the backend remembers it by device.

The backend#

Create entry/src/main/ets/pages/chat.api.ts:

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

const db = new Database('app.db')
db.run('create table if not exists people (device text primary key, name text not null unique collate nocase)')

export function getName(): string {
  return nameOf(caller().deviceId) ?? ''
}

export function setName(name: string): string {
  const clean = name.trim()
  if (clean === '' || clean.length > 20) throw new ApiError('BAD_REQUEST', 'Use 1 to 20 characters')
  const { deviceId } = caller()
  if (db.query('select 1 from people where name = ? and device != ?').get(clean, deviceId)) {
    throw new ApiError('CONFLICT', `${clean} is taken`)
  }
  db.run('insert into people (device, name) values (?, ?) on conflict (device) do update set name = excluded.name', [deviceId, clean])
  return clean
}

function nameOf(device: string): string | undefined {
  return db.query<{ name: string }, [string]>('select name from people where device = ?').get(device)?.name
}

What is going on:

  • Exported functions are endpoints. getName and setName can be called from the app; nameOf is not exported, so it stays private to the server.
  • 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: it only reads. Everything else is a mutation. The difference matters in a minute.
  • caller().deviceId is the id of the device that made the call. The app sends it with every request. It tells devices apart, but it is not a login: do not use it to protect anything valuable.
  • ApiError carries a code the screen can check. CONFLICT becomes HTTP 409, BAD_REQUEST becomes 400. Any other thrown error becomes INTERNAL, and its stack goes to the logs.
  • SQLite comes with Bun. app.db survives restarts and deploys; a variable at the top of the file does not.

Save the file. watch prints the generated client: chat.api.ets (getName, setName).

The screen#

Replace entry/src/main/ets/pages/Index.ets:

ArkTS
import { AsyncValue, LiveValue } from 'arkapi'
import { getName, setName } from './chat.api'

@Entry
@Component
struct Index {
  @State name: LiveValue<string> = new LiveValue(getName)
  @State saving: AsyncValue<string> = new AsyncValue()
  @State nameDraft: string = ''

  build() {
    Column({ space: 12 }) {
      if (this.name.data === null) {
        LoadingProgress().width(32).color('#8A8A99')
      } else if (this.name.data === '') {
        this.namePicker()
      } else {
        this.chat(this.name.data)
      }
    }
    .width('100%')
    .height('100%')
    .padding(16)
    .justifyContent(FlexAlign.Center)
    .backgroundColor('#101014')
  }

  @Builder
  namePicker() {
    Text('Pick a name').fontSize(22).fontColor('#FFFFFF')
    TextInput({ text: $$this.nameDraft, placeholder: 'Ada' })
      .fontColor('#FFFFFF')
      .placeholderColor('#77778A')
      .backgroundColor('#22222A')
    Button('Join')
      .width('100%')
      .fontColor('#FFFFFF')
      .backgroundColor('#4F6BF5')
      .enabled(!this.saving.loading)
      .onClick(() => { this.saving.run(setName(this.nameDraft)) })
    Text(this.nameError()).fontColor('#FF7B7B')
  }

  nameError(): string {
    if (this.saving.errorCode === 'CONFLICT') {
      return 'Someone already has that name'
    }
    if (this.saving.errorCode === 'BAD_REQUEST') {
      return 'Use 1 to 20 characters'
    }
    return this.saving.error ?? ''
  }

  @Builder
  chat(name: string) {
    Text(`Hi, ${name}`).fontSize(22).fontColor('#FFFFFF')
  }
}

The two wrappers are the whole client API:

  • LiveValue keeps a query's result on screen. data is null until the first answer arrives, so the screen shows a spinner, then the name picker (empty name) or the chat.
  • AsyncValue runs one call for a button. run(promise) sets loading while the call is in flight, then either data or error and errorCode.

Notice what is missing: after setName succeeds, nothing tells the screen to reload the name. ArkAPI re-runs live queries after every mutation and sends the results that changed. getName now returns the new name, so the screen switches to the chat by itself.

Check errorCode, not the message text. error is the full message, handy in logs; NETWORK means the device could not reach the backend.

Try it#

Run the app, pick a name, and you see "Hi, Ada". Now be a second device from the terminal. Every endpoint is a POST with the arguments as a JSON array:

Terminal
curl -X POST http://localhost:3000/api/pages.chat.setName \
  -H 'X-ArkAPI-Device: laptop' -d '{"args": ["ada"]}'

The answer is 409 with {"error": "ada is taken", "code": "CONFLICT"}. The name column ignores case, so ada and Ada are the same name. Try {"args": [42]} too: the server checks the arguments against the signature and answers 400 before setName runs.

Next: live messages.

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