API reference
The complete public surface of Ledger v2.4. Everything is exported from the
package root except framework bindings, which live in ledger/react,
ledger/vue, and ledger/svelte.
createLedger()
Creates a store from a map of collections. This is the entry point.
function createLedger<S extends Schema>(
collections: S,
options?: LedgerOptions
): Ledger<S>;
interface LedgerOptions {
persist?: Adapter; // storage adapter, default: in-memory
schemaVersion?: number; // current schema version, default: 1
migrations?: Record<number, MigrationFn>;
} | Option | Type | Description |
|---|---|---|
persist | Adapter | Storage backend. Omit for in-memory only. |
schemaVersion | number | Current schema version for migrations. |
migrations | Record<number, fn> | Upgrade steps keyed by target version. |
Returns a Ledger whose properties are the collections you passed, plus ready (a promise) and flush().
collection()
Declares a typed collection. The generic parameter is the record type.
function collection<T>(options?: {
key?: keyof T; // primary key field, default: 'id'
index?: (keyof T)[]; // fields to build secondary indexes on
}): Collection<T>; | Option | Type | Default |
|---|---|---|
key | keyof T | 'id' |
index | (keyof T)[] | [] |
Collection methods
| Method | Returns | Description |
|---|---|---|
insert(record) | T | Add a record. Throws if the key exists. |
upsert(record) | T | Insert or replace by key. |
update(key, patch) | T | Shallow-merge a partial into a record. |
unset(key, field) | T | Delete a single field from a record. |
remove(key) | boolean | Delete a record by key. |
get(key) | T | undefined | Read one record by key. |
all() | T[] | Snapshot of every record. |
where(fn) | Query<T> | Start a filtered query. |
onChange(fn) | () => void | Subscribe to a raw change feed. |
where()
Filters records by a predicate and returns a chainable query.
where(predicate: (record: T) => boolean): Query<T>;
// Example
db.users.where((u) => u.role === 'admin' && u.active); live()
Turns a query into a reactive subscription. The callback fires immediately and on every change to the result.
live(): LiveQuery<T>;
interface LiveQuery<T> {
subscribe(fn: (records: T[]) => void): () => void;
all(): T[];
}
// Example
const stop = db.users.where((u) => u.active).live().subscribe(render);
stop(); // unsubscribe subscribe returns its unsubscribe function. Call it to stop receiving updates and free the query.
React binding
The useQuery hook subscribes on mount and unsubscribes on unmount.
import { useQuery } from 'ledger/react';
function useQuery<T>(factory: () => LiveQuery<T>, deps?: unknown[]): T[];
// Example
const admins = useQuery(() => db.users.where((u) => u.role === 'admin').live());