Skip to main content
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.
ParameterTypeDescription
projectAndDatabasestringA combined identifier in the format 'projectId/databaseId'.
optionsLarkDatabaseOptionsOptional configuration object.
import { LarkDatabase } from '@lark-sh/client';

const db = new LarkDatabase('my-project/my-database');

Properties

PropertyTypeDescription
connectedbooleanWhether the client is currently connected to the server.
stateConnectionStateThe current connection state. One of 'disconnected', 'connecting', 'connected', 'joined', 'authenticated', or 'reconnecting'.
authAuthInfo | nullThe current authentication info, or null if not signed in.
reconnectingbooleanWhether the client is currently attempting to reconnect.
transportType'websocket' | 'webtransport' | nullThe active transport protocol, or null if not connected.
serverTimeOffsetnumberEstimated offset in milliseconds between the client clock and the server clock.
volatilePathsstring[]List of paths configured for high-frequency volatile updates.

AuthInfo

PropertyTypeDescription
uidstringThe authenticated user’s unique identifier.
providerstringThe authentication provider used.
tokenstringThe current authentication token.

Methods

connect

connect(options?: ConnectOptions): Promise<void>
Opens a connection to the Lark server. Resolves when the connection is established.
const db = new LarkDatabase('my-project/my-database');
await db.connect();

disconnect

disconnect(): Promise<void>
Closes the connection to the server. Resolves when the connection is fully closed.
await db.disconnect();

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.
ParameterTypeDescription
pathstringOptional 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.
ParameterTypeDescription
tokenstringAn authentication token.
await db.signIn('eyJhbGciOi...');

signOut

signOut(): Promise<void>
Signs out the current user and reverts to unauthenticated access.
await db.signOut();

transaction

transaction(ops: TransactionOperation[]): Promise<TransactionResult>
Executes a batch of operations atomically. All operations succeed or all fail together.
ParameterTypeDescription
opsTransactionOperation[]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

goOffline(): void
Manually disconnects the client and disables automatic reconnection. Pending writes are preserved.
db.goOffline();

goOnline

goOnline(): void
Re-enables the connection after a goOffline() call. The client will attempt to reconnect and flush any pending writes.
db.goOnline();

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 — discarded writes cannot be recovered.
This permanently drops any unsent writes. Only use this if you intentionally want to discard local changes.
db.clearPendingWrites();

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');
  }
});