UNPKG

delta-sync

Version:

A lightweight framework for bi-directional database synchronization with automatic version tracking and conflict resolution.

78 lines (77 loc) 2.79 kB
export class MemoryAdapter { constructor() { this.stores = new Map(); } // validate store name is avaliable validateStoreName(storeName) { if (!storeName || typeof storeName !== 'string') { throw new Error('**Invalid store name**: Store name must be a non-empty string'); } } // validate items is avaliable validateItems(items) { for (const item of items) { if (!item || typeof item !== 'object') { throw new Error('**Invalid item**: Item must be an object'); } if (!item.id || typeof item.id !== 'string') { throw new Error('**Invalid item**: Item must have a string id property'); } } } // read data from memory store with pagination async readStore(storeName, limit = 100, offset = 0) { this.validateStoreName(storeName); const store = this.stores.get(storeName) || new Map(); const allItems = Array.from(store.values()).sort((a, b) => a.id.localeCompare(b.id)); const items = allItems.slice(offset, offset + limit); const hasMore = allItems.length > offset + limit; return { items, hasMore }; } // read data from memory store with ids async readBulk(storeName, ids) { this.validateStoreName(storeName); if (!Array.isArray(ids)) { throw new Error('**Invalid ids**: Must provide an array of ids'); } const store = this.stores.get(storeName) || new Map(); return ids.map(id => store.get(id)).filter(item => item !== undefined); } // write data to memory store async putBulk(storeName, items) { this.validateStoreName(storeName); this.validateItems(items); if (!this.stores.has(storeName)) { this.stores.set(storeName, new Map()); } const store = this.stores.get(storeName); for (const item of items) { store.set(item.id, item); } return items; } // delete data from memory store async deleteBulk(storeName, ids) { this.validateStoreName(storeName); if (!Array.isArray(ids)) { throw new Error('**Invalid ids**: Must provide an array of ids'); } const store = this.stores.get(storeName); if (store) { ids.forEach(id => store.delete(id)); } } // clear data from memory store async clearStore(storeName) { this.validateStoreName(storeName); if (this.stores.has(storeName)) { this.stores.get(storeName).clear(); return true; } return false; } // get all stores in memory async getStores() { return Array.from(this.stores.keys()); } }