SDK Reference
Complete reference for the DeltaBase TypeScript SDK
SDK Reference
Section titled “SDK Reference”Complete reference for @delta-base/server
- the TypeScript SDK for Node.js applications.
Installation
Section titled “Installation”npm install @delta-base/server
Main Classes
Section titled “Main Classes”DeltaBase
Section titled “DeltaBase”Main entry point for the SDK.
import { DeltaBase } from '@delta-base/server';
const deltabase = new DeltaBase({ apiKey: 'your-api-key', baseUrl?: 'https://api.delta-base.com' // Optional});
Methods:
getEventStore(eventStoreId)
Section titled “getEventStore(eventStoreId)”Get an EventStore client for stream operations.
const eventStore = deltabase.getEventStore('my-event-store');
getEventBus(eventStoreId)
Section titled “getEventBus(eventStoreId)”Get an EventBus client for subscription management.
const eventBus = deltabase.getEventBus('my-event-store');
getManagement()
Section titled “getManagement()”Get a ManagementClient for administrative operations.
const management = deltabase.getManagement();
EventStore
Section titled “EventStore”Core client for event stream operations.
Stream Operations
Section titled “Stream Operations”appendToStream<T>(streamId, events, options?)
Section titled “appendToStream<T>(streamId, events, options?)”Append events to a stream with optional optimistic concurrency control.
interface AppendOptions { expectedStreamVersion?: number; idempotencyKey?: string;}
const result = await eventStore.appendToStream('user-123', [ { type: 'user.created', data: { id: 'user-123', email: 'john@example.com' }, metadata?: { userId: 'admin' } }], { expectedStreamVersion: 5 // Optional: fail if stream has moved past version 5});
// Result typeinterface AppendResult { streamId: string; eventsAppended: number; currentStreamVersion: number; globalPosition: number;}
readStream<T>(streamId, options?)
Section titled “readStream<T>(streamId, options?)”Read events from a stream.
interface ReadStreamOptions { direction?: 'forward' | 'backward'; fromStreamPosition?: number; toStreamPosition?: number; limit?: number; // Max 1000}
const events = await eventStore.readStream<UserEvent>('user-123', { direction: 'forward', limit: 100});
// Returns array of ReadEvent<T>interface ReadEvent<T> { streamId: string; streamPosition: number; globalPosition: number; eventId: string; type: string; data: T; metadata?: any; schemaVersion: string; transactionId: string; createdAt: string;}
aggregateStream<State_Event>(streamId, options)
Section titled “aggregateStream<State_Event>(streamId, options)”Build state by applying events to an aggregate.
interface AggregateOptions<State, Event> { initialState: () => State; evolve: (state: State, event: ReadEvent<Event>) => State; fromStreamPosition?: number; toStreamPosition?: number;}
const result = await eventStore.aggregateStream<User, UserEvent>('user-123', { initialState: () => ({ id: '', email: '', name: '', active: false }), evolve: (user, event) => { switch (event.type) { case 'user.created': return { ...user, ...event.data, active: true }; case 'user.deactivated': return { ...user, active: false }; default: return user; } }});
// Result typeinterface AggregateResult<State> { state: State; version: number; lastEventPosition: number;}
Query Operations
Section titled “Query Operations”queryEvents<T>(options?)
Section titled “queryEvents<T>(options?)”Query events across all streams with filtering.
interface QueryEventsOptions { types?: string[]; // Filter by event types streams?: string[]; // Filter by stream IDs after?: string; // ISO timestamp before?: string; // ISO timestamp fromGlobalPosition?: number; limit?: number; offset?: number; direction?: 'forward' | 'backward';}
const events = await eventStore.queryEvents<UserEvent>({ types: ['user.created', 'user.updated'], after: '2024-01-01T00:00:00Z', limit: 50});
// Returns QueryResult<ReadEvent<T>>interface QueryResult<T> { data: T[]; total?: number; hasMore: boolean; nextOffset?: number;}
queryStreams(options?)
Section titled “queryStreams(options?)”Query stream information.
interface QueryStreamsOptions { streamType?: string; // Filter by stream type prefix hasEvents?: boolean; // Only streams with events limit?: number; offset?: number;}
const streams = await eventStore.queryStreams({ streamType: 'user', limit: 100});
// Returns QueryResult<StreamInfo>interface StreamInfo { streamId: string; streamType: string; eventCount: number; firstEventPosition: number; lastEventPosition: number; createdAt: string; updatedAt: string;}
listStreams(options?)
Section titled “listStreams(options?)”Get a simple list of stream IDs.
const streamIds = await eventStore.listStreams({ limit: 1000});// Returns string[]
EventBus
Section titled “EventBus”Client for managing event subscriptions.
Core Methods
Section titled “Core Methods”subscribe(options)
Section titled “subscribe(options)”Create a comprehensive subscription.
interface SubscribeOptions { eventFilter: string; // Pattern like 'user.*', '*.created', etc. subscriberType: SubscriberType; subscriberConfig: SubscriberConfig; retryPolicy?: RetryPolicy; position?: 'latest' | 'earliest';}
enum SubscriberType { Webhook = 'webhook', WebSocket = 'websocket'}
interface WebhookConfig { url: string; headers?: Record<string, string>; timeout?: number;}
interface RetryPolicy { maxRetries?: number; // Default: 3 initialBackoffMs?: number; // Default: 1000 backoffMultiplier?: number; // Default: 2}
const subscription = await eventBus.subscribe({ eventFilter: 'user.*', subscriberType: SubscriberType.Webhook, subscriberConfig: { url: 'https://myapp.com/webhooks/deltabase', headers: { 'Authorization': 'Bearer secret' } }, retryPolicy: { maxRetries: 5, backoffMultiplier: 2 }});
subscribeWebhook(eventFilter, url, options?)
Section titled “subscribeWebhook(eventFilter, url, options?)”Convenient method for webhook subscriptions.
interface WebhookSubscribeOptions { headers?: Record<string, string>; retryPolicy?: RetryPolicy; position?: 'latest' | 'earliest';}
const subscription = await eventBus.subscribeWebhook( 'user.*', 'https://myapp.com/webhooks/deltabase', { headers: { 'X-API-Key': 'secret' }, retryPolicy: { maxRetries: 5 } });
getSubscription(subscriptionId)
Section titled “getSubscription(subscriptionId)”Get subscription details.
const subscription = await eventBus.getSubscription('sub_abc123');
interface Subscription { id: string; eventFilter: string; subscriberType: string; subscriberConfig: any; status: 'active' | 'paused' | 'failed'; retryPolicy?: RetryPolicy; position: string; createdAt: string; lastDeliveryAttempt?: string; failedDeliveries: number; totalDeliveries: number;}
listSubscriptions(options?)
Section titled “listSubscriptions(options?)”List all subscriptions.
interface ListSubscriptionsOptions { status?: 'active' | 'paused' | 'failed'; limit?: number; offset?: number;}
const result = await eventBus.listSubscriptions({ status: 'active', limit: 50});// Returns QueryResult<Subscription>
unsubscribe(subscriptionId)
Section titled “unsubscribe(subscriptionId)”Delete a subscription.
await eventBus.unsubscribe('sub_abc123');
ManagementClient
Section titled “ManagementClient”Administrative operations for event stores.
Event Store Management
Section titled “Event Store Management”createEventStore(options)
Section titled “createEventStore(options)”Create a new event store.
interface CreateEventStoreOptions { name: string; description?: string; region?: string; settings?: EventStoreSettings;}
interface EventStoreSettings { retentionPeriodDays?: number; // Default: 365 maxStreamSizeBytes?: number; // Default: 100MB}
const eventStore = await management.createEventStore({ name: 'my-new-store', description: 'Event store for my application', settings: { retentionPeriodDays: 730, // 2 years maxStreamSizeBytes: 209715200 // 200MB }});
listEventStores(options?)
Section titled “listEventStores(options?)”List accessible event stores.
interface ListEventStoresOptions { filter?: string; // Filter by name limit?: number; offset?: number;}
const stores = await management.listEventStores({ filter: 'my-app', limit: 20});// Returns QueryResult<EventStore>
getEventStore(eventStoreId)
Section titled “getEventStore(eventStoreId)”Get detailed event store information.
const store = await management.getEventStore('es_abc123');
interface EventStore { id: string; name: string; description?: string; region?: string; status: 'active' | 'suspended' | 'deleted'; createdAt: string; updatedAt: string; statistics?: { totalStreams: number; totalEvents: number; databaseSizeBytes: number; oldestEventTimestamp?: string; newestEventTimestamp?: string; }; settings?: EventStoreSettings;}
updateEventStore(eventStoreId, settings)
Section titled “updateEventStore(eventStoreId, settings)”Update event store settings.
await management.updateEventStore('es_abc123', { retentionPeriodDays: 1095 // 3 years});
deleteEventStore(eventStoreId)
Section titled “deleteEventStore(eventStoreId)”Delete an event store (irreversible).
await management.deleteEventStore('es_abc123');
Error Handling
Section titled “Error Handling”All methods can throw DeltaBaseError
with structured information:
import { DeltaBaseError } from '@delta-base/server';
try { await eventStore.appendToStream('stream-1', events, { expectedStreamVersion: 5 });} catch (error) { if (error instanceof DeltaBaseError) { console.log('Status:', error.status); // HTTP status code console.log('Code:', error.code); // Error code console.log('Message:', error.message); // Human readable message console.log('Details:', error.details); // Additional context
if (error.status === 409) { // Handle version conflict console.log('Stream was modified by someone else'); } }}
Common Error Codes:
UNAUTHORIZED
(401): Invalid API keyFORBIDDEN
(403): Insufficient permissionsNOT_FOUND
(404): Resource doesn’t existVERSION_CONFLICT
(409): Stream version mismatchRATE_LIMITED
(429): Rate limit exceededINTERNAL_ERROR
(500): Server error
Type Definitions
Section titled “Type Definitions”Event Types
Section titled “Event Types”// Input event for appendinginterface Event<Type = string, Data = any, Metadata = any> { type: Type; data: Data; metadata?: Metadata;}
// Output event from readinginterface ReadEvent<Data = any> { streamId: string; streamPosition: number; globalPosition: number; eventId: string; type: string; data: Data; metadata?: any; schemaVersion: string; transactionId: string; createdAt: string;}
Common Patterns
Section titled “Common Patterns”// Strongly typed eventsinterface UserCreated { type: 'user.created'; data: { id: string; email: string; name: string; };}
interface UserUpdated { type: 'user.updated'; data: { id: string; email?: string; name?: string; };}
type UserEvent = UserCreated | UserUpdated;
// Usageawait eventStore.appendToStream<UserEvent>('user-123', [{ type: 'user.created', data: { id: 'user-123', email: 'john@example.com', name: 'John' }}]);
const events = await eventStore.readStream<UserEvent>('user-123');
This SDK provides a complete, type-safe interface for building event-sourced applications with DeltaBase.