Skip to content

API Reference

Complete reference for all StateDB classes, methods, and types.

StateDB

Constructor

ts
new StateDB(name?: string, options?: StateDBOptions)
ParameterTypeDefaultDescription
namestring'statedb'Database name (used as storage key prefix)
options.persistentbooleanfalseEnable auto-save/load
options.storage'local' | 'session''local'Storage backend
options.debouncenumber100Debounce interval in ms

Methods

MethodSignatureReturnsDescription
createCollection(name: string, options?: CollectionOptions)CollectionCreate or retrieve a collection
getCollection(name: string)Collection | nullGet an existing collection
listCollections()string[]List all collection names
dropCollection(name: string)booleanDrop a collection
drop()booleanDrop all collections and flush storage
save()booleanImmediately save to storage
load()booleanLoad from storage
flush()booleanRemove saved data from storage
export()ExportDataExport all data (without __inc)
dump()DumpDataFull snapshot (with __inc + counter)
import(data: ImportData)booleanImport clean data (re-inserts)
restore(dump: DumpData)booleanRestore a full dump

CollectionOptions

ts
interface CollectionOptions {
  schema?: SchemaDefinition;
  capped?: boolean;
  max?: number;
}

Collection

CRUD Methods

MethodSignatureReturnsDescription
insertOne(doc: object)Document | nullInsert a document
insertMany(docs: object[])Document[]Insert multiple documents
find(query?: QueryFilter, projection?: ProjectionSpec)QueryResultFind documents
findOne(query?: QueryFilter)Document | nullFind first matching document
count(query?: QueryFilter)numberCount matching documents
exists(query?: QueryFilter)booleanCheck if any document matches
first()Document | nullFirst document by insertion order
last()Document | nullLast document by insertion order
updateOne(query: QueryFilter, update: UpdateSpec)UpdateResultUpdate first match
updateMany(query: QueryFilter, update: UpdateSpec)UpdateResultUpdate all matches
replaceOne(query: QueryFilter, replacement: object)UpdateResultReplace first match entirely
upsertOne(query: QueryFilter, doc: object)UpdateResultUpdate or insert
deleteOne(query: QueryFilter)DeleteResultDelete first match
deleteMany(query: QueryFilter)DeleteResultDelete all matches
drop()DeleteResultRemove all documents, reset counter

Index Methods

MethodSignatureReturnsDescription
createIndex(fields: string | string[] | Record<string, number>, options?: IndexOptions)stringCreate an index, returns index name
dropIndex(name: string)booleanRemove an index
getIndexes()string[]List all index names

Watcher Methods

MethodSignatureReturnsDescription
watch(callback: WatcherCallback, options?: WatcherOptions)numberRegister a watcher, returns ID
unwatch(id?: number)voidRemove one or all watchers

Hook Methods

MethodSignatureReturnsDescription
pre(operation: HookOperation, callback: PreHookCallback)thisRegister a pre-hook
post(operation: HookOperation, callback: PostHookCallback)thisRegister a post-hook
removePre(operation: HookOperation, callback?: PreHookCallback)thisRemove pre-hook(s)
removePost(operation: HookOperation, callback?: PostHookCallback)thisRemove post-hook(s)

QueryResult

Returned by collection.find(). Supports chainable modifiers and terminal methods.

Chainable Methods

MethodSignatureReturnsDescription
sort(spec: SortSpec)thisSort results (1 ascending, -1 descending)
skip(n: number)thisSkip the first n results
limit(n: number)thisLimit to n results
project(spec: ProjectionSpec)thisInclude/exclude fields

Terminal Methods

MethodSignatureReturnsDescription
toArray()Document[]Execute and return array
count()numberCount of results
first()Document | nullFirst result
last()Document | nullLast result
forEach(callback: (doc, i, arr) => void)thisIterate results
map(callback: (doc, i, arr) => T)T[]Map results to new array
filter(callback: (doc, i, arr) => boolean)Document[]Filter results
explain()ExplainResultQuery execution plan

Projection

Include specific fields (inclusion mode):

js
users.find({}, { name: 1, age: 1 }).toArray();
// [{ name: 'Omar', age: 30, __inc: 1 }]

Exclude specific fields (exclusion mode):

js
users.find({}, { password: 0 }).toArray();
// All fields except password

__inc is always included in inclusion mode.

Sort

js
users.find().sort({ age: 1 }).toArray();    // ascending
users.find().sort({ age: -1 }).toArray();   // descending

// Multi-field sort
users.find().sort({ role: 1, age: -1 }).toArray();

Type Reference

ts
import type {
  // Core
  Document,
  StateDBOptions,
  CollectionOptions,

  // Query
  QueryFilter,
  QueryOperators,
  ProjectionSpec,
  SortSpec,

  // Update
  UpdateSpec,
  UpdateOperators,

  // Results
  UpdateResult,
  DeleteResult,
  ExplainResult,
  ExecutionStats,

  // Schema
  SchemaDefinition,
  SchemaFieldDefinition,
  SchemaType,
  SchemaOptions,

  // Index
  IndexOptions,

  // Watcher
  WatcherEvent,
  WatcherCallback,
  WatcherOptions,

  // Hooks
  HookOperation,
  PreHookCallback,
  PostHookCallback,

  // Export/Import
  CollectionDump,
  ExportData,
  DumpData,
  ImportData,
} from '@phpdot/statedb';

Key Types

ts
interface Document {
  __inc: number;
  [key: string]: unknown;
}

interface UpdateResult {
  matchedCount: number;
  modifiedCount: number;
  upsertedId?: number;
}

interface DeleteResult {
  deletedCount: number;
}

type WatcherEvent = 'insert' | 'update' | 'delete' | 'drop';
type HookOperation = 'insert' | 'update' | 'delete';

type WatcherCallback = (
  event: WatcherEvent,
  docs: Document[],
  prevDocs: Document[] | null,
) => void;

interface ExplainResult {
  queryPlanner: {
    winningPlan: {
      stage: string;
      inputStage?: {
        stage: string;
        indexName: string | null;
        indexFields: string[] | null;
      };
    };
  };
  executionStats: {
    nReturned: number;
    totalDocsExamined: number;
    totalKeysExamined: number;
    indexUsed: boolean;
    indexName: string | null;
    indexFields: string[] | null;
    executionTimeMs: number;
  };
}

MIT Licensed