The LarkDatabase class is the main entry point for interacting with a Lark database. It manages the connection lifecycle, authentication, and provides access to database references.
Constructor
new LarkDatabase(projectAndDatabase: string, options?: LarkDatabaseOptions)
Creates a new LarkDatabase instance.
| Parameter | Type | Description |
|---|
projectAndDatabase | string | A combined identifier in the format 'projectId/databaseId'. |
options | LarkDatabaseOptions | Optional configuration object. |
LarkDatabaseOptions
| Option | Type | Default | Description |
|---|
anonymous | boolean | false | Connect without user credentials. |
token | string | — | A JWT for authenticated access. |
domain | string | 'larkdb.net' | The Lark server domain. |
transport | 'auto' | 'websocket' | 'webtransport' | 'websocket' | Which transport protocol to use. |
webtransportTimeout | number | 2000 | Milliseconds to wait for WebTransport before falling back to WebSocket. Only applies when transport is 'auto'. |
You must provide either anonymous: true or a token. If you pass both, the token takes priority.
import { LarkDatabase } from '@lark-sh/client';
const db = new LarkDatabase('my-project/my-database', { anonymous: true });
Properties
| Property | Type | Description |
|---|
connected | boolean | Whether the client is currently connected to the server. |
state | ConnectionState | The current connection state. One of 'disconnected', 'connecting', 'connected', 'joined', 'authenticated', or 'reconnecting'. |
auth | AuthInfo | null | The current authentication info, or null if not signed in. |
reconnecting | boolean | Whether the client is currently attempting to reconnect. |
transportType | 'websocket' | 'webtransport' | null | The active transport protocol, or null if not connected. |
serverTimeOffset | number | Estimated offset in milliseconds between the client clock and the server clock. |
volatilePaths | string[] | List of paths configured for high-frequency volatile updates. |
AuthInfo
| Property | Type | Description |
|---|
uid | string | The authenticated user’s unique identifier. |
provider | string | The authentication provider used. |
token | string | The current authentication token. |
Methods
connect
Opens a connection to the Lark server using the options passed to the constructor. Resolves when the connection is fully established and authenticated.
const db = new LarkDatabase('my-project/my-database', { anonymous: true });
await db.connect(); // optional, operations queue automatically
disconnect
disconnect(): Promise<void>
Closes the connection to the server. Resolves when the connection is fully closed.
ref
ref(path?: string): DatabaseReference
Returns a DatabaseReference pointing to the specified path in the database. If no path is provided, returns a reference to the root.
| Parameter | Type | Description |
|---|
path | string | Optional path relative to the database root. |
const usersRef = db.ref('users');
const rootRef = db.ref();
const nestedRef = db.ref('users/alice/profile');
signIn
signIn(token: string): Promise<void>
Authenticates the client with the given token. Resolves when authentication succeeds.
| Parameter | Type | Description |
|---|
token | string | An authentication token. |
await db.signIn('eyJhbGciOi...');
signOut
Signs out the current user and reverts to unauthenticated access.
transaction
transaction(ops: TransactionOperation[]): Promise<TransactionResult>
Executes a batch of operations atomically. All operations succeed or all fail together.
| Parameter | Type | Description |
|---|
ops | TransactionOperation[] | An array of operations to execute atomically. |
const result = await db.transaction([
{ type: 'set', path: 'counters/a', value: 1 },
{ type: 'set', path: 'counters/b', value: 2 },
]);
goOffline
Manually disconnects the client and disables automatic reconnection. Pending writes are preserved.
goOnline
Re-enables the connection after a goOffline() call. The client will attempt to reconnect and flush any pending writes.
hasPendingWrites
hasPendingWrites(): boolean
Returns true if there are writes that have not yet been acknowledged by the server.
if (db.hasPendingWrites()) {
console.log('Waiting for writes to sync...');
}
getPendingWriteCount
getPendingWriteCount(): number
Returns the number of write operations that have not yet been acknowledged by the server.
console.log(`${db.getPendingWriteCount()} writes pending`);
clearPendingWrites
clearPendingWrites(): void
Discards all pending writes that have not been sent to the server. Use with caution, because discarded writes cannot be recovered.
This permanently drops any unsent writes. Only use this if you intentionally want to discard local changes.
Event Methods
All event methods return an unsubscribe function. Call it to stop listening.
onConnect
onConnect(callback: () => void): () => void
Registers a listener that fires when the client establishes a connection.
const unsubscribe = db.onConnect(() => {
console.log('Connected to Lark');
});
// Later, stop listening
unsubscribe();
onDisconnect
onDisconnect(callback: () => void): () => void
Registers a listener that fires when the client loses its connection.
const unsubscribe = db.onDisconnect(() => {
console.log('Disconnected from Lark');
});
onReconnecting
onReconnecting(callback: () => void): () => void
Registers a listener that fires when the client begins a reconnection attempt.
const unsubscribe = db.onReconnecting(() => {
console.log('Attempting to reconnect...');
});
onError
onError(callback: (error: LarkError) => void): () => void
Registers a listener that fires when a connection-level error occurs.
const unsubscribe = db.onError((error) => {
console.error(`Lark error [${error.code}]: ${error.message}`);
});
onAuthStateChanged
onAuthStateChanged(callback: (auth: AuthInfo | null) => void): () => void
Registers a listener that fires when the authentication state changes: on sign-in, sign-out, or token refresh.
const unsubscribe = db.onAuthStateChanged((auth) => {
if (auth) {
console.log(`Signed in as ${auth.uid}`);
} else {
console.log('Signed out');
}
});