API reference/fetchium/stores/sync

fetchium/stores/sync

fetchium/stores/sync

Synchronous query store implementation for Fetchium. Provides in-memory and pluggable persistent storage with LRU cache eviction and reference-counted entity cleanup.

ts
import { SyncQueryStore, MemoryPersistentStore } from 'fetchium/stores/sync';
import type { SyncPersistentStore } from 'fetchium/stores/sync';

Classes

SyncQueryStore

Implements the QueryStore interface using a synchronous key-value backend. Manages an LRU queue per query class and automatically evicts the oldest entries when the queue exceeds maxCount. Entity data is reference-counted; entities are cascade-deleted when their reference count reaches zero.

Constructor

ts
new SyncQueryStore(kv: SyncPersistentStore)
ParameterTypeDescription
kvSyncPersistentStoreThe underlying synchronous key-value store.

Methods

MethodSignatureDescription
loadQuery(queryDef: QueryDefinition, queryKey: number): CachedQuery | undefinedLoads a cached query by key. Returns undefined if the cache entry has expired (beyond cacheTime) or does not exist. Also preloads referenced entities.
saveQuery(queryDef: QueryDefinition, queryKey: number, value: unknown, updatedAt: number, refIds?: Set<number>): voidPersists a query result, its timestamp, and entity reference IDs. Activates the query in the LRU queue.
saveEntity(entityKey: number, value: unknown, refIds?: Set<number>): voidPersists an entity's serialized data and its child entity references. Manages reference counts for nested entities.
mergeEntity(entityKey: number, fields: unknown, refIds?: Set<number>): voidWrites the fields streamed events supplied for an entity built from them: merged over the stored record when there is one (the record's references are then derived from the merged value), written as the record otherwise. A record that cannot be merged into is replaced.
activateQuery(queryDef: QueryDefinition, queryKey: number): voidMoves a query to the front of the LRU queue for its query class. If the queue is full, the oldest entry is evicted. A queue persisted with a different maxCount is resized: growing reallocates it, shrinking evicts the keys that no longer fit.
deleteQuery(queryKey: number): voidDeletes a query's stored value, reference IDs, and decrements reference counts for all referenced entities.
purgeStaleQueries(): voidScans all query classes and removes those whose lastUsedAt timestamp exceeds their cacheTime. Called automatically on QueryClient construction.
onDelete(listener: (key: number) => void): () => voidRegisters a listener called with the key of every record the store drops on its own (an LRU eviction, the reference-count cascade that follows it, a purge). Listeners are shared by every store over the same kv. Returns an unsubscribe function; QueryClient.destroy() calls it.
hasEntity(key: number): booleanWhether the store holds a record for the key. The client refreshes the record of an entity a streamed event updates while the entity is not in memory only when this answers true.

MemoryPersistentStore

In-memory implementation of SyncPersistentStore. Stores all data in a plain JavaScript object. Suitable for development, testing, and applications that do not need persistence across sessions.

Constructor

ts
new MemoryPersistentStore();

No parameters. Creates an empty store.

Methods

Implements all methods of SyncPersistentStore (see interface below).


Interfaces

SyncPersistentStore

The interface for synchronous key-value storage backends. Implement this to plug in custom storage (e.g., localStorage, synchronous SQLite, shared memory).

ts
interface SyncPersistentStore {
  has(key: string): boolean;

  getString(key: string): string | undefined;
  setString(key: string, value: string): void;

  getNumber(key: string): number | undefined;
  setNumber(key: string, value: number): void;

  getBuffer(key: string): Uint32Array | undefined;
  setBuffer(key: string, value: Uint32Array): void;

  delete(key: string): void;

  getAllKeys(): string[];
}
MethodSignatureDescription
has(key: string): booleanReturns true if the key exists in the store.
getString(key: string): string | undefinedRetrieves a string value by key.
setString(key: string, value: string): voidStores a string value.
getNumber(key: string): number | undefinedRetrieves a numeric value by key.
setNumber(key: string, value: number): voidStores a numeric value.
getBuffer(key: string): Uint32Array | undefinedRetrieves a Uint32Array buffer by key. Used for LRU queues and entity reference ID lists.
setBuffer(key: string, value: Uint32Array): voidStores a Uint32Array buffer.
delete(key: string): voidDeletes a key and its associated value.
getAllKeys(): string[]Returns all keys in the store. Used by purgeStaleQueries to scan for expired entries.

Storage key layout

Internally, SyncQueryStore uses the following key prefixes in the underlying SyncPersistentStore:

Prefix / PatternValue typeDescription
v:{id}stringJSON-serialized value for a query or entity.
u:{id}numberupdatedAt timestamp (ms since epoch) for a query.
r:{id}Uint32ArrayEntity reference IDs for a query or entity.
rc:{id}numberReference count for an entity.
q:{queryDefId}Uint32ArrayLRU queue buffer for a query class.
lu:{queryDefId}numberLast-used timestamp for a query class.
ct:{queryDefId}numberCache time (minutes) for a query class.

Example

ts
import { QueryClient } from 'fetchium';
import { SyncQueryStore, MemoryPersistentStore } from 'fetchium/stores/sync';
import { RESTQueryAdapter } from 'fetchium/rest';

// Create an in-memory store
const store = new SyncQueryStore(new MemoryPersistentStore());

// Create the query client
const client = new QueryClient({
  store,
  adapters: [
    new RESTQueryAdapter({
      fetch: globalThis.fetch,
      baseUrl: 'https://api.example.com',
    }),
  ],
});