The app works on your computer. Now put the backend online, so people can chat from anywhere.
Deploy#
Create an account once per machine, then deploy:
bunx arkapi signup --email [email protected]
bunx arkapi deploy
Already have an account? Use bunx arkapi login --email [email protected] instead of signup.
The first deploy creates your app and writes its id to arkapi.config.ts. Every deploy bundles the backend, uploads it, and regenerates the client so it points to the hosted URL. The host starts the new version next to the old one and switches only when it answers; open sockets move over. app.db and uploaded files stay where they are.
Give the hosted backend its announcement token. Setting a variable restarts the backend:
bunx arkapi env set ANNOUNCE_TOKEN=pick-a-long-random-token
Rebuild the app#
The backend URL and the types are compiled into the app, so build and install it again after a deploy, from DevEco Studio. Your local app.db stays on your computer: on the hosted service everyone starts without a name.
The deploy prints the app's URL. Announcements now go there:
curl -X POST https://arkapi.emincanozcan.com/apps/<your app id>/http/announce \
-H 'Authorization: Bearer pick-a-long-random-token' -d 'We are live'
Watch it run#
bunx arkapi open
The dashboard shows requests and errors per minute, every endpoint with its call count and timing, recent errors with their code and message, the tables in app.db, the logs, and the environment variables. To follow the logs in the terminal, including each job cleanup ok line:
bunx arkapi logs -f
Every deploy is listed in the dashboard. If one goes wrong, Roll back switches to an earlier version.
Keep going#
bunx arkapi watch points the client at your computer again; run deploy before you build an app for the hosted backend. When you change a function's signature, the app you built earlier still works for the calls that match, and the rest fail with a message to rebuild.
You have used all of ArkAPI. The other chapters cover each part in more detail: server functions, calling from ArkTS, errors, files, HTTP routes, jobs, and the hosted service's limits.
The whole app#
entry/src/main/ets/pages/chat.api.ts:
import { Database } from 'bun:sqlite'
import { ApiError, caller, event, every, files, online, type Routes } from 'arkapi/server'
export interface Message {
id: number
name: string
text: string
photoUrl: string | null
mine: boolean
}
interface MessageRow {
id: number
name: string
text: string
photo: string | null
mine: number
}
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)')
db.run('create table if not exists messages (id integer primary key, device text not null, text text not null, photo text, at integer not null)')
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
}
export function getMessages(): Message[] {
const rows = db.query<MessageRow, [string]>(`
select m.id, coalesce(p.name, 'Announcement') as name, m.text, m.photo, m.device = ? as mine
from messages m left join people p on p.device = m.device
order by m.id desc limit 100`).all(caller().deviceId)
return rows.reverse().map((row) => ({
id: row.id, name: row.name, text: row.text, mine: row.mine === 1,
photoUrl: row.photo === null ? null : files.url(row.photo),
}))
}
export function sendMessage(text: string): void {
const clean = text.trim()
if (clean === '') throw new ApiError('BAD_REQUEST', 'Write something first')
save(me(), clean, null)
}
export function sendPhoto(fileId: string): void {
if (!files.list().some((file) => file.id === fileId)) throw new ApiError('NOT_FOUND', 'Upload the photo first')
save(me(), '', fileId)
}
export function countOnline(): number {
return online().length
}
export interface Typing {
name: string
}
export const typing = event<Typing>()
export function setTyping(): void {
const device = me()
typing.send(online().filter((other) => other !== device), { name: nameOf(device)! })
}
export const routes: Routes = {
'POST /announce': async (req) => {
const token = process.env.ANNOUNCE_TOKEN
if (!token || req.headers.get('Authorization') !== `Bearer ${token}`) {
throw new ApiError('UNAUTHORIZED', 'Wrong token')
}
save('announcement', await req.text(), null)
return new Response('ok')
},
}
every('1h', function cleanup() {
const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
const old = db.query<{ photo: string }, [number]>('select photo from messages where at < ? and photo is not null').all(weekAgo)
db.run('delete from messages where at < ?', [weekAgo])
old.forEach((row) => files.remove(row.photo))
})
function me(): string {
const { deviceId } = caller()
if (!nameOf(deviceId)) throw new ApiError('UNAUTHORIZED', 'Pick a name first')
return deviceId
}
function save(device: string, text: string, photo: string | null): void {
db.run('insert into messages (device, text, photo, at) values (?, ?, ?, ?)', [device, text, photo, Date.now()])
}
function nameOf(device: string): string | undefined {
return db.query<{ name: string }, [string]>('select name from people where device = ?').get(device)?.name
}
entry/src/main/ets/pages/Index.ets:
import { AsyncValue, Listening, LiveValue } from 'arkapi'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { countOnline, getMessages, getName, Message, onTyping, sendMessage, sendPhoto, setName, setTyping, Typing, uploadFile } from './chat.api'
@Entry
@Component
struct Index {
@State name: LiveValue<string> = new LiveValue(getName)
@State saving: AsyncValue<string> = new AsyncValue()
@State nameDraft: string = ''
@State messages: LiveValue<Message[]> = new LiveValue(getMessages)
@State online: LiveValue<number> = new LiveValue(countOnline)
@State sending: AsyncValue<void> = new AsyncValue()
@State draft: string = ''
@State typist: string = ''
private typing: Listening | null = null
private typedAt: number = 0
private typistAt: number = 0
aboutToAppear(): void {
this.typing = onTyping((event: Typing) => {
this.typist = event.name
this.typistAt = Date.now()
setTimeout(() => {
if (Date.now() - this.typistAt >= 3000) {
this.typist = ''
}
}, 3000)
})
}
aboutToDisappear(): void {
this.typing?.stop()
}
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(`${name} · ${this.online.data ?? 0} online`).fontSize(12).fontColor('#8A8A99')
List({ space: 8 }) {
ForEach(this.messages.data ?? [], (message: Message) => {
ListItem() {
this.bubble(message)
}
}, (message: Message) => `${message.id}`)
}
.width('100%')
.layoutWeight(1)
.stackFromEnd(true)
Text(this.typist === '' ? '' : `${this.typist} is typing…`).fontSize(11).fontColor('#8A8A99')
Row({ space: 8 }) {
Button('+')
.fontColor('#FFFFFF')
.backgroundColor('#2A2A33')
.enabled(!this.sending.loading)
.onClick(() => { this.sending.run(this.pickPhoto()) })
TextInput({ text: $$this.draft, placeholder: 'Message' })
.layoutWeight(1)
.fontColor('#FFFFFF')
.placeholderColor('#77778A')
.backgroundColor('#22222A')
.onChange(() => this.typed())
.onSubmit(() => this.send())
Button('Send')
.fontColor('#FFFFFF')
.backgroundColor('#4F6BF5')
.enabled(!this.sending.loading)
.onClick(() => this.send())
}
}
@Builder
bubble(message: Message) {
Column({ space: 2 }) {
Text(message.name).fontSize(11).fontColor('#8A8A99')
if (message.photoUrl !== null) {
Image(message.photoUrl).width(180).borderRadius(14)
} else {
Text(message.text)
.fontSize(15)
.fontColor('#FFFFFF')
.padding({ left: 12, right: 12, top: 8, bottom: 8 })
.borderRadius(14)
.backgroundColor(message.mine ? '#4F6BF5' : '#2A2A33')
}
}
.width('100%')
.alignItems(message.mine ? HorizontalAlign.End : HorizontalAlign.Start)
}
typed(): void {
if (Date.now() - this.typedAt > 2000) {
this.typedAt = Date.now()
setTyping().catch(() => {})
}
}
async pickPhoto(): Promise<void> {
try {
const options = new photoAccessHelper.PhotoSelectOptions()
options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE
options.maxSelectNumber = 1
const picked = await new photoAccessHelper.PhotoViewPicker().select(options)
if (picked.photoUris.length > 0) {
const photo = await uploadFile(picked.photoUris[0])
await sendPhoto(photo.id)
}
} catch (error) {
throw error as Error
}
}
send(): void {
this.sending.run(sendMessage(this.draft)).then(() => {
if (this.sending.error === null) {
this.draft = ''
}
})
}
}