levelcache/ts/levelcache.classes.cache.diskmanager.ts

72 lines
2.3 KiB
TypeScript
Raw Permalink Normal View History

2022-03-22 21:45:12 +00:00
import * as plugins from './levelcache.plugins.js';
import * as paths from './levelcache.paths.js';
import { AbstractCache } from './levelcache.abstract.classes.cache.js';
2023-07-20 20:54:07 +00:00
import { type ILevelCacheConstructorOptions, LevelCache } from './levelcache.classes.levelcache.js';
2022-03-22 21:45:12 +00:00
import { CacheEntry } from './levelcache.classes.cacheentry.js';
2020-02-14 17:28:13 +00:00
/**
2020-02-15 22:38:28 +00:00
*
2020-02-14 17:28:13 +00:00
*/
2021-04-23 18:40:57 +00:00
export class CacheDiskManager extends AbstractCache {
private levelCacheRef: LevelCache;
private readyDeferred = plugins.smartpromise.defer<void>();
2021-04-23 18:41:30 +00:00
2021-04-23 18:40:57 +00:00
public ready = this.readyDeferred.promise;
2021-04-23 18:41:30 +00:00
public status: 'active' | 'inactive';
2021-04-23 18:40:57 +00:00
public fsPath: string;
public maxCacheSizeInMb: number;
constructor(levelCacheRefArg: LevelCache) {
super();
this.levelCacheRef = levelCacheRefArg;
this.init();
}
public async init() {
if (this.levelCacheRef.options.diskStoragePath) {
2021-04-23 18:41:30 +00:00
this.fsPath = plugins.path.join(
this.levelCacheRef.options.diskStoragePath,
this.levelCacheRef.options.cacheId
);
2021-04-23 18:40:57 +00:00
} else {
this.fsPath = plugins.path.join(paths.nogitDir, this.levelCacheRef.options.cacheId);
}
if (this.status === 'active') {
plugins.smartfile.fs.ensureDirSync(this.fsPath);
}
this.readyDeferred.resolve();
}
public async retrieveCacheEntryByKey(keyArg: string): Promise<CacheEntry> {
2021-04-23 18:41:30 +00:00
const fileString = await plugins.smartfile.fs.toStringSync(
plugins.path.join(this.fsPath, encodeURIComponent(keyArg))
);
2021-04-23 18:40:57 +00:00
return CacheEntry.fromStorageJsonString(fileString);
}
public async storeCacheEntryByKey(keyArg: string, cacheEntryArg: CacheEntry) {
2021-04-23 18:41:30 +00:00
await plugins.smartfile.memory.toFs(
cacheEntryArg.foldToJson(),
plugins.path.join(this.fsPath, encodeURIComponent(keyArg))
);
2021-04-23 18:40:57 +00:00
}
public async checkKeyPresence(keyArg: string): Promise<boolean> {
2021-04-23 18:40:57 +00:00
return plugins.smartfile.fs.isFile(plugins.path.join(this.fsPath, encodeURIComponent(keyArg)));
}
public async deleteCacheEntryByKey(keyArg: string) {
await plugins.smartfile.fs.remove(plugins.path.join(this.fsPath, encodeURIComponent(keyArg)));
}
public async cleanOutdated() {}
public async cleanAll() {
2021-04-23 18:40:57 +00:00
if (this.status === 'active') {
if (plugins.smartfile.fs.isDirectory(this.fsPath)) {
await plugins.smartfile.fs.ensureEmptyDir(this.fsPath);
}
}
}
}