import { createServiceLogger } from '../../utils/logger'; import { openDB } from '../../orbit/orbitDBService'; import { getConnection } from '../core/connection'; import * as cache from '../cache/cacheService'; import * as events from '../events/eventService'; import { validateDocument } from '../schema/validator'; import { measurePerformance } from '../metrics/metricsService'; import { ErrorCode, StoreType, StoreOptions, CreateResult, UpdateResult, PaginatedResult, QueryOptions, ListOptions } from '../types'; import { DBError } from '../core/error'; const logger = createServiceLogger('DB_STORE'); /** * Base Store interface that all store implementations should extend */ export interface BaseStore { /** * Create a new document */ create>( collection: string, id: string, data: Omit, options?: StoreOptions ): Promise; /** * Get a document by ID */ get>( collection: string, id: string, options?: StoreOptions & { skipCache?: boolean } ): Promise; /** * Update a document */ update>( collection: string, id: string, data: Partial>, options?: StoreOptions & { upsert?: boolean } ): Promise; /** * Delete a document */ remove( collection: string, id: string, options?: StoreOptions ): Promise; /** * List all documents in a collection with pagination */ list>( collection: string, options?: ListOptions ): Promise>; /** * Query documents in a collection with filtering and pagination */ query>( collection: string, filter: (doc: T) => boolean, options?: QueryOptions ): Promise>; /** * Create an index for a collection to speed up queries */ createIndex( collection: string, field: string, options?: StoreOptions ): Promise; } /** * Open a store of the specified type */ export async function openStore( collection: string, storeType: StoreType, options?: StoreOptions ): Promise { try { const connection = getConnection(options?.connectionId); return await openDB(collection, storeType); } catch (error) { logger.error(`Error opening ${storeType} store for collection ${collection}:`, error); throw new DBError(ErrorCode.OPERATION_FAILED, `Failed to open ${storeType} store for collection ${collection}`, error); } } /** * Helper function to prepare a document for storage */ export function prepareDocument>( collection: string, data: Omit, existingDoc?: T | null ): T { const timestamp = Date.now(); // If it's an update to an existing document if (existingDoc) { const doc = { ...existingDoc, ...data, updatedAt: timestamp } as T; // Validate the document against its schema validateDocument(collection, doc); return doc; } // Otherwise it's a new document const doc = { ...data, createdAt: timestamp, updatedAt: timestamp } as unknown as T; // Validate the document against its schema validateDocument(collection, doc); return doc; }