import * as plugins from './levelcache.plugins'; import { LevelCache } from './levelcache.classes.levelcache'; import { AbstractCache } from './levelcache.abstract.classes.cache'; import { CacheEntry } from './levelcache.classes.cacheentry'; export class CacheRouter { public levelCacheRef: LevelCache; public cacheKeyMap = new plugins.lik.FastMap(); constructor(levelCacheRef: LevelCache) { this.levelCacheRef = levelCacheRef; } /** * gets the relevant cache to perform a store action on */ async getCacheForStoreAction(keyArg: string, cacheEntry: CacheEntry): Promise { let returnCache: AbstractCache; switch (true) { case cacheEntry.contents.byteLength <= 500: returnCache = this.levelCacheRef.cacheMemoryManager; break; case this.levelCacheRef.cacheDiskManager.status === 'active' && cacheEntry.contents.byteLength >= 500 && (cacheEntry.contents.byteLength < 10000 || this.levelCacheRef.cacheS3Manager.status === 'inactive'): returnCache = this.levelCacheRef.cacheDiskManager; break; case cacheEntry.contents.byteLength >= 10000 && this.levelCacheRef.cacheS3Manager.status === 'active': returnCache = this.levelCacheRef.cacheS3Manager; break; default: returnCache = this.levelCacheRef.cacheMemoryManager; } this.cacheKeyMap.addToMap(keyArg, returnCache); return returnCache; } /** * gets the relevant cache to perform a retrieval action on */ async getCacheForRetrieveAction(keyArg: string): Promise { const done = plugins.smartpromise.defer(); const returnCache = this.cacheKeyMap.getByKey(keyArg); if (!returnCache && this.levelCacheRef.options.persistentCache) { const checkCache = (cacheArg: AbstractCache) => { const resultPromise = cacheArg.checkKeyPresence(keyArg); resultPromise.then(hasKeyArg => { if (hasKeyArg) { done.resolve(cacheArg); } }); return resultPromise; }; Promise.all([ checkCache(this.levelCacheRef.cacheMemoryManager), checkCache(this.levelCacheRef.cacheDiskManager), checkCache(this.levelCacheRef.cacheMemoryManager) ]).then(() => { done.resolve(returnCache); }); } else { done.resolve(returnCache); } return done.promise; } }