async-source
Advanced tools
Comparing version
@@ -13,3 +13,3 @@ interface AsyncStorage { | ||
debounceTime?: number; | ||
requestCacheKey?: string; | ||
requestCacheKey?: string | (() => string); | ||
cacheTime?: number; | ||
@@ -43,2 +43,3 @@ cacheStorage?: CacheStorage; | ||
static setConfig(config: AsyncSourceConfig): void; | ||
static invalidateCacheKey(cacheKey: string, storage?: CacheStorage): Promise<void>; | ||
get data(): ResponseData<T>; | ||
@@ -45,0 +46,0 @@ get isLoading(): boolean; |
@@ -39,2 +39,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var DEFAULT_ENTRY_KEY = 'default'; | ||
var AsyncSource = /** @class */ (function () { | ||
@@ -78,2 +79,29 @@ function AsyncSource(serviceMethod, errorHandler, debounceTimeOrConfig) { | ||
}; | ||
AsyncSource.invalidateCacheKey = function (cacheKey, storage) { | ||
var _a; | ||
if (storage === void 0) { storage = AsyncSource.defaultStorage; } | ||
return __awaiter(this, void 0, void 0, function () { | ||
var key, error_1; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
key = "".concat(AsyncSource.cachePrefix, "-").concat(cacheKey); | ||
_b.label = 1; | ||
case 1: | ||
_b.trys.push([1, 4, , 5]); | ||
if (!cacheKey) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, ((_a = storage === null || storage === void 0 ? void 0 : storage.removeItem) === null || _a === void 0 ? void 0 : _a.call(storage, key))]; | ||
case 2: | ||
_b.sent(); | ||
_b.label = 3; | ||
case 3: return [3 /*break*/, 5]; | ||
case 4: | ||
error_1 = _b.sent(); | ||
console.warn({ message: "Cache invalidate error cacheKey:".concat(key), error: error_1 }); | ||
return [3 /*break*/, 5]; | ||
case 5: return [2 /*return*/]; | ||
} | ||
}); | ||
}); | ||
}; | ||
Object.defineProperty(AsyncSource.prototype, "data", { | ||
@@ -214,4 +242,4 @@ // Response data getter | ||
case 0: | ||
this.updateCacheKey(args); | ||
return [4 /*yield*/, this.getCachedData()]; | ||
this.updateCacheKey(); | ||
return [4 /*yield*/, this.getCachedData(args)]; | ||
case 1: | ||
@@ -229,15 +257,16 @@ cachedData = _a.sent(); | ||
}; | ||
AsyncSource.prototype.updateCacheKey = function (requestParams) { | ||
var baseCacheKey = "".concat(AsyncSource.cachePrefix, "-").concat(this.requestCacheKey); | ||
var isRequestParamsExist = Boolean(requestParams.length); | ||
var requestParamsHash; | ||
if (isRequestParamsExist) { | ||
AsyncSource.prototype.updateCacheKey = function () { | ||
var dynamicKey = ''; | ||
if (typeof this.requestCacheKey === 'function') { | ||
try { | ||
requestParamsHash = JSON.stringify(requestParams); | ||
dynamicKey = this.requestCacheKey(); | ||
} | ||
catch (error) { | ||
console.warn({ message: "Request params saving error cacheKey:".concat(baseCacheKey), params: requestParams, error: error }); | ||
console.warn({ message: 'Error generating dynamic cacheKey', error: error }); | ||
} | ||
} | ||
this.cacheKey = requestParamsHash ? "".concat(baseCacheKey, "-").concat(requestParamsHash) : baseCacheKey; | ||
else if (typeof this.requestCacheKey === 'string') { | ||
dynamicKey = this.requestCacheKey; | ||
} | ||
this.cacheKey = "".concat(AsyncSource.cachePrefix, "-").concat(dynamicKey); | ||
}; | ||
@@ -247,3 +276,3 @@ AsyncSource.prototype.removeCachedData = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
var error_1; | ||
var error_2; | ||
return __generator(this, function (_c) { | ||
@@ -262,4 +291,4 @@ switch (_c.label) { | ||
case 3: | ||
error_1 = _c.sent(); | ||
console.warn({ message: "Cache removing error cacheKey:".concat(this.cacheKey), error: error_1 }); | ||
error_2 = _c.sent(); | ||
console.warn({ message: "Cache removing error cacheKey:".concat(this.cacheKey), error: error_2 }); | ||
return [3 /*break*/, 4]; | ||
@@ -271,26 +300,32 @@ case 4: return [2 /*return*/]; | ||
}; | ||
AsyncSource.prototype.getCachedData = function () { | ||
AsyncSource.prototype.getCachedData = function (args) { | ||
var _a, _b; | ||
return __awaiter(this, void 0, void 0, function () { | ||
var storedData, _c, data, timestamp, isExpired, error_2; | ||
return __generator(this, function (_d) { | ||
switch (_d.label) { | ||
var storedData, cacheMap, isRequestParamsExist, argKey, cacheEntry, data, timestamp, isExpired, error_3; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
if (!this.cacheKey) | ||
return [2 /*return*/, null]; | ||
_d.label = 1; | ||
_c.label = 1; | ||
case 1: | ||
_d.trys.push([1, 3, , 4]); | ||
_c.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, ((_b = (_a = this.cacheStorage) === null || _a === void 0 ? void 0 : _a.getItem) === null || _b === void 0 ? void 0 : _b.call(_a, this.cacheKey))]; | ||
case 2: | ||
storedData = _d.sent(); | ||
storedData = _c.sent(); | ||
if (storedData) { | ||
_c = JSON.parse(storedData), data = _c.data, timestamp = _c.timestamp; | ||
isExpired = Date.now() - timestamp > this.cacheTime; | ||
return [2 /*return*/, isExpired ? null : data]; | ||
cacheMap = JSON.parse(storedData); | ||
isRequestParamsExist = Boolean(args.length); | ||
argKey = isRequestParamsExist ? JSON.stringify(args) : DEFAULT_ENTRY_KEY; | ||
cacheEntry = cacheMap[argKey]; | ||
if (cacheEntry) { | ||
data = cacheEntry.data, timestamp = cacheEntry.timestamp; | ||
isExpired = Date.now() - timestamp > this.cacheTime; | ||
return [2 /*return*/, isExpired ? null : data]; | ||
} | ||
} | ||
return [2 /*return*/, null]; | ||
case 3: | ||
error_2 = _d.sent(); | ||
console.warn({ message: "Cache getting error cacheKey:".concat(this.cacheKey), error: error_2 }); | ||
error_3 = _c.sent(); | ||
console.warn({ message: "Cache getting error cacheKey:".concat(this.cacheKey), error: error_3 }); | ||
return [2 /*return*/, null]; | ||
@@ -302,27 +337,34 @@ case 4: return [2 /*return*/]; | ||
}; | ||
AsyncSource.prototype.setCachedData = function (data) { | ||
var _a, _b; | ||
AsyncSource.prototype.setCachedData = function (data, args) { | ||
var _a, _b, _c, _d; | ||
return __awaiter(this, void 0, void 0, function () { | ||
var cacheValue, error_3; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
var isRequestParamsExist, argKey, newEntry, existingData, cacheMap, error_4; | ||
return __generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
if (!this.cacheKey) | ||
return [2 /*return*/]; | ||
cacheValue = { | ||
_e.label = 1; | ||
case 1: | ||
_e.trys.push([1, 4, , 5]); | ||
isRequestParamsExist = Boolean(args.length); | ||
argKey = isRequestParamsExist ? JSON.stringify(args) : DEFAULT_ENTRY_KEY; | ||
newEntry = { | ||
data: data, | ||
timestamp: Date.now() | ||
}; | ||
_c.label = 1; | ||
case 1: | ||
_c.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, ((_b = (_a = this.cacheStorage) === null || _a === void 0 ? void 0 : _a.setItem) === null || _b === void 0 ? void 0 : _b.call(_a, this.cacheKey, JSON.stringify(cacheValue)))]; | ||
return [4 /*yield*/, ((_b = (_a = this.cacheStorage) === null || _a === void 0 ? void 0 : _a.getItem) === null || _b === void 0 ? void 0 : _b.call(_a, this.cacheKey))]; | ||
case 2: | ||
_c.sent(); | ||
return [3 /*break*/, 4]; | ||
existingData = _e.sent(); | ||
cacheMap = existingData ? JSON.parse(existingData) : {}; | ||
cacheMap[argKey] = newEntry; | ||
return [4 /*yield*/, ((_d = (_c = this.cacheStorage) === null || _c === void 0 ? void 0 : _c.setItem) === null || _d === void 0 ? void 0 : _d.call(_c, this.cacheKey, JSON.stringify(cacheMap)))]; | ||
case 3: | ||
error_3 = _c.sent(); | ||
console.warn({ message: "Cache saving error cacheKey:".concat(this.cacheKey), error: error_3 }); | ||
return [3 /*break*/, 4]; | ||
case 4: return [2 /*return*/]; | ||
_e.sent(); | ||
return [3 /*break*/, 5]; | ||
case 4: | ||
error_4 = _e.sent(); | ||
console.warn({ message: "Cache saving error cacheKey:".concat(this.cacheKey), error: error_4 }); | ||
return [3 /*break*/, 5]; | ||
case 5: return [2 /*return*/]; | ||
} | ||
@@ -335,3 +377,3 @@ }); | ||
return __awaiter(this, void 0, void 0, function () { | ||
var requestId, response, error_4; | ||
var requestId, response, error_5; | ||
return __generator(this, function (_a) { | ||
@@ -369,3 +411,3 @@ switch (_a.label) { | ||
if (this.isCacheEnabled) { | ||
this.setCachedData(response); | ||
this.setCachedData(response, args); | ||
} | ||
@@ -375,3 +417,3 @@ } | ||
case 5: | ||
error_4 = _a.sent(); | ||
error_5 = _a.sent(); | ||
if (this.isLastRequest(requestId)) { | ||
@@ -381,3 +423,3 @@ this.isRequestPending = false; | ||
this.responseData = null; | ||
this.onError(error_4); | ||
this.onError(error_5); | ||
} | ||
@@ -384,0 +426,0 @@ return [3 /*break*/, 6]; |
@@ -1,1 +0,1 @@ | ||
"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});var AsyncSource=function(){function AsyncSource(serviceMethod,errorHandler,debounceTimeOrConfig){if(errorHandler===void 0){errorHandler=function(){}}if(debounceTimeOrConfig===void 0){debounceTimeOrConfig=100}this.responseData=null;this.isRequestPending=false;this.isFetchedData=false;this.lastRequestId=0;this.isCacheEnabled=false;this.cacheStorage=null;this.isUpdateCache=true;this.serviceMethod=serviceMethod;this.onError=errorHandler;if(typeof debounceTimeOrConfig==="number"){this.debounceTime=debounceTimeOrConfig}else{var _a=debounceTimeOrConfig.debounceTime,debounceTime=_a===void 0?100:_a,requestCacheKey=debounceTimeOrConfig.requestCacheKey,_b=debounceTimeOrConfig.cacheTime,cacheTime=_b===void 0?AsyncSource.defaultCacheTime:_b,_c=debounceTimeOrConfig.cacheStorage,cacheStorage=_c===void 0?AsyncSource.defaultStorage:_c,_d=debounceTimeOrConfig.isUpdateCache,isUpdateCache=_d===void 0?true:_d;this.debounceTime=debounceTime;this.isCacheEnabled=Boolean(requestCacheKey);this.requestCacheKey=requestCacheKey;this.cacheTime=cacheTime;this.cacheStorage=cacheStorage;this.isUpdateCache=isUpdateCache}}AsyncSource.setConfig=function(config){if(config.cacheStorage){AsyncSource.defaultStorage=config.cacheStorage}if(typeof config.cacheTime==="number"){AsyncSource.defaultCacheTime=config.cacheTime}if(config.cachePrefix){AsyncSource.cachePrefix=config.cachePrefix}};Object.defineProperty(AsyncSource.prototype,"data",{get:function(){return this.responseData},enumerable:false,configurable:true});Object.defineProperty(AsyncSource.prototype,"isLoading",{get:function(){return this.isRequestPending},enumerable:false,configurable:true});Object.defineProperty(AsyncSource.prototype,"isFetch",{get:function(){return this.isFetchedData},enumerable:false,configurable:true});AsyncSource.prototype.update=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.request(args)];case 1:_a.sent();return[2]}})})};AsyncSource.prototype.updateIfEmpty=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(this.data)return[2];return[4,this.request(args)];case 1:_a.sent();return[2]}})})};AsyncSource.prototype.updateOnce=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(!this.isLoading)return[3,3];return[4,new Promise(function(resolve){return setTimeout(resolve,100)})];case 1:_a.sent();return[4,this.updateOnce.apply(this,args)];case 2:_a.sent();return[3,5];case 3:return[4,this.updateIfEmpty.apply(this,args)];case 4:_a.sent();_a.label=5;case 5:return[2]}})})};AsyncSource.prototype.updateImmediate=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.request(args,undefined,true)];case 1:_a.sent();return[2]}})})};AsyncSource.prototype.push=function(successHandler){var args=[];for(var _i=1;_i<arguments.length;_i++){args[_i-1]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.request(args,successHandler)];case 1:_a.sent();return[2]}})})};AsyncSource.prototype.clear=function(){this.isRequestPending=false;this.isFetchedData=false;this.responseData=null;this.lastRequestId=0;this.removeCachedData()};AsyncSource.prototype.syncCache=function(args){return __awaiter(this,void 0,void 0,function(){var cachedData;return __generator(this,function(_a){switch(_a.label){case 0:this.updateCacheKey(args);return[4,this.getCachedData()];case 1:cachedData=_a.sent();if(cachedData){this.responseData=cachedData;this.isFetchedData=true;this.isRequestPending=false}return[2]}})})};AsyncSource.prototype.updateCacheKey=function(requestParams){var baseCacheKey="".concat(AsyncSource.cachePrefix,"-").concat(this.requestCacheKey);var isRequestParamsExist=Boolean(requestParams.length);var requestParamsHash;if(isRequestParamsExist){try{requestParamsHash=JSON.stringify(requestParams)}catch(error){console.warn({message:"Request params saving error cacheKey:".concat(baseCacheKey),params:requestParams,error:error})}}this.cacheKey=requestParamsHash?"".concat(baseCacheKey,"-").concat(requestParamsHash):baseCacheKey};AsyncSource.prototype.removeCachedData=function(){var _a,_b;return __awaiter(this,void 0,void 0,function(){var error_1;return __generator(this,function(_c){switch(_c.label){case 0:if(!this.cacheKey)return[2];_c.label=1;case 1:_c.trys.push([1,3,,4]);return[4,(_b=(_a=this.cacheStorage)===null||_a===void 0?void 0:_a.removeItem)===null||_b===void 0?void 0:_b.call(_a,this.cacheKey)];case 2:_c.sent();return[3,4];case 3:error_1=_c.sent();console.warn({message:"Cache removing error cacheKey:".concat(this.cacheKey),error:error_1});return[3,4];case 4:return[2]}})})};AsyncSource.prototype.getCachedData=function(){var _a,_b;return __awaiter(this,void 0,void 0,function(){var storedData,_c,data,timestamp,isExpired,error_2;return __generator(this,function(_d){switch(_d.label){case 0:if(!this.cacheKey)return[2,null];_d.label=1;case 1:_d.trys.push([1,3,,4]);return[4,(_b=(_a=this.cacheStorage)===null||_a===void 0?void 0:_a.getItem)===null||_b===void 0?void 0:_b.call(_a,this.cacheKey)];case 2:storedData=_d.sent();if(storedData){_c=JSON.parse(storedData),data=_c.data,timestamp=_c.timestamp;isExpired=Date.now()-timestamp>this.cacheTime;return[2,isExpired?null:data]}return[2,null];case 3:error_2=_d.sent();console.warn({message:"Cache getting error cacheKey:".concat(this.cacheKey),error:error_2});return[2,null];case 4:return[2]}})})};AsyncSource.prototype.setCachedData=function(data){var _a,_b;return __awaiter(this,void 0,void 0,function(){var cacheValue,error_3;return __generator(this,function(_c){switch(_c.label){case 0:if(!this.cacheKey)return[2];cacheValue={data:data,timestamp:Date.now()};_c.label=1;case 1:_c.trys.push([1,3,,4]);return[4,(_b=(_a=this.cacheStorage)===null||_a===void 0?void 0:_a.setItem)===null||_b===void 0?void 0:_b.call(_a,this.cacheKey,JSON.stringify(cacheValue))];case 2:_c.sent();return[3,4];case 3:error_3=_c.sent();console.warn({message:"Cache saving error cacheKey:".concat(this.cacheKey),error:error_3});return[3,4];case 4:return[2]}})})};AsyncSource.prototype.request=function(args,successHandler,isImmediate){return __awaiter(this,void 0,void 0,function(){var requestId,response,error_4;return __generator(this,function(_a){switch(_a.label){case 0:this.isRequestPending=true;return[4,this.createRequestId(isImmediate)];case 1:requestId=_a.sent();if(!this.isLastRequest(requestId))return[2];if(!this.isCacheEnabled)return[3,3];return[4,this.syncCache(args)];case 2:_a.sent();if(this.responseData&&!this.isRequestPending){this.isFetchedData=true;successHandler===null||successHandler===void 0?void 0:successHandler(this.responseData);if(!this.isUpdateCache){return[2]}}_a.label=3;case 3:_a.trys.push([3,5,,6]);return[4,this.serviceMethod.apply(this,args)];case 4:response=_a.sent();if(this.isLastRequest(requestId)){this.isRequestPending=false;this.isFetchedData=true;this.responseData=response;successHandler===null||successHandler===void 0?void 0:successHandler(response);if(this.isCacheEnabled){this.setCachedData(response)}}return[3,6];case 5:error_4=_a.sent();if(this.isLastRequest(requestId)){this.isRequestPending=false;this.isFetchedData=true;this.responseData=null;this.onError(error_4)}return[3,6];case 6:return[2]}})})};AsyncSource.prototype.createRequestId=function(isImmediate){var _this=this;var isFirstRequest=!this.lastRequestId;var requestId=this.lastRequestId+1;this.lastRequestId=requestId;if(isFirstRequest||isImmediate){return Promise.resolve(requestId)}return new Promise(function(resolve){return setTimeout(resolve,_this.debounceTime,requestId)})};AsyncSource.prototype.isLastRequest=function(requestId){return requestId===this.lastRequestId};AsyncSource.defaultCacheTime=12*60*60*1e3;AsyncSource.defaultStorage=localStorage;AsyncSource.cachePrefix="AsyncSource";return AsyncSource}();exports.default=AsyncSource; | ||
"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value)})}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator["throw"](value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};var __generator=this&&this.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");while(g&&(g=0,op[0]&&(_=0)),_)try{if(f=1,y&&(t=op[0]&2?y["return"]:op[0]?y["throw"]||((t=y["return"])&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;if(y=0,t)op=[op[0]&2,t.value];switch(op[0]){case 0:case 1:t=op;break;case 4:_.label++;return{value:op[1],done:false};case 5:_.label++;y=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t=_.trys,t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1];t=op;break}if(t&&_.label<t[2]){_.label=t[2];_.ops.push(op);break}if(t[2])_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e];y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:true}}};Object.defineProperty(exports,"__esModule",{value:true});var DEFAULT_ENTRY_KEY="default";var AsyncSource=function(){function AsyncSource(serviceMethod,errorHandler,debounceTimeOrConfig){if(errorHandler===void 0){errorHandler=function(){}}if(debounceTimeOrConfig===void 0){debounceTimeOrConfig=100}this.responseData=null;this.isRequestPending=false;this.isFetchedData=false;this.lastRequestId=0;this.isCacheEnabled=false;this.cacheStorage=null;this.isUpdateCache=true;this.serviceMethod=serviceMethod;this.onError=errorHandler;if(typeof debounceTimeOrConfig==="number"){this.debounceTime=debounceTimeOrConfig}else{var _a=debounceTimeOrConfig.debounceTime,debounceTime=_a===void 0?100:_a,requestCacheKey=debounceTimeOrConfig.requestCacheKey,_b=debounceTimeOrConfig.cacheTime,cacheTime=_b===void 0?AsyncSource.defaultCacheTime:_b,_c=debounceTimeOrConfig.cacheStorage,cacheStorage=_c===void 0?AsyncSource.defaultStorage:_c,_d=debounceTimeOrConfig.isUpdateCache,isUpdateCache=_d===void 0?true:_d;this.debounceTime=debounceTime;this.isCacheEnabled=Boolean(requestCacheKey);this.requestCacheKey=requestCacheKey;this.cacheTime=cacheTime;this.cacheStorage=cacheStorage;this.isUpdateCache=isUpdateCache}}AsyncSource.setConfig=function(config){if(config.cacheStorage){AsyncSource.defaultStorage=config.cacheStorage}if(typeof config.cacheTime==="number"){AsyncSource.defaultCacheTime=config.cacheTime}if(config.cachePrefix){AsyncSource.cachePrefix=config.cachePrefix}};AsyncSource.invalidateCacheKey=function(cacheKey,storage){var _a;if(storage===void 0){storage=AsyncSource.defaultStorage}return __awaiter(this,void 0,void 0,function(){var key,error_1;return __generator(this,function(_b){switch(_b.label){case 0:key="".concat(AsyncSource.cachePrefix,"-").concat(cacheKey);_b.label=1;case 1:_b.trys.push([1,4,,5]);if(!cacheKey)return[3,3];return[4,(_a=storage===null||storage===void 0?void 0:storage.removeItem)===null||_a===void 0?void 0:_a.call(storage,key)];case 2:_b.sent();_b.label=3;case 3:return[3,5];case 4:error_1=_b.sent();console.warn({message:"Cache invalidate error cacheKey:".concat(key),error:error_1});return[3,5];case 5:return[2]}})})};Object.defineProperty(AsyncSource.prototype,"data",{get:function(){return this.responseData},enumerable:false,configurable:true});Object.defineProperty(AsyncSource.prototype,"isLoading",{get:function(){return this.isRequestPending},enumerable:false,configurable:true});Object.defineProperty(AsyncSource.prototype,"isFetch",{get:function(){return this.isFetchedData},enumerable:false,configurable:true});AsyncSource.prototype.update=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.request(args)];case 1:_a.sent();return[2]}})})};AsyncSource.prototype.updateIfEmpty=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(this.data)return[2];return[4,this.request(args)];case 1:_a.sent();return[2]}})})};AsyncSource.prototype.updateOnce=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:if(!this.isLoading)return[3,3];return[4,new Promise(function(resolve){return setTimeout(resolve,100)})];case 1:_a.sent();return[4,this.updateOnce.apply(this,args)];case 2:_a.sent();return[3,5];case 3:return[4,this.updateIfEmpty.apply(this,args)];case 4:_a.sent();_a.label=5;case 5:return[2]}})})};AsyncSource.prototype.updateImmediate=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.request(args,undefined,true)];case 1:_a.sent();return[2]}})})};AsyncSource.prototype.push=function(successHandler){var args=[];for(var _i=1;_i<arguments.length;_i++){args[_i-1]=arguments[_i]}return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return[4,this.request(args,successHandler)];case 1:_a.sent();return[2]}})})};AsyncSource.prototype.clear=function(){this.isRequestPending=false;this.isFetchedData=false;this.responseData=null;this.lastRequestId=0;this.removeCachedData()};AsyncSource.prototype.syncCache=function(args){return __awaiter(this,void 0,void 0,function(){var cachedData;return __generator(this,function(_a){switch(_a.label){case 0:this.updateCacheKey();return[4,this.getCachedData(args)];case 1:cachedData=_a.sent();if(cachedData){this.responseData=cachedData;this.isFetchedData=true;this.isRequestPending=false}return[2]}})})};AsyncSource.prototype.updateCacheKey=function(){var dynamicKey="";if(typeof this.requestCacheKey==="function"){try{dynamicKey=this.requestCacheKey()}catch(error){console.warn({message:"Error generating dynamic cacheKey",error:error})}}else if(typeof this.requestCacheKey==="string"){dynamicKey=this.requestCacheKey}this.cacheKey="".concat(AsyncSource.cachePrefix,"-").concat(dynamicKey)};AsyncSource.prototype.removeCachedData=function(){var _a,_b;return __awaiter(this,void 0,void 0,function(){var error_2;return __generator(this,function(_c){switch(_c.label){case 0:if(!this.cacheKey)return[2];_c.label=1;case 1:_c.trys.push([1,3,,4]);return[4,(_b=(_a=this.cacheStorage)===null||_a===void 0?void 0:_a.removeItem)===null||_b===void 0?void 0:_b.call(_a,this.cacheKey)];case 2:_c.sent();return[3,4];case 3:error_2=_c.sent();console.warn({message:"Cache removing error cacheKey:".concat(this.cacheKey),error:error_2});return[3,4];case 4:return[2]}})})};AsyncSource.prototype.getCachedData=function(args){var _a,_b;return __awaiter(this,void 0,void 0,function(){var storedData,cacheMap,isRequestParamsExist,argKey,cacheEntry,data,timestamp,isExpired,error_3;return __generator(this,function(_c){switch(_c.label){case 0:if(!this.cacheKey)return[2,null];_c.label=1;case 1:_c.trys.push([1,3,,4]);return[4,(_b=(_a=this.cacheStorage)===null||_a===void 0?void 0:_a.getItem)===null||_b===void 0?void 0:_b.call(_a,this.cacheKey)];case 2:storedData=_c.sent();if(storedData){cacheMap=JSON.parse(storedData);isRequestParamsExist=Boolean(args.length);argKey=isRequestParamsExist?JSON.stringify(args):DEFAULT_ENTRY_KEY;cacheEntry=cacheMap[argKey];if(cacheEntry){data=cacheEntry.data,timestamp=cacheEntry.timestamp;isExpired=Date.now()-timestamp>this.cacheTime;return[2,isExpired?null:data]}}return[2,null];case 3:error_3=_c.sent();console.warn({message:"Cache getting error cacheKey:".concat(this.cacheKey),error:error_3});return[2,null];case 4:return[2]}})})};AsyncSource.prototype.setCachedData=function(data,args){var _a,_b,_c,_d;return __awaiter(this,void 0,void 0,function(){var isRequestParamsExist,argKey,newEntry,existingData,cacheMap,error_4;return __generator(this,function(_e){switch(_e.label){case 0:if(!this.cacheKey)return[2];_e.label=1;case 1:_e.trys.push([1,4,,5]);isRequestParamsExist=Boolean(args.length);argKey=isRequestParamsExist?JSON.stringify(args):DEFAULT_ENTRY_KEY;newEntry={data:data,timestamp:Date.now()};return[4,(_b=(_a=this.cacheStorage)===null||_a===void 0?void 0:_a.getItem)===null||_b===void 0?void 0:_b.call(_a,this.cacheKey)];case 2:existingData=_e.sent();cacheMap=existingData?JSON.parse(existingData):{};cacheMap[argKey]=newEntry;return[4,(_d=(_c=this.cacheStorage)===null||_c===void 0?void 0:_c.setItem)===null||_d===void 0?void 0:_d.call(_c,this.cacheKey,JSON.stringify(cacheMap))];case 3:_e.sent();return[3,5];case 4:error_4=_e.sent();console.warn({message:"Cache saving error cacheKey:".concat(this.cacheKey),error:error_4});return[3,5];case 5:return[2]}})})};AsyncSource.prototype.request=function(args,successHandler,isImmediate){return __awaiter(this,void 0,void 0,function(){var requestId,response,error_5;return __generator(this,function(_a){switch(_a.label){case 0:this.isRequestPending=true;return[4,this.createRequestId(isImmediate)];case 1:requestId=_a.sent();if(!this.isLastRequest(requestId))return[2];if(!this.isCacheEnabled)return[3,3];return[4,this.syncCache(args)];case 2:_a.sent();if(this.responseData&&!this.isRequestPending){this.isFetchedData=true;successHandler===null||successHandler===void 0?void 0:successHandler(this.responseData);if(!this.isUpdateCache){return[2]}}_a.label=3;case 3:_a.trys.push([3,5,,6]);return[4,this.serviceMethod.apply(this,args)];case 4:response=_a.sent();if(this.isLastRequest(requestId)){this.isRequestPending=false;this.isFetchedData=true;this.responseData=response;successHandler===null||successHandler===void 0?void 0:successHandler(response);if(this.isCacheEnabled){this.setCachedData(response,args)}}return[3,6];case 5:error_5=_a.sent();if(this.isLastRequest(requestId)){this.isRequestPending=false;this.isFetchedData=true;this.responseData=null;this.onError(error_5)}return[3,6];case 6:return[2]}})})};AsyncSource.prototype.createRequestId=function(isImmediate){var _this=this;var isFirstRequest=!this.lastRequestId;var requestId=this.lastRequestId+1;this.lastRequestId=requestId;if(isFirstRequest||isImmediate){return Promise.resolve(requestId)}return new Promise(function(resolve){return setTimeout(resolve,_this.debounceTime,requestId)})};AsyncSource.prototype.isLastRequest=function(requestId){return requestId===this.lastRequestId};AsyncSource.defaultCacheTime=12*60*60*1e3;AsyncSource.defaultStorage=localStorage;AsyncSource.cachePrefix="AsyncSource";return AsyncSource}();exports.default=AsyncSource; |
@@ -420,3 +420,3 @@ "use strict"; | ||
(0, vitest_1.it)("should save data to cache after successful fetch", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response, serviceMethod, asyncSource, _a, key, value, parsedValue; | ||
var response, serviceMethod, _a, key, value, parsedValue; | ||
return __generator(this, function (_b) { | ||
@@ -427,3 +427,3 @@ switch (_b.label) { | ||
serviceMethod = vitest_1.vi.fn(function () { return Promise.resolve(response); }); | ||
asyncSource = new index_1.default(serviceMethod, vitest_1.vi.fn(), { | ||
sut = new index_1.default(serviceMethod, vitest_1.vi.fn(), { | ||
requestCacheKey: "testKey", | ||
@@ -434,5 +434,9 @@ cacheStorage: mockStorage, | ||
}); | ||
return [4 /*yield*/, asyncSource.update()]; | ||
return [4 /*yield*/, sut.update()]; | ||
case 1: | ||
_b.sent(); | ||
return [4 /*yield*/, delay(100)]; | ||
case 2: | ||
_b.sent(); | ||
(0, vitest_1.expect)(mockStorage.getItem).toHaveBeenCalledTimes(2); | ||
(0, vitest_1.expect)(mockStorage.setItem).toHaveBeenCalledOnce(); | ||
@@ -442,4 +446,4 @@ _a = mockStorage.setItem.mock.calls[0], key = _a[0], value = _a[1]; | ||
parsedValue = JSON.parse(value); | ||
(0, vitest_1.expect)(parsedValue.data).toEqual(response); | ||
(0, vitest_1.expect)(parsedValue.timestamp).toBeGreaterThan(0); | ||
(0, vitest_1.expect)(parsedValue.default.data).toEqual(response); | ||
(0, vitest_1.expect)(parsedValue.default.timestamp).toBeGreaterThan(0); | ||
return [2 /*return*/]; | ||
@@ -449,2 +453,32 @@ } | ||
}); }); | ||
(0, vitest_1.it)("dynamic requestCacheKey", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response, serviceMethod, _a, key, value, parsedValue; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
response = { data: "test data" }; | ||
serviceMethod = vitest_1.vi.fn(function () { return Promise.resolve(response); }); | ||
sut = new index_1.default(serviceMethod, vitest_1.vi.fn(), { | ||
requestCacheKey: function () { return "testKey"; }, | ||
cacheStorage: mockStorage, | ||
cacheTime: 1000, | ||
isUpdateCache: true | ||
}); | ||
return [4 /*yield*/, sut.update()]; | ||
case 1: | ||
_b.sent(); | ||
return [4 /*yield*/, delay(100)]; | ||
case 2: | ||
_b.sent(); | ||
(0, vitest_1.expect)(mockStorage.getItem).toHaveBeenCalledTimes(2); | ||
(0, vitest_1.expect)(mockStorage.setItem).toHaveBeenCalledOnce(); | ||
_a = mockStorage.setItem.mock.calls[0], key = _a[0], value = _a[1]; | ||
(0, vitest_1.expect)(key).toContain("AsyncSource-testKey"); | ||
parsedValue = JSON.parse(value); | ||
(0, vitest_1.expect)(parsedValue.default.data).toEqual(response); | ||
(0, vitest_1.expect)(parsedValue.default.timestamp).toBeGreaterThan(0); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
(0, vitest_1.it)("should retrieve data from cache if available and not expired", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
@@ -455,4 +489,4 @@ var cachedResponse; | ||
case 0: | ||
cachedResponse = { data: { data: "cached data" }, timestamp: Date.now() }; | ||
mockStorage.getItem.mockResolvedValueOnce(JSON.stringify(cachedResponse)); | ||
cachedResponse = { default: { data: { data: "cached data" }, timestamp: Date.now() } }; | ||
mockStorage.getItem.mockResolvedValue(JSON.stringify(cachedResponse)); | ||
sut = new index_1.default(vitest_1.vi.fn(), vitest_1.vi.fn(), { | ||
@@ -466,3 +500,3 @@ requestCacheKey: "testKey", | ||
_a.sent(); | ||
(0, vitest_1.expect)(mockStorage.getItem).toHaveBeenCalledOnce(); | ||
(0, vitest_1.expect)(mockStorage.getItem).toHaveBeenCalledTimes(2); | ||
(0, vitest_1.expect)(mockStorage.getItem).toHaveBeenCalledWith(vitest_1.expect.stringContaining("AsyncSource-testKey")); | ||
@@ -479,4 +513,4 @@ return [2 /*return*/]; | ||
expiredTimestamp = Date.now() - 2000; | ||
cachedResponse = { data: { data: "cached data" }, timestamp: expiredTimestamp }; | ||
mockStorage.getItem.mockResolvedValueOnce(JSON.stringify(cachedResponse)); | ||
cachedResponse = { default: { data: { data: "cached data" }, timestamp: expiredTimestamp } }; | ||
mockStorage.getItem.mockResolvedValue(JSON.stringify(cachedResponse)); | ||
response = { data: "fresh data" }; | ||
@@ -492,2 +526,5 @@ serviceMethod = vitest_1.vi.fn(function () { return Promise.resolve(response); }); | ||
_a.sent(); | ||
return [4 /*yield*/, delay(100)]; | ||
case 2: | ||
_a.sent(); | ||
(0, vitest_1.expect)(sut.data).toEqual(response); | ||
@@ -537,4 +574,6 @@ (0, vitest_1.expect)(mockStorage.setItem).toHaveBeenCalledOnce(); | ||
(0, vitest_1.expect)(JSON.parse(value1)).toEqual(vitest_1.expect.objectContaining({ | ||
data: response, | ||
timestamp: vitest_1.expect.any(Number) | ||
default: { | ||
data: response, | ||
timestamp: vitest_1.expect.any(Number) | ||
} | ||
})); | ||
@@ -546,12 +585,12 @@ defaultStorageSetItemSpy.mockRestore(); | ||
}); }); | ||
(0, vitest_1.it)("should create two cache records with diff args", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response, serviceMethod, _a, key1, value1, _b, key2, value2; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
(0, vitest_1.it)("should store multiple cache entries under one key for different request args", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var response, serviceMethod, setItemSpy, _a, cacheKey, storedValue, parsed; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
response = { data: "default storage data" }; | ||
serviceMethod = vitest_1.vi.fn(function () { return Promise.resolve(response); }); | ||
setItemSpy = vitest_1.vi.spyOn(Storage.prototype, "setItem"); | ||
sut = new index_1.default(serviceMethod, vitest_1.vi.fn(), { | ||
requestCacheKey: "defaultKey", | ||
cacheStorage: mockStorage, | ||
cacheTime: 1000, | ||
@@ -561,18 +600,21 @@ }); | ||
case 1: | ||
_c.sent(); | ||
_b.sent(); | ||
return [4 /*yield*/, sut.update(2)]; | ||
case 2: | ||
_c.sent(); | ||
_a = mockStorage.setItem.mock.calls[0], key1 = _a[0], value1 = _a[1]; | ||
_b = mockStorage.setItem.mock.calls[1], key2 = _b[0], value2 = _b[1]; | ||
(0, vitest_1.expect)(key1).toContain("AsyncSource-defaultKey-[1]"); | ||
(0, vitest_1.expect)(JSON.parse(value1)).toEqual(vitest_1.expect.objectContaining({ | ||
data: response, | ||
timestamp: vitest_1.expect.any(Number) | ||
_b.sent(); | ||
(0, vitest_1.expect)(setItemSpy).toHaveBeenCalledTimes(2); | ||
_a = setItemSpy.mock.calls[1], cacheKey = _a[0], storedValue = _a[1]; | ||
(0, vitest_1.expect)(cacheKey).toContain("AsyncSource-defaultKey"); | ||
parsed = JSON.parse(storedValue); | ||
(0, vitest_1.expect)(parsed).toEqual(vitest_1.expect.objectContaining({ | ||
"[1]": { | ||
data: response, | ||
timestamp: vitest_1.expect.any(Number) | ||
}, | ||
"[2]": { | ||
data: response, | ||
timestamp: vitest_1.expect.any(Number) | ||
} | ||
})); | ||
(0, vitest_1.expect)(key2).toContain("AsyncSource-defaultKey-[2]"); | ||
(0, vitest_1.expect)(JSON.parse(value2)).toEqual(vitest_1.expect.objectContaining({ | ||
data: response, | ||
timestamp: vitest_1.expect.any(Number) | ||
})); | ||
setItemSpy.mockRestore(); | ||
return [2 /*return*/]; | ||
@@ -603,3 +645,3 @@ } | ||
(0, vitest_1.expect)(serviceMethod).toHaveBeenCalledTimes(2); | ||
(0, vitest_1.expect)(defaultStorageGetItemSpy).toHaveBeenCalledTimes(2); | ||
(0, vitest_1.expect)(defaultStorageGetItemSpy).toHaveBeenCalledTimes(4); | ||
(0, vitest_1.expect)(defaultStorageSetItemSpy).toHaveBeenCalledTimes(2); | ||
@@ -631,3 +673,3 @@ return [2 /*return*/]; | ||
(0, vitest_1.expect)(defaultStorageSetItemSpy).toHaveBeenCalledOnce(); | ||
(0, vitest_1.expect)(defaultStorageGetItemSpy).toHaveBeenCalledTimes(2); | ||
(0, vitest_1.expect)(defaultStorageGetItemSpy).toHaveBeenCalledTimes(3); | ||
return [2 /*return*/]; | ||
@@ -637,2 +679,54 @@ } | ||
}); }); | ||
(0, vitest_1.it)("should successfully invalidate the cache key", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var cacheKey, expectedKey, defaultStorageRemoveItemSpy; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
cacheKey = "testKey"; | ||
expectedKey = "AsyncSource-".concat(cacheKey); | ||
defaultStorageRemoveItemSpy = vitest_1.vi.spyOn(Storage.prototype, "removeItem"); | ||
// Call the function | ||
return [4 /*yield*/, index_1.default.invalidateCacheKey(cacheKey)]; | ||
case 1: | ||
// Call the function | ||
_a.sent(); | ||
// Assert that removeItem was called with the correct key | ||
(0, vitest_1.expect)(defaultStorageRemoveItemSpy).toHaveBeenCalledWith(expectedKey); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
(0, vitest_1.it)("should successfully invalidate the cache key for not default storage", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var cacheKey, expectedKey; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
cacheKey = "testKey"; | ||
expectedKey = "AsyncSource-".concat(cacheKey); | ||
// Call the function | ||
return [4 /*yield*/, index_1.default.invalidateCacheKey(cacheKey, mockStorage)]; | ||
case 1: | ||
// Call the function | ||
_a.sent(); | ||
// Assert that removeItem was called with the correct key | ||
(0, vitest_1.expect)(mockStorage.removeItem).toHaveBeenCalledWith(expectedKey); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
(0, vitest_1.it)('should set cacheKey using static string requestCacheKey', function () { | ||
var source = new index_1.default(function () { return Promise.resolve('data'); }, function () { }, { | ||
requestCacheKey: 'my-static-key' | ||
}); | ||
// Force update | ||
source.updateCacheKey(); | ||
(0, vitest_1.expect)(source.cacheKey).toBe('AsyncSource-my-static-key'); | ||
}); | ||
(0, vitest_1.it)('should set cacheKey using dynamic function requestCacheKey', function () { | ||
var source = new index_1.default(function () { return Promise.resolve('data'); }, function () { }, { | ||
requestCacheKey: function () { return 'dynamic-key'; } | ||
}); | ||
source.updateCacheKey(); | ||
(0, vitest_1.expect)(source.cacheKey).toBe('AsyncSource-dynamic-key'); | ||
}); | ||
}); | ||
@@ -649,29 +743,2 @@ (0, vitest_1.describe)("AsyncSource Cache Exception Handling", function () { | ||
}); | ||
(0, vitest_1.it)("should handle JSON.stringify error in updateCacheKey", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var circularReference, initialResponse, serviceMethod, consoleWarnSpy; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
circularReference = {}; | ||
circularReference.self = circularReference; | ||
initialResponse = { data: "initial data" }; | ||
serviceMethod = vitest_1.vi.fn(function () { return Promise.resolve(initialResponse); }); | ||
sut = new index_1.default(serviceMethod, vitest_1.vi.fn(), { | ||
requestCacheKey: "testCircular", | ||
cacheStorage: mockStorage | ||
}); | ||
consoleWarnSpy = vitest_1.vi.spyOn(console, "warn"); | ||
return [4 /*yield*/, sut.update(circularReference)]; | ||
case 1: | ||
_a.sent(); | ||
(0, vitest_1.expect)(serviceMethod).toHaveBeenCalledOnce(); | ||
(0, vitest_1.expect)(consoleWarnSpy).toHaveBeenCalledWith(vitest_1.expect.objectContaining({ | ||
message: "Request params saving error cacheKey:AsyncSource-testCircular", | ||
error: vitest_1.expect.any(Error) | ||
})); | ||
consoleWarnSpy.mockRestore(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
(0, vitest_1.it)("should handle removeItem error in removeCachedData", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
@@ -766,4 +833,63 @@ var initialResponse, serviceMethod, consoleWarnSpy; | ||
}); }); | ||
(0, vitest_1.it)("should handle errors during cache invalidation", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var cacheKey, consoleWarnSpy; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
cacheKey = "testKey"; | ||
mockStorage.removeItem.mockRejectedValueOnce(new Error("Storage error")); | ||
consoleWarnSpy = vitest_1.vi.spyOn(console, 'warn').mockImplementation(function () { }); | ||
// Call the function | ||
return [4 /*yield*/, index_1.default.invalidateCacheKey(cacheKey, mockStorage)]; | ||
case 1: | ||
// Call the function | ||
_a.sent(); | ||
// Assert that removeItem was called | ||
(0, vitest_1.expect)(mockStorage.removeItem).toHaveBeenCalledWith("AsyncSource-".concat(cacheKey)); | ||
// Assert that console.warn was called to log the error | ||
(0, vitest_1.expect)(consoleWarnSpy).toHaveBeenCalledWith({ | ||
message: "Cache invalidate error cacheKey:AsyncSource-".concat(cacheKey), | ||
error: vitest_1.expect.any(Error), | ||
}); | ||
// Clean up spy | ||
consoleWarnSpy.mockRestore(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
(0, vitest_1.it)("should do nothing when no cache key is provided", function () { return __awaiter(void 0, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
// Call the function with an empty cache key | ||
return [4 /*yield*/, index_1.default.invalidateCacheKey("", mockStorage)]; | ||
case 1: | ||
// Call the function with an empty cache key | ||
_a.sent(); | ||
// Assert that removeItem was not called | ||
(0, vitest_1.expect)(mockStorage.removeItem).not.toHaveBeenCalled(); | ||
return [2 /*return*/]; | ||
} | ||
}); | ||
}); }); | ||
(0, vitest_1.it)('should log a warning and set empty cacheKey if dynamic function throws', function () { | ||
var source = new index_1.default(function () { return Promise.resolve('data'); }, function () { }, { | ||
requestCacheKey: function () { | ||
throw new Error('Fail'); | ||
} | ||
}); | ||
source.updateCacheKey(); | ||
(0, vitest_1.expect)(console.warn).toHaveBeenCalledWith(vitest_1.expect.objectContaining({ | ||
message: 'Error generating dynamic cacheKey', | ||
error: vitest_1.expect.any(Error) | ||
})); | ||
(0, vitest_1.expect)(source.cacheKey).toBe('AsyncSource-'); | ||
}); | ||
(0, vitest_1.it)('should set empty cacheKey if requestCacheKey is undefined', function () { | ||
var source = new index_1.default(function () { return Promise.resolve('data'); }, function () { }, {}); | ||
source.updateCacheKey(); | ||
(0, vitest_1.expect)(source.cacheKey).toBe('AsyncSource-'); | ||
}); | ||
}); | ||
}); | ||
//# sourceMappingURL=index.test.js.map |
{ | ||
"name": "async-source", | ||
"version": "2.0.0", | ||
"version": "2.0.1", | ||
"description": "async requests wrapper", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.min.js", |
@@ -191,3 +191,3 @@ # AsyncSource | ||
debounceTime?: number; // Delay before request execution (in milliseconds) | ||
requestCacheKey?: string; // Request cache key (required for enable cache) | ||
requestCacheKey?: string | (() => string); // Request cache key (required for enable cache) | ||
cacheTime?: number; // Cache expiration in milliseconds | ||
@@ -202,3 +202,3 @@ cacheStorage?: CacheStorage; // Storage (e.g., localStorage, sessionStorage, indexDB) | ||
| `debounceTime` | `number` | `300` | Delay before request execution (in milliseconds). | | ||
| `requestCacheKey` | `string` | | Request cache key (required for enabling cache). | | ||
| `requestCacheKey` | `string \| (() => string)` | | Request cache key (required for enabling cache). | | ||
| `cacheTime` | `number` | `43200000` | Cache expiration time in milliseconds (default: 12 hours). | | ||
@@ -208,3 +208,28 @@ | `cacheStorage` | `CacheStorage` | `localStorage` | Storage interface (e.g., localStorage, sessionStorage, indexedDB). | | ||
### AsyncSource.invalidateCacheKey | ||
Invalidates (removes) the cache entry associated with the provided cache key. | ||
This method removes the cached data from the storage based on the provided `cacheKey` and the `cachePrefix`. The key used to identify the cached data is a combination of `cachePrefix` and the provided `cacheKey`. If the cache item exists in the storage, it will be removed. If an error occurs during the removal, it will be caught and logged, and the method will return `null`. | ||
#### Parameters | ||
- **`cacheKey`** (`string`): The key used to identify the cached data to be invalidated. This value is combined with the `cachePrefix` to form the full cache key. | ||
- **`storage`** (`CacheStorage`, optional): The storage where the cache is stored. If not provided, the default storage (`AsyncSource.defaultStorage`) will be used. | ||
#### Returns | ||
- **`Promise<void | null>`**: A promise that resolves to `void` if the cache entry was successfully invalidated, or `null` if an error occurred during the removal. | ||
#### Example | ||
```typescript | ||
// Example usage: | ||
await AsyncSource.invalidateCacheKey("myCacheKey"); | ||
// You can also provide a custom storage: | ||
await AsyncSource.invalidateCacheKey("myCacheKey", customStorage); | ||
``` | ||
#### Example #### | ||
@@ -211,0 +236,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
138898
14.4%1378
13.98%329
8.22%