2022-06-26 18:36:22 +00:00
|
|
|
import * as plugins from './smartcache.plugins.js';
|
|
|
|
import { CacheManager } from './smartcache.classes.cachemanager.js';
|
2018-07-12 19:32:20 +00:00
|
|
|
|
|
|
|
export class SmartCache {
|
|
|
|
private _cacheManager = new CacheManager();
|
|
|
|
|
|
|
|
async cacheReturn(asyncCachedFuncArg: () => Promise<any>, cacheDuration: number = 5000) {
|
2021-04-21 19:52:53 +00:00
|
|
|
const callStack: string = new plugins.smarterror.SmartError(
|
|
|
|
'Cache Creation Point'
|
|
|
|
).cleanFullStack.split('\n')[2];
|
2020-02-03 20:08:57 +00:00
|
|
|
const callHash = plugins.smarthash.sha256FromStringSync(callStack);
|
2018-07-12 21:52:06 +00:00
|
|
|
|
2018-08-21 22:35:03 +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);
|
2020-02-03 20:08:57 +00:00
|
|
|
const newCachedObject = await asyncCachedFuncArg();
|
2018-07-12 19:32:20 +00:00
|
|
|
this._cacheManager.setCache(callHash, newCachedObject, cacheDuration);
|
|
|
|
return newCachedObject;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|