smartcache/ts/smartcache.classes.cachemanager.ts

73 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-06-26 18:36:22 +00:00
import * as plugins from './smartcache.plugins.js';
2018-07-12 19:32:20 +00:00
import { SmartError } from '@pushrocks/smarterror';
export interface ICacheMap {
[key: string]: {
timer: plugins.smarttime.Timer;
cachedDeferred: plugins.smartpromise.Deferred<any>;
cachedObject: any;
};
}
export class CacheManager {
private _cacheMap: ICacheMap = {};
2022-06-26 18:36:22 +00:00
cacheExists(identifierArg: string): boolean {
2018-07-12 19:32:20 +00:00
if (this._cacheMap[identifierArg]) {
return true;
}
return false;
}
stillValid(identifierArg: string): boolean {
2018-07-12 21:52:06 +00:00
if (
this.cacheExists(identifierArg) &&
this._cacheMap[identifierArg].timer.startedAt.isYoungerThanMilliSeconds(
this._cacheMap[identifierArg].timer.timeInMilliseconds
)
) {
2018-07-12 19:32:20 +00:00
return true;
}
return false;
}
// announce the caching of something
announceCache(identifierArg: string, validForArg: number) {
this._cacheMap[identifierArg] = {
timer: new plugins.smarttime.Timer(validForArg),
cachedDeferred: new plugins.smartpromise.Deferred(),
2021-04-21 19:52:53 +00:00
cachedObject: null,
2018-07-12 19:32:20 +00:00
};
this._cacheMap[identifierArg].timer.start();
this._cacheMap[identifierArg].timer.completed.then(() => {
2018-07-12 21:52:06 +00:00
this.deleteCache(identifierArg);
2018-07-12 19:32:20 +00:00
});
}
/**
* waits for the cache to be ready
*/
2018-07-12 21:52:06 +00:00
async waitForCacheReady(identifierArg: string) {
await this._cacheMap[identifierArg].cachedDeferred.promise;
2018-07-12 19:32:20 +00:00
return true;
}
setCache(identifierArg: string, cachedObjectArg: any, validForArg = 1000) {
2018-07-12 21:52:06 +00:00
if (!this.cacheExists(identifierArg)) {
console.log(
new SmartError(`Cache for ${identifierArg} has not been announced or timed out!`)
);
2018-07-12 19:32:20 +00:00
}
this._cacheMap[identifierArg].cachedObject = cachedObjectArg;
this._cacheMap[identifierArg].cachedDeferred.resolve();
}
getCache(identifierArg: string) {
return this._cacheMap[identifierArg];
}
async deleteCache(identifierArg: string) {
delete this._cacheMap[identifierArg];
}
}