Skip to main content

Creating a Client

import { createClient } from '@ondb/sdk';

const client = createClient({
  endpoint: 'https://api.ondb.io',
  appId: 'your-app-id',
  appKey: 'your-app-key',      // For writes (X-App-Key header)
  agentKey: 'your-agent-key',  // Optional: For agent payments (X-Agent-Key header)
  timeout: 30000,              // Request timeout (ms)
  retryCount: 3,               // Retry attempts
  retryDelay: 1000,            // Retry delay (ms)
});

Core Operations

store

Store data with USDC payment.
const result = await client.store(
  { collection: 'users', data: [{ name: 'Alice' }] },
  async (quote) => {
    // quote contains: totalCost, brokerAddress, tokenSymbol, network, chainType
    const txHash = await processPayment(quote);
    return { txHash, network: quote.network, sender: walletAddress, chainType: quote.chainType, paymentMethod: 'native' };
  },
  true // waitForConfirmation
);

query

Query data with filters.
const result = await client.queryBuilder()
  .collection('users')
  .whereField('active').isTrue()
  .limit(10)
  .execute();

health

Health check.
const health = await client.health();
console.log('Status:', health.status);

CRUD Operations

Create

Store documents in a collection.
const result = await client.store(
  { collection: 'users', data: [{ name: 'Alice', email: 'alice@example.com' }] },
  paymentCallback
);

Read (Single)

Find the latest version of a single document.
const doc = await client.queryBuilder()
  .collection('users')
  .whereField('email').equals('alice@example.com')
  .executeUnique();

Read (Many)

Find multiple documents with filters.
const result = await client.queryBuilder()
  .collection('users')
  .whereField('active').isTrue()
  .orderBy('createdAt', 'DESC')
  .limit(10)
  .offset(0)
  .execute();
const docs = result.records;

Update

Find, modify, and re-store to append a new version.
const doc = await client.queryBuilder()
  .collection('users')
  .whereField('email').equals('alice@example.com')
  .executeUnique();
if (doc) {
  await client.store(
    { collection: 'users', data: [{ ...doc, name: 'Alice Smith' }] },
    paymentCallback
  );
}

Delete (Soft)

Find, set deleted flag, and re-store.
const doc = await client.queryBuilder()
  .collection('users')
  .whereField('email').equals('alice@example.com')
  .executeUnique();
if (doc) {
  await client.store(
    { collection: 'users', data: [{ ...doc, deleted: true, deletedAt: new Date().toISOString() }] },
    paymentCallback
  );
}

Count

Count matching documents.
const count = await client.queryBuilder()
  .collection('users')
  .whereField('active').isTrue()
  .count();

Query Builder

queryBuilder

Create fluent query builder.
const builder = client.queryBuilder();

const users = await builder
  .collection('users')
  .whereField('active').isTrue()
  .orderBy('createdAt', 'DESC')
  .limit(10)
  .execute();

Task Management

getTaskStatus

Get task status.
const status = await client.getTaskStatus(ticketId);
console.log('Status:', status.status);

waitForTaskCompletion

Wait for task.
const task = await client.waitForTaskCompletion(
  ticketId,
  2000,    // Poll every 2 seconds
  600000   // Max wait 10 minutes
);

SQL Interface

sql

Execute SQL queries against your collections.
const result = await client.sql(
  'SELECT * FROM my_app::users WHERE email = "alice@example.com"',
  { includeHistory: false }
);

console.log(result.data);    // Array of records
console.log(result.count);   // Total count

sqlInsert

Execute SQL INSERT statements.
await client.sqlInsert(
  'INSERT INTO my_app::users (email, name) VALUES ("alice@example.com", "Alice")'
);

Predefined Queries

createQuery

Create a named, parameterized query that can be executed via a public endpoint.
await client.createQuery({
  name: 'active_users',
  source_collection: 'users',
  base_query: {
    find: { status: { is: 'active' } },
    select: { email: true, name: true }
  },
  parameters: [
    { name: 'limit', field_path: 'limit', default: 10 },
    { name: 'country', field_path: 'country', required: true, description: 'Filter by country' }
  ],
  description: 'Get active users by country'
});

executeQuery

Execute a predefined query (public endpoint, no auth required).
const result = await client.executeQuery('active_users', { country: 'US' }, 1);
// result: { success, query_name, data, count, query_time_ms }

listQueries / getQuery / deleteQuery

const queries = await client.listQueries();
const query = await client.getQuery('active_users');
await client.deleteQuery('active_users');

Collection Management

createCollection

Create a collection with schema-based index configuration.
await client.createCollection({
  name: 'users',
  fields: {
    email: { type: 'string', index: true, unique: true },
    name: { type: 'string', index: true },
    age: { type: 'number', indexType: 'btree' },
    'address.city': { type: 'string', index: true }
  },
  useBaseFields: true // Auto-index id, createdAt, updatedAt, deletedAt
});

syncCollection

Sync a schema to the backend (creates new indexes, upsert behavior). Supports sharding configuration.
await client.syncCollection({
  name: 'orderbook_snapshots',
  fields: {
    market: { type: 'string', index: true },
    timestamp: { type: 'number', index: true },
    mid_price: { type: 'number' }
  },
  sharding: {
    keys: [
      { field: 'market', type: 'discrete' },
      { field: 'timestamp', type: 'time_range', granularity: 'hour' }
    ],
    enforce_in_queries: true,
    max_shard_size: 50_000_000
  }
});

setupSharding

Configure sharding on an existing collection.
await client.setupSharding('orderbook_snapshots', {
  keys: [
    { field: 'market', type: 'discrete' },
    { field: 'timestamp', type: 'time_range', granularity: 'hour' }
  ],
  enforce_in_queries: true
});

updateCollection

Update collection properties.
await client.updateCollection('users', {
  public: true,
  description: 'User profiles',
  default_sort_column: 'createdAt',
  collection_type: 'local' // 'local' | 'offline' | 'api' | 'hybrid'
});

deleteCollection / getCollectionInfo

const info = await client.getCollectionInfo('collection-id');
// info: { id, name, namespace, document_count, size_kb, created_at, ... }

await client.deleteCollection('users');

Data Retention

getRetention / setRetention

// Get retention config
const config = await client.getRetention('users');
// config: { collection, retention_days, monthly_cost_per_kb, status }

// Set retention (null = permanent)
await client.setRetention('logs', { retention_days: 30 });

// Get cost estimates for all collections
const costs = await client.getRetentionCost();
// costs: { collections: [...], total_monthly_cost }

Events (TypeScript Only)

The TypeScript SDK supports event-based transaction tracking:
client.on('transaction:queued', (ticket) => { ... });
client.on('transaction:pending', (tx) => { ... });
client.on('transaction:confirmed', (tx) => { ... });
client.on('transaction:failed', (tx) => { ... });
client.on('error', (error) => { ... });

Next Steps

Query Builder

Fluent query API reference

Database Manager

Collections, indexes, and views