import { HashedCacheManager } from "./hashed-cache-manager.js"; import { ERPObjType } from "../../types/erp-types.js"; import type { Knex } from "knex"; export type BatchResult = { duplicates: T[]; nonDuplicates: T[]; }; type BatchCacheManagerOptions = { ttl?: number; tableName?: string; /** Injectable Knex handle (tests); defaults to the SDK's local SQLite. */ db?: Knex; }; export class BatchCacheManager { private cacheManager: HashedCacheManager; constructor(options?: BatchCacheManagerOptions) { this.cacheManager = new HashedCacheManager({ ttl: options?.ttl, tableName: options?.tableName, db: options?.db, }); } /** * Checks a batch of objects against the cache and separates them into duplicates and non-duplicates * @param type The type of objects * @param objects Array of objects to check * @returns Object containing arrays of duplicate and non-duplicate objects */ async dedupeBatch( type: ERPObjType, objects: object[] ): Promise> { const result: BatchResult = { duplicates: [], nonDuplicates: [], }; // Check each object individually for (const object of objects) { const hasChanged = await this.cacheManager.hasChanged(type, object); if (hasChanged) { result.nonDuplicates.push(object); } else { result.duplicates.push(object); } } return result; } /** * Stores a batch of objects in the cache * @param type The type of objects * @param objects Array of objects to store */ async storeBatch( type: ERPObjType, objects: object[] ): Promise<{ totalInserted: number }> { // Store each object individually let totalInserted = 0; for (const object of objects) { const inserted = await this.cacheManager.store(type, object); if (inserted) { totalInserted++; } } return { totalInserted }; } /** * Removes objects from the cache * @param type The type of objects * @param objects Array of objects to remove */ async removeObjects(type: ERPObjType, objects: object[]): Promise { // Remove each object individually for (const object of objects) { await this.cacheManager.removeRecord(type, object); } } /** * Gets all records of a specific type */ async getRecordsByType(type: ERPObjType): Promise { return this.cacheManager.getRecordsByType(type); } /** * Removes all records of a specific type */ async removeRecordsByType(type: ERPObjType): Promise { return this.cacheManager.removeRecordsByType(type); } /** * Clears all records from the cache */ async clear(): Promise { return this.cacheManager.clear(); } /** * Cleans up resources */ async destroy(): Promise { return this.cacheManager.destroy(); } }