import * as plugins from './levelcache.plugins.js'; import * as paths from './levelcache.paths.js'; import { AbstractCache } from './levelcache.abstract.classes.cache.js'; import { type ILevelCacheConstructorOptions, LevelCache, } from './levelcache.classes.levelcache.js'; import { CacheEntry } from './levelcache.classes.cacheentry.js'; /** * */ export class CacheDiskManager extends AbstractCache { private levelCacheRef: LevelCache; private readyDeferred = plugins.smartpromise.defer(); public ready = this.readyDeferred.promise; public status: 'active' | 'inactive'; public fsPath: string; public maxCacheSizeInMb: number; constructor(levelCacheRefArg: LevelCache) { super(); this.levelCacheRef = levelCacheRefArg; this.init(); } public async init() { if (this.levelCacheRef.options.diskStoragePath) { this.fsPath = plugins.path.join( this.levelCacheRef.options.diskStoragePath, this.levelCacheRef.options.cacheId, ); } else { this.fsPath = plugins.path.join( paths.nogitDir, this.levelCacheRef.options.cacheId, ); } if (this.status === 'active') { await plugins.fs.directory(this.fsPath).recursive().create(); } this.readyDeferred.resolve(); } public async retrieveCacheEntryByKey(keyArg: string): Promise { const fileString = (await plugins.fs .file(plugins.path.join(this.fsPath, encodeURIComponent(keyArg))) .encoding('utf8') .read()) as string; return CacheEntry.fromStorageJsonString(fileString); } public async storeCacheEntryByKey(keyArg: string, cacheEntryArg: CacheEntry) { await plugins.fs .file(plugins.path.join(this.fsPath, encodeURIComponent(keyArg))) .write(cacheEntryArg.foldToJson()); } public async checkKeyPresence(keyArg: string): Promise { return plugins.fs .file(plugins.path.join(this.fsPath, encodeURIComponent(keyArg))) .exists(); } public async deleteCacheEntryByKey(keyArg: string) { const cacheFile = plugins.fs.file( plugins.path.join(this.fsPath, encodeURIComponent(keyArg)), ); if (await cacheFile.exists()) { await cacheFile.delete(); } } public async cleanOutdated() {} public async cleanAll() { if (this.status === 'active') { const dir = plugins.fs.directory(this.fsPath); if (await dir.exists()) { await plugins.fs.directory(this.fsPath).recursive().delete(); await plugins.fs.directory(this.fsPath).recursive().create(); } } } }