zendb-client
v0.3.1
Published
TypeScript client library for ZenDB - Document Database for the Internet Computer
Downloads
679
Maintainers
Readme
ZenDB TypeScript Client
TypeScript client for ZenDB on the Internet Computer.
Install
npm install zendb-clientQuick Start
import { connectToZenDBClient, IDL, idlTypeToSchema } from 'zendb-client';
// Provide an ICP identity from your app/runtime.
const identity = yourIdentity;
const client = await connectToZenDBClient('your-canister-id', identity);
// Create database
await client.createDatabase('myapp');
// Define schema using Candid IDL helpers
const userSchema = idlTypeToSchema(
IDL.Record({
name: IDL.Text,
age: IDL.Nat,
active: IDL.Bool,
}),
);
// Create collection
const db = client.database('myapp');
const users = await db.createCollection('users', userSchema);
// Insert and query
await users.insertJson({ name: 'Alice', age: 30n, active: true });
const found = await users.search({ And: [] }, { limit: 10 });
console.log(found.documents.length);Chainable QueryBuilder
import { QueryBuilder, Q } from 'zendb-client';
const query = new QueryBuilder()
.Where('age', Q.gte({ Nat: 18n }))
.Where('active', Q.eq({ Bool: true }))
.Or(
new QueryBuilder().Where('name', Q.startsWith({ Text: 'Al' })),
new QueryBuilder().Where('name', Q.textPhrase('alice cooper')),
)
.SortBy('age', { Descending: null })
.Limit(25)
.Skip(0);
const result = await users.search(query);Range + anyOf + count
import { QueryBuilder, Q } from 'zendb-client';
const countQuery = new QueryBuilder()
.Where('status', Q.anyOf([{ Text: 'active' }, { Text: 'pending' }]))
.Where('age', Q.between({ Nat: 18n }, { Nat: 65n }));
const total = await users.count(countQuery);
console.log(total.count);Text search + update
import { QueryBuilder, Q } from 'zendb-client';
const textQuery = new QueryBuilder()
.Where('bio', Q.textAnyOf(['motoko', 'icp']))
.Where('bio', Q.textNot({ phrase: 'deprecated profile' }))
.Limit(50);
await users.update(textQuery, [
['active', { Set: { Bool: true } }],
]);Supported operators via Q:
- eq
- gt
- gte
- lt
- lte
- not
- anyOf
- between
- betweenLeftOpen
- betweenRightOpen
- betweenExclusive
- exists
- startsWith
- text
- textWord
- textPhrase
- textStartsWith
- textAnyOf
- textAllOf
- textNot
Core Exports
- connectToZenDBClient
- ZenDBClient
- Database
- Collection
- QueryBuilder
- idlTypeToSchema
- IDL
- Q
API Signatures
Top-level
connectToZenDBClient(canisterId: string, identity: Identity): Promise<ZenDBClient>: Connects to a ZenDB canister and waits for readiness.idlTypeToSchema(type: IDL.Type): Schema: Converts a Candid IDL type into ZenDB schema format.createQueryBuilder(initial?: ZenQueryLang | QueryBuilder): QueryBuilder: Creates a new chainable query builder.
QueryBuilder
new QueryBuilder(initial?: ZenQueryLang | QueryBuilder): Creates a new builder with optional initial query.Where(field: string, operator: QueryOperator): QueryBuilder: Adds a field operation clause.And(...queries: (ZenQueryLang | QueryBuilder)[]): QueryBuilder: Adds an AND group.Or(...queries: (ZenQueryLang | QueryBuilder)[]): QueryBuilder: Adds an OR group.Not(field: string, operator: QueryOperator): QueryBuilder: Adds a negated field operation.SortBy(field: string, direction: SortDirection): QueryBuilder: Sets sort field and direction.Limit(value: number | bigint): QueryBuilder: Sets query result limit.Skip(value: number | bigint): QueryBuilder: Sets query offset.PaginationToken(value: PaginationToken): QueryBuilder: Sets cursor token for pagination.build(): ZenQueryLang: Returns the logical query tree.buildStableQuery(): StableQuery: Returns the full query payload including pagination/sort.
ZenDBClient
apiVersion(): Promise<string>: Returns API version from the target canister.stats(): Promise<InstanceStats>: Returns global canister stats.createDatabase(databaseName: string): Promise<void>: Creates a database.deleteDatabase(databaseName: string): Promise<void>: Deletes a database.listDatabaseNames(): Promise<string[]>: Lists all database names.renameDatabase(oldName: string, newName: string): Promise<void>: Renames a database.listCollectionNames(databaseName: string): Promise<string[]>: Lists collections in a database.database(name: string): Database: Returns aDatabasehelper bound to a name.
Database
apiVersion(): Promise<string>: Returns API version through database-scoped actor.createDatabase(databaseName: string): Promise<void>: Creates a database.deleteDatabase(databaseName: string): Promise<void>: Deletes a database.createCollection<Record>(databaseName: string, collectionName: string, schema: Schema | IDL.Type, options?: any): Promise<Collection<Record>>: Creates a collection and returns a typed collection helper.deleteCollection(databaseName: string, collectionName: string): Promise<void>: Deletes a collection.stats(): Promise<DatabaseStats>: Returns stats for the bound database name.databaseStats(databaseName: string): Promise<DatabaseStats>: Returns stats for any database name.listCollectionNames(databaseName: string): Promise<string[]>: Lists collection names.getCollectionStats(databaseName: string, collectionName: string): Promise<CollectionStats | null>: Gets a single collection's stats.getAllCollectionsStats(databaseName: string): Promise<[string, CollectionStats][]>: Gets stats for all collections in a database.
Collection
schema(): Promise<Schema>: Gets collection schema.insert(document: CandidBlob): Promise<DocumentId>: Inserts a pre-encoded Candid document.insertJson(json: unknown): Promise<DocumentId>: Encodes JSON using schema and inserts one document.insertDocs(documents: CandidBlob[]): Promise<DocumentId[]>: Inserts multiple pre-encoded documents.insertManyJson(docs: object[]): Promise<DocumentId[]>: Encodes and inserts multiple JSON documents.get(documentId: DocumentId): Promise<Record | null>: Fetches and decodes one document.replace(documentId: DocumentId, document: Uint8Array | number[]): Promise<void>: Replaces one document blob by id.updateById(documentId: DocumentId, updates: [string, FieldUpdateOperations][]): Promise<void>: Applies field updates to one document by id.deleteById(documentId: DocumentId): Promise<DeleteByIdResult>: Deletes one document by id.search(query: ZenQueryLang | QueryBuilder, options?: QueryOptions): Promise<SearchResult<Record>>: Searches and decodes matching documents.searchForOne(query: ZenQueryLang | QueryBuilder, options?: QueryOptions): Promise<[string, Record] | null>: Returns one decoded match.count(query: ZenQueryLang | QueryBuilder, options?: QueryOptions): Promise<CountResult>: Counts matching documents.update(query: ZenQueryLang | QueryBuilder, updates: [string, FieldUpdateOperations][], options?: QueryOptions): Promise<UpdateResult>: Applies updates to matched documents.delete(query: ZenQueryLang | QueryBuilder, options?: QueryOptions): Promise<DeleteResult>: Deletes matched documents.size(): Promise<bigint>: Returns collection document count.createIndex(indexName: string, fields: [string, CreateIndexSortDirection][], options?: CreateIndexOptions): Promise<void>: Creates a structured index.deleteIndex(indexName: string): Promise<void>: Deletes an index.getIndexes(): Promise<[string, IndexStats][]>: Returns index metadata.createTextIndex(indexName: string, fields: string[]): Promise<void>: Creates a text index.deleteTextIndex(indexName: string): Promise<void>: Deletes a text index.hideIndexes(indexNames: string[]): Promise<void>: Hides indexes from query planner.unhideIndexes(indexNames: string[]): Promise<void>: Re-enables hidden indexes.listIndexNames(): Promise<string[]>: Lists index names.
License
MIT
