smartcache/ts/smartcache.classes.smartcache.ts

26 lines
959 B
TypeScript
Raw Normal View History

2018-07-12 19:32:20 +00:00
import * as plugins from './smartcache.plugins';
import { CacheManager } from './smartcache.classes.cachemanager';
export class SmartCache {
private _cacheManager = new CacheManager();
async cacheReturn(asyncCachedFuncArg: () => Promise<any>, cacheDuration: number = 5000) {
let callStack: string = new plugins.smarterror.SmartError('').cleanFullStack;
2018-09-07 23:11:25 +00:00
let callHash = plugins.smarthash.sha256FromStringSync(callStack);
2018-07-12 21:52:06 +00:00
// console.log(callHash);
2018-07-12 21:52:06 +00:00
if (
this._cacheManager.cacheExists(callHash) &&
(await this._cacheManager.waitForCacheReady(callHash)) &&
this._cacheManager.stillValid(callHash)
) {
2018-07-12 19:32:20 +00:00
return this._cacheManager.getCache(callHash).cachedObject;
} else {
this._cacheManager.announceCache(callHash, cacheDuration);
2018-07-12 21:52:06 +00:00
let newCachedObject = await asyncCachedFuncArg();
2018-07-12 19:32:20 +00:00
this._cacheManager.setCache(callHash, newCachedObject, cacheDuration);
return newCachedObject;
}
}
}