SirannonClient connects to one Sirannon server through HTTP or WebSocket. Both transports execute database operations, while WebSocket also supports change subscriptions and live queries.
The complete client.ts file below connects to the authenticated server.ts from the server guide. Start that server first, then provide the same SIRANNON_TOKEN to this Node process.
Connect and read
Pass an http:// or https:// base URL for either transport. The client derives the WebSocket URL when necessary. operationRef provides a registered operation identifier and its argument and row types.
import { type LiveUpdate, operationRef } from '@delali/sirannon-db'
import { SirannonClient } from '@delali/sirannon-db/client'
interface Order {
id: number
total: number
status: string
}
const token = process.env.SIRANNON_TOKEN
if (!token) throw new Error('Set SIRANNON_TOKEN to the server operator credential')
const ordersByStatus = operationRef<{ status: string }, Order>('ordersByStatus')
const placeOrder = operationRef<{ total: number }>('placeOrder')
const client = new SirannonClient('http://127.0.0.1:9876', {
transport: 'websocket',
headers: { Authorization: `Bearer ${token}` },
autoReconnect: true,
})
try {
const db = client.database('orders')
const before = await db.query(ordersByStatus, { status: 'pending' })
console.log('Pending orders before the write:', before.length)
const pending = await db.live(ordersByStatus, { status: 'pending' })
const delivered = Promise.withResolvers<void>()
const deadline = setTimeout((): void => delivered.reject(new Error('Live delivery exceeded the example deadline')), 5000)
const unsubscribe = pending.subscribe((_update: LiveUpdate<Order>): void => {
const state = pending.getState()
if (state.status === 'error') delivered.reject(state.error)
if (state.status === 'ready' && state.rows.length > before.length) delivered.resolve()
})
try {
console.log(await db.execute(placeOrder, { total: 2400 }))
await delivered.promise
console.log(pending.getState())
} finally {
clearTimeout(deadline)
unsubscribe()
await pending.close()
}
} finally {
client.close()
}The server's stored orders determine the printed values, so this example has no fixed result panel. query returns an array; check its first element for undefined when expecting one row.
A manually declared reference provides TypeScript types without runtime row validation. Code generation derives references and registry digests from the server's definitions.
Run a write
execute(operation, args) invokes a registered write. The server executes its statements in one transaction and returns a result per statement.
The registry refuses missing arguments with MISSING_ARGUMENT and undeclared arguments with ARGUMENT_NOT_ALLOWED. An identity-derived argument comes from the server's authenticated context, so a caller cannot supply it.
A lost reply leaves a write's outcome uncertain. Use stable operation identifiers or idempotent application writes when a caller can retry after a disconnect.
Subscribe to changes
await db.on(table).subscribe(callback, options?) opens a row-change feed. The server must watch that table. The returned handle's unsubscribe() closes the feed.
An ordinary table subscription can expose rows outside a registered read. The server therefore requires either acceptSql: true or an onBeforeSubscribe hook that authorises the table and filter. The server example on this page's linked guide keeps SQL disabled and demonstrates a registered live query.
Use SubscribeOptions.onError for callback failures, malformed change frames, and a server refusal during restoration. A restoration refusal ends the subscription after reporting the error. Temporary connection failures can reconnect.
onReset means that the server cannot replay the earlier cursor. Reload application state before treating the continued stream as current. Subscription resumption explains durable cursors and epochs.
Keep a result current
db.live(operation, args) opens a registered read as a live query. Its handle exposes getState(), subscribe(), and close().
The server sends the first rows and later splices. During a disconnect, the client retains earlier rows and reports revalidation. Reconnection opens the registered read again and replaces those rows with the server's fresh answer.
A registry mismatch causes one capability refresh and retry. A second refusal fails the query. Both live queries and row subscriptions require WebSocket and fail with TRANSPORT_ERROR over HTTP.
Send a statement
A server with acceptSql: true also permits query(sql, params), execute(sql, params), transaction(statements), batch(sql, paramsBatch), and load(sql, paramsBatch, durability?, checkpoint?).
A remote transaction accepts a fixed statement array in one request. It provides no callback transaction that retains the server's writer between network requests. A batch executes one statement with several parameter sets atomically.
The client caches GET /capabilities. If a report omits query.sql, the client refuses SQL with SQL_NOT_ACCEPTED before sending it. For compatibility with an older server whose capability endpoint returns NOT_FOUND, it permits the SQL request and lets that server decide. Closing the client aborts an outstanding capability fetch and prevents later requests.
Bind parameters separately from SQL. Value encoding preserves large integers and BLOBs on both transports.
Import a large dataset
loadAll(sql, rows, options?) accepts an iterable or asynchronous iterable and sends sequential batches. It returns summed rowsLoaded and changes.
Each batch restores the configured durability before replying. The final batch requests a checkpoint, subject to the database's backup configuration. Every encoded batch must fit within maxBodyBytes. Bulk loading includes a complete import example and the available durability policies.
Ask for a fresher read
A single-server client can pass { readConcern: { level: 'linearizable' } } or another supported concern as the query's options argument. A replication execution target enforces that concern; a plain core database provides no distributed guarantee.
Topology-aware routing uses a client-wide concern to select a node. It refuses a per-call concern with INVALID_ARGUMENT, so the caller cannot accidentally request a level that routing does not enforce.
When the server refuses your credential
A WebSocket upgrade refusal uses close code 4401 for unauthenticated access and 4403 for forbidden access. The client converts these into UNAUTHORIZED and FORBIDDEN. It also treats application codes from 4000 to 4099 as terminal credential refusals.
The refused connection stays closed and later calls receive the refusal. Obtain a fresh credential and construct a new client. Other disconnects can reconnect when autoReconnect is enabled.
The server closes a connection whose outbound buffer exceeds its limit with 4290. Graceful shutdown uses 1001. Neither close code is a credential refusal.
Client options
| Option | Default | Behaviour |
|---|---|---|
transport | 'websocket' | The client also accepts 'http'. |
headers | none | The client adds these headers to HTTP requests and, on Node and Bun, to WebSocket upgrades. |
webSocketProtocols | none | The client offers a string or array of credential subprotocols after sirannon.v1. |
autoReconnect | true | The WebSocket transport retries temporary disconnects. |
reconnectInterval | 1000 | The value sets the reconnect delay in milliseconds. |
requestTimeout | 30000 | The value sets the request deadline in milliseconds; zero removes it. |
A browser WebSocket provides no custom-header API. A browser client with headers and no webSocketProtocols fails at construction with INVALID_ARGUMENT. Send an HTTP bearer credential through headers and a short-lived ticket through subprotocols, as security explains.
Subprotocols must be distinct, non-empty HTTP tokens. Spaces, commas, and quotation marks fail validation. Standard base64 can include / and =, so use unpadded base64url for a ticket. Invalid-header and subprotocol errors identify the entry's position without repeating its credential.
Routing options such as endpoints and readPreference belong to TopologyAwareClient, not SirannonClient. Invalid routing options fail at construction with INVALID_ARGUMENT. Keep the topology entry outside browser bundles.
client.close() closes every database transport and cancels capability checks. Later work fails with TRANSPORT_ERROR. Handle errors through the exported RemoteError class and its code, while keeping credential and internal error details out of public messages.