Platform API Reference

Every Roost app server receives a set of platform services through its base class. These are available as this.db, this.events, this.media, and so on. This page documents every method, its arguments, and return types.

Note: All services are accessed through this in your Server class, which extends the generated BaseServer. Your server also has this.userID (the current user's ID, set when open() is called).

Database — this.db

Each app gets its own SQLite database (WAL mode, serialized writes). Migrations in server/migrations/ are applied automatically.

db.get<R>(q, ...vars)

Execute a SQL query and return the first matching row. Use a TypeScript generic to type the result.

ParameterTypeDescription
qstringSQL query with ? placeholders
...varsunknown[]Bind values for the placeholders

Returns: Promise<R>

const row = await this.db.get<{ id: number; title: string }>(
  `SELECT * FROM todos WHERE id = ?`, todoId
)

db.all<R>(q, ...vars)

Execute a SQL query and return all matching rows as an array.

ParameterTypeDescription
qstringSQL query with ? placeholders
...varsunknown[]Bind values for the placeholders

Returns: Promise<R[]>

db.run(q, ...vars)

Execute a write query (INSERT, UPDATE, DELETE). Returns metadata about the operation.

ParameterTypeDescription
qstringSQL statement with ? placeholders
...varsunknown[]Bind values for the placeholders

Returns: Promise<RunResult>

const result = await this.db.run(
  `INSERT INTO todos (user_id, title) VALUES (?, ?)`,
  this.userID, "Buy milk"
)
// result.lastInsertedId — the auto-increment ID of the new row
// result.rowsAffected  — number of rows changed

db.tx<T>(fn)

Run multiple queries inside a transaction. If the callback throws, all changes are rolled back. The tx object exposes the same get, all, and run methods.

ParameterTypeDescription
fn(tx: Tx) => Promise<T>Callback receiving the transaction handle

Returns: Promise<T> — the value returned by the callback.

await this.db.tx(async (tx) => {
  await tx.run(`UPDATE accounts SET balance = balance - ? WHERE id = ?`, amount, from)
  await tx.run(`UPDATE accounts SET balance = balance + ? WHERE id = ?`, amount, to)
})

Events — this.events

Broadcast real-time messages to connected clients. Events are defined in your schema.json and delivered over the WebSocket connection.

events.emit(m)

Send an event to the current user (all their connected clients).

ParameterTypeDescription
mAppEventsEvent object with eventType discriminator

Returns: Promise<void>

events.emitAll(m)

Broadcast an event to all connected users of the app.

ParameterTypeDescription
mAppEventsEvent object with eventType discriminator

Returns: Promise<void>

events.emitUser(userID, m)

Send an event to a specific user by their ID.

ParameterTypeDescription
userIDstringTarget user ID
mAppEventsEvent object with eventType discriminator

Returns: void

Media — this.media

Process audio, video, and image files. All methods work with file IDs (digests) from uploaded files.

media.extractAudio(fileID)

Extract metadata from an audio file using FFprobe: duration, bitrate, codec, artist, album, track number, and more.

ParameterTypeDescription
fileIDstringFile digest of the audio file

Returns: Promise<AudioMetadata>

media.extractTags(fileIDs)

Extract embedded tag data (artist, album, year, genre, cover art) from multiple audio files. Uses majority voting across files for consistency. No external lookups.

ParameterTypeDescription
fileIDsstring[]Array of file digests

Returns: Promise<TagData>

media.transcodeVideo(fileID, options?)

Transcode a video file via FFmpeg for browser-compatible playback. Optionally receive progress updates and a cancel handle.

ParameterTypeDescription
fileIDstringFile digest of the video
optionsTranscodeVideoOptionsOptional progress/cancel callbacks

Returns: Promise<TranscodeResult>

media.transcodeAudio(fileID)

Transcode an audio file for browser-compatible playback.

ParameterTypeDescription
fileIDstringFile digest of the audio file

Returns: Promise<TranscodeResult>

media.resizeImageWidth(fileID, width)

Resize an image to the given width (preserving aspect ratio) using libvips. Returns the file ID of the resized image.

ParameterTypeDescription
fileIDstringFile digest of the image
widthnumberTarget width in pixels

Returns: Promise<{ fileID: string }>

Properties

PropertyTypeDescription
media.currentAudioTransformstringThe FFmpeg transform string used for audio transcoding
media.currentVideoTransformstringThe FFmpeg transform string used for video transcoding

System — this.system

System utilities for file management, notifications, and background work.

system.scheduleWork()

Schedule background work. The platform will call your server's work() method (if defined) in the near future. Useful for deferring heavy processing so it doesn't block the current request.

Returns: void

system.notify(userId, subject, body)

Send a push notification to a user. On iOS, this triggers an APNs notification. On web, it sets the app badge.

ParameterTypeDescription
userIdstringTarget user ID
subjectstringNotification title
bodystringNotification body text

Returns: void

system.getFileInfo(fileDigest)

Get metadata about an uploaded file: name, MIME type, extension, size, and creation date.

ParameterTypeDescription
fileDigeststringFile digest

Returns: Promise<UploadedFileInfo>

system.readFile(fileID)

Read the contents of an uploaded file as a string.

ParameterTypeDescription
fileIDstringFile digest

Returns: Promise<string>

system.listFiles(opts)

List uploaded files with optional search, sorting, and pagination.

ParameterTypeDescription
optsListFilesOptionsSearch, sort, and pagination options

Returns: Promise<ListFilesResult>

system.registerInterest(fileDigest)

Register that this app uses a file. Prevents the file from being garbage-collected even if the user who uploaded it deletes it.

ParameterTypeDescription
fileDigeststringFile digest

Returns: Promise<void>

system.registerDisinterest(fileDigest)

Unregister interest in a file. If no other app or user references the file, it becomes eligible for garbage collection.

ParameterTypeDescription
fileDigeststringFile digest

Returns: Promise<void>

system.setBadge(count)

Set the unread badge count for this app. Displayed in the app launcher sidebar. Set to 0 to clear.

ParameterTypeDescription
countnumberBadge count (0 to clear)

Returns: void

Users — this.users

Query information about users on the Roost instance.

users.list()

Returns all users on the Roost instance. Each user object includes their ID, display name, username, email, avatar digest, and primary color.

Returns: Promise<User[]>

HTTP — this.http

Make outbound HTTP requests from your server. Useful for fetching external APIs or downloading files.

http.get(url)

Make an HTTP GET request and return the response status and body.

ParameterTypeDescription
urlstringURL to fetch

Returns: Promise<HttpResponse>

const resp = await this.http.get("https://api.example.com/data")
if (resp.status === 200) {
  const data = JSON.parse(resp.body)
}

http.saveToFile(url, fileName)

Download a URL and save it as an uploaded file. Returns the file digest of the saved file, which can be used with other services like media or system.

ParameterTypeDescription
urlstringURL to download
fileNamestringName to give the saved file

Returns: Promise<string> — the file digest

Type reference

These types are used as parameters and return values throughout the platform API. They are automatically available in your server code via the generated interface.ts.

RunResult

FieldTypeDescription
lastInsertedIdnumberAuto-increment ID of the last inserted row
rowsAffectednumberNumber of rows changed by the query

User

FieldTypeDescription
idstringUnique user identifier
namestringDisplay name
usernamestringUsername
emailstringEmail address
avatarstringAvatar file digest
primaryColorstringUser's chosen accent color

AudioMetadata

FieldTypeDescription
durationnumberDuration in seconds
bitratenumberBitrate in bits/sec
sizenumberFile size in bytes
artiststringTrack artist
albumArtiststringAlbum artist
titlestringTrack title
albumstringAlbum name
commentstringComment metadata
composerstringComposer
releaseYearnumberRelease year
trackstringTrack number (e.g. "3/12")
discstringDisc number
genrestringGenre
formatstringContainer format
codecstringAudio codec
codecLongNamestringFull codec name
channelsnumberNumber of audio channels
sampleRatenumberSample rate in Hz (optional)

TagData

FieldTypeDescription
artiststringArtist name (majority vote)
albumArtiststringAlbum artist
albumstringAlbum name
yearnumberRelease year
genrestringGenre
albumArtIDstringFile digest of embedded cover art

HttpResponse

FieldTypeDescription
statusnumberHTTP status code
bodystringResponse body as string

TranscodeResult

FieldTypeDescription
fileIDstringFile digest of the transcoded file
transcodedbooleanWhether transcoding was needed (false if already compatible)
contentTypestringMIME type of the output file

TranscodeVideoOptions

FieldTypeDescription
onProgress?(pct: number) => voidCalled with progress percentage (0–100)
onCancel?(cancel: () => void) => voidCalled with a function to cancel transcoding

UploadedFileInfo

FieldTypeDescription
namestringOriginal file name
mimestringMIME type
extensionstringFile extension (e.g. "jpg")
sizenumberFile size in bytes
createdAtnumberUpload timestamp (Unix seconds)

ListFilesOptions

FieldTypeDescription
search?stringFilter files by name
sortBy?stringSort field (e.g. "createdAt", "name", "size")
sortDir?string"asc" or "desc"
cursor?stringPagination cursor from a previous result

ListFilesResult

FieldTypeDescription
itemsFileItem[]Array of files (digest, name, mime, extension, size, createdAt)
totalnumberTotal number of matching files
pageInfo{ hasMore, cursor }Pagination info for fetching the next page