Chore: convert CachingProxy to TS

This commit is contained in:
Alexander Zobnin
2020-05-15 13:53:35 +03:00
parent 4a3bb91aaf
commit 6eba6f870c

View File

@@ -4,6 +4,10 @@
*/ */
export class CachingProxy { export class CachingProxy {
cacheEnabled: boolean;
ttl: number;
cache: any;
promises: any;
constructor(cacheOptions) { constructor(cacheOptions) {
this.cacheEnabled = cacheOptions.enabled; this.cacheEnabled = cacheOptions.enabled;
@@ -33,13 +37,13 @@ export class CachingProxy {
} }
proxyfyWithCache(func, funcName, funcScope) { proxyfyWithCache(func, funcName, funcScope) {
let proxyfied = this.proxyfy(func, funcName, funcScope); const proxyfied = this.proxyfy(func, funcName, funcScope);
return this.cacheRequest(proxyfied, funcName, funcScope); return this.cacheRequest(proxyfied, funcName, funcScope);
} }
_isExpired(cacheObject) { _isExpired(cacheObject) {
if (cacheObject) { if (cacheObject) {
let object_age = Date.now() - cacheObject.timestamp; const object_age = Date.now() - cacheObject.timestamp;
return !(cacheObject.timestamp && object_age < this.ttl); return !(cacheObject.timestamp && object_age < this.ttl);
} else { } else {
return true; return true;
@@ -52,8 +56,9 @@ export class CachingProxy {
* with same params when waiting for result. * with same params when waiting for result.
*/ */
function callOnce(func, promiseKeeper, funcScope) { function callOnce(func, promiseKeeper, funcScope) {
// tslint:disable-next-line: only-arrow-functions
return function() { return function() {
var hash = getRequestHash(arguments); const hash = getRequestHash(arguments);
if (!promiseKeeper[hash]) { if (!promiseKeeper[hash]) {
promiseKeeper[hash] = Promise.resolve( promiseKeeper[hash] = Promise.resolve(
func.apply(funcScope, arguments) func.apply(funcScope, arguments)
@@ -68,13 +73,14 @@ function callOnce(func, promiseKeeper, funcScope) {
} }
function cacheRequest(func, funcName, funcScope, self) { function cacheRequest(func, funcName, funcScope, self) {
// tslint:disable-next-line: only-arrow-functions
return function() { return function() {
if (!self.cache[funcName]) { if (!self.cache[funcName]) {
self.cache[funcName] = {}; self.cache[funcName] = {};
} }
let cacheObject = self.cache[funcName]; const cacheObject = self.cache[funcName];
let hash = getRequestHash(arguments); const hash = getRequestHash(arguments);
if (self.cacheEnabled && !self._isExpired(cacheObject[hash])) { if (self.cacheEnabled && !self._isExpired(cacheObject[hash])) {
return Promise.resolve(cacheObject[hash].value); return Promise.resolve(cacheObject[hash].value);
} else { } else {
@@ -96,7 +102,7 @@ function getRequestHash(args) {
} }
String.prototype.getHash = function() { String.prototype.getHash = function() {
var hash = 0, i, chr, len; let hash = 0, i, chr, len;
if (this.length !== 0) { if (this.length !== 0) {
for (i = 0, len = this.length; i < len; i++) { for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i); chr = this.charCodeAt(i);