axios-cache-interceptor: RedisStore - TypeError: Cannot read property 'data' of undefined

Using Redis store to get, set,remove. And i see below exception

err: TypeError: Cannot read property 'data' of undefined at t.adapter (/node_modules/axios-cache-interceptor/cjs/index.js:1:3074)

I do not see cjs/index.js in [axios-cache-interceptor](https://github.com/arthurfiorette/axios-cache-interceptor) repo

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 42 (21 by maintainers)

Commits related to this issue

Most upvoted comments

@arthurfiorette I figured the same issue but using localStorage. What I observed is having multiple gets to the same endpoint with a custom id and invalidating the request by id before executing the next to get request, then this error occurred. Probably because the code expects to have the request already cached. But I expect that if the request is not cached then do the original request to DB. I also observed that when this error appears all the following requests will fail and checking the network I observed that no request is made.

Well, I’m don’t know much about different redis instructions, there’s any major difference?

Also, how we can generate a custom key for custom storage, so that in tests i can look for that key

// You can force custom keys:
// https://axios-cache-interceptor.js.org/#/pages/per-request-configuration?id=id
const response = await axios.get('url', {
  id: 'custom key'
});

// Or get what id was used:
// https://axios-cache-interceptor.js.org/#/pages/response-object?id=id
const usedIdForThisRequest = response.id;

Went to read the documentation and it isn’t good. I guess that i’ll have to rewrite a lot of things today 😃

With umd development mode enabled, here is the output

node_modules/axios-cache-interceptor/umd/dev.js:1 !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AxiosCacheInterceptor=t():e.AxiosCacheInterceptor=t()}("undefined"!=typeof self?self:this,(function(){return(()=>{"use strict";var e={d:(t,a)=>{for(var r in a)e.o(a,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:a[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Header:()=>s,buildKeyGenerator:()=>E,buildMemoryStorage:()=>I,buildStorage:()=>S,buildWebStorage:()=>T,canStale:()=>y,createCacheResponse:()=>g,createValidateStatus:()=>d,defaultHeaderInterpreter:()=>i,defaultKeyGenerator:()=>j,defaultRequestInterceptor:()=>h,defaultResponseInterceptor:()=>m,isExpired:()=>x,isMethodIn:()=>u,isStorage:()=>w,setupCache:()=>R,testCachePredicate:()=>l,updateCache:()=>p,updateStaleRequest:()=>f});const a=Symbol("cache-parser");function r(e){return("string"==typeof e||"number"==typeof e)&&(e=Number(e))>=0&&e<1/0}function n(e){return!0===e||"number"==typeof e||"string"==typeof e&&"false"!==e}const o=Number;const s=Object.freeze({IfModifiedSince:"if-modified-since",LastModified:"last-modified",IfNoneMatch:"if-none-match",CacheControl:"cache-control",ETag:"etag",Expires:"expires",Age:"age",XAxiosCacheEtag:"x-axios-cache-etag",XAxiosCacheLastModified:"x-axios-cache-last-modified",XAxiosCacheStaleIfError:"x-axios-cache-stale-if-error"}),i=e=>{if(!e)return"not enough headers";const t=e[s.CacheControl];if(t){const{noCache:i,noStore:c,mustRevalidate:d,maxAge:u,immutable:f}=function(e){const t=Object.defineProperty({},a,{enumerable:!1,value:1});if(!e||"string"!=typeof e)return t;const s=function(e){const t={},a=e.toLowerCase().replace(/\s+/g,"").split(",");for(const e in a){var r;const n=a[e].split("=",2);t[n[0]]=null==(r=n[1])||r}return t}(e),i=s["max-age"],c=s["max-stale"],d=s["min-fresh"],u=s["s-maxage"],f=s["stale-if-error"],g=s["stale-while-revalidate"];return n(s.immutable)&&(t.immutable=!0),r(i)&&(t.maxAge=o(i)),r(c)&&(t.maxStale=o(c)),r(d)&&(t.minFresh=o(d)),n(s["must-revalidate"])&&(t.mustRevalidate=!0),n(s["must-understand"])&&(t.mustUnderstand=!0),n(s["no-cache"])&&(t.noCache=!0),n(s["no-store"])&&(t.noStore=!0),n(s["no-transform"])&&(t.noTransform=!0),n(s["only-if-cached"])&&(t.onlyIfCached=!0),n(s.private)&&(t.private=!0),n(s["proxy-revalidate"])&&(t.proxyRevalidate=!0),n(s.public)&&(t.public=!0),r(u)&&(t.sMaxAge=o(u)),r(f)&&(t.staleIfError=o(f)),r(g)&&(t.staleWhileRevalidate=o(g)),t}(String(t));if(i||c)return"dont cache";if(f)return 31536e6;if(d)return 0;if(u){const t=e[s.Age];return t?1e3*(u-Number(t)):1e3*u}}const i=e[s.Expires];if(i){const e=Date.parse(String(i))-Date.now();return e>=0?e:"dont cache"}return"not enough headers"},c=Symbol();function d(e){return e?t=>e(t)||304===t:e=>e>=200&&e<300||304===e}function u(e="get",t=[]){e=e.toLowerCase();for(const a of t)if(a.toLowerCase()===e)return!0;return!1}function f(e,t){t.headers||(t.headers={});const{etag:a,modifiedSince:r}=t.cache;if(a){const r=!0===a?e.data?.headers[s.ETag]:a;r&&(t.headers[s.IfNoneMatch]=r)}r&&(t.headers[s.IfModifiedSince]=!0===r?e.data.headers[s.LastModified]||new Date(e.createdAt).toUTCString():r.toUTCString())}function g(e,t){return 304===e.status&&t?(e.cached=!0,e.data=t.data,e.status=t.status,e.statusText=t.statusText,e.headers={...t.headers,...e.headers},t):{data:e.data,status:e.status,statusText:e.statusText,headers:e.headers}}function h(e){const t=async t=>{if(!1===t.cache)return e.debug?.({msg:"Ignoring cache because config.cache is false",data:t}),t;if(t.cache={...e.defaults.cache,...t.cache},!u(t.method,t.cache.methods))return e.debug?.({msg:Ignored because method (${t.method}) is not in cache.methods (${t.cache.methods})}),t;const a=t.id=e.generateKey(t);let r,n=await e.storage.get(a);e:if("empty"===n.state||"stale"===n.state){if(e.waiting[a]){n=await e.storage.get(a),e.debug?.({id:a,msg:"Waiting list had an deferred for this key, waiting for it to finish"});break e}return e.waiting[a]=function(){let e,t;const a=new Promise(((a,r)=>{e=a,t=r}));return a.resolve=e,a.reject=t,a[c]=1,a}(),e.waiting[a]?.catch((()=>{})),await e.storage.set(a,{state:"loading",previous:n.state,data:n.data,createdAt:n.createdAt}),"stale"===n.state&&(f(n,t),e.debug?.({id:a,msg:"Updated stale request"})),t.validateStatus=d(t.validateStatus),e.debug?.({id:a,msg:"Sending request, waiting for response"}),t}if("loading"===n.state){const n=e.waiting[a];if(!n)return await e.storage.remove(a),t;e.debug?.({id:a,msg:"Detected concurrent request, waiting for it to finish"});try{r=await n}catch(r){return e.debug?.({id:a,msg:"Deferred rejected, requesting again",data:r}),t}}else r=n.data;return t.adapter=()=>Promise.resolve({config:t,data:r.data,headers:r.headers,status:r.status,statusText:r.statusText,cached:!0,id:a}),e.debug?.({id:a,msg:"Returning cached response"}),t};return{onFulfilled:t,apply:()=>e.interceptors.request.use(t)}}async function l(e,t){if("function"==typeof t)return t(e);const{statusCheck:a,responseMatch:r,containsHeaders:n}=t;if(a&&!await a(e.status)||r&&!await r(e))return!1;if(n)for(const t in n){const a=n[t];if(a&&!await a(e.headers[t.toLowerCase()]??e.headers[t]))return!1}return!0}async function p(e,t,a){for(const r in a){const n=a[r];if("delete"===n){await e.remove(r);continue}const o=await e.get(r);if("loading"===o.state)continue;const s=await n(o,t);"delete"!==s?"ignore"!==s&&await e.set(r,s):await e.remove(r)}}function m(e){const t=async t=>{await e.storage.remove(t),e.waiting[t]?.reject(null),delete e.waiting[t]},a=async a=>{var r;if(a.id=(r=a.config).id??(r.id=e.generateKey(a.config)),a.cached??(a.cached=!1),a.cached)return e.debug?.({id:a.id,msg:"Returned cached response"}),a;if(!a.config.cache)return e.debug?.({id:a.id,msg:"Response with config.cache === false",data:a}),{...a,cached:!1};const n=a.config.cache,o=await e.storage.get(a.id);if("stale"===o.state||"empty"===o.state||"cached"===o.state)return e.debug?.({id:a.id,msg:"Response not cached but storage is not loading",data:{cache:o,response:a}}),a;if(!o.data&&!await l(a,n.cachePredicate))return await t(a.id),e.debug?.({id:a.id,msg:"Cache predicate rejected this response"}),a;for(const e in s)e.startsWith("XAxiosCache")&&delete a.headers[e];n.etag&&!0!==n.etag&&(a.headers[s.XAxiosCacheEtag]=n.etag),n.modifiedSince&&(a.headers[s.XAxiosCacheLastModified]=!0===n.modifiedSince?"use-cache-timestamp":n.modifiedSince.toUTCString());let i=n.ttl||-1;if(n?.interpretHeader){const r=e.headerInterpreter(a.headers);if("dont cache"===r)return await t(a.id),e.debug?.({id:a.id,msg:"Cache header interpreted as 'dont cache'",data:{cache:o,response:a,expirationTime:r}}),a;i="not enough headers"===r?i:r}const c=g(a,o.data);"function"==typeof i&&(i=await i(a)),n.staleIfError&&(a.headers[s.XAxiosCacheStaleIfError]=String(i)),e.debug?.({id:a.id,msg:"Useful response configuration found",data:{cacheConfig:n,ttl:i,cacheResponse:c}}),n?.update&&await p(e.storage,a,n.update);const d={state:"cached",ttl:i,createdAt:Date.now(),data:c},u=e.waiting[a.id];return u&&(u.resolve(d.data),delete e.waiting[a.id],e.debug?.({id:a.id,msg:"Found waiting deferred(s) and resolved them"})),await e.storage.set(a.id,d),e.debug?.({id:a.id,msg:"Response cached",data:{cache:d,response:a}}),a},r=async a=>{const r=a.config;if(!r||!1===r.cache||!r.id)throw e.debug?.({msg:"Web request returned an error but cache handling is not enabled",data:{error:a,config:r}}),a;const n=await e.storage.get(r.id),o=r.cache;if("loading"!==n.state||"stale"!==n.previous)throw await t(r.id),e.debug?.({msg:"Caught an error in the request interceptor",data:{error:a,config:r}}),a;if(o?.staleIfError){const t="function"==typeof o.staleIfError?await o.staleIfError(a.response,n,a):o.staleIfError;if(e.debug?.({msg:"Found cache if stale config for rejected response",data:{error:a,config:r,staleIfError:t}}),!0===t||"number"==typeof t&&n.createdAt+t>Date.now())return e.waiting[r.id]?.resolve(n.data),delete e.waiting[r.id],await e.storage.set(r.id,{state:"stale",createdAt:Date.now(),data:n.data}),e.debug?.({msg:"staleIfError resolved this response with cached data",data:{error:a,config:r,cache:n}}),{cached:!0,config:r,id:r.id,data:n.data.data,headers:n.data.headers,status:n.data.status,statusText:n.data.statusText}}throw e.debug?.({msg:"Received an unknown error that could not be handled",data:{error:a,config:r}}),a};return{onFulfilled:a,onRejected:r,apply:()=>e.interceptors.response.use(a,r)}}const b=Symbol(),w=e=>!!e&&!!e[b];function y(e){const t=e.data.headers;return s.ETag in t||s.LastModified in t||s.XAxiosCacheEtag in t||s.XAxiosCacheStaleIfError in t||s.XAxiosCacheLastModified in t}function x(e){return e.createdAt+e.ttl<=Date.now()}function S({set:e,find:t,remove:a}){return{[b]:1,set:e,remove:a,get:async r=>{const n=await t(r);if(!n)return{state:"empty"};if("cached"!==n.state||!x(n))return n;if(y(n)){const t={state:"stale",createdAt:n.createdAt,data:n.data};return await e(r,t),t}return await a(r),{state:"empty"}}}}function I(){const e=S({find:t=>e.data[t],set:(t,a)=>{e.data[t]=a},remove:t=>{delete e.data[t]}});return e.data=Object.create(null),e}function v(e){const t=typeof e;if(e&&"object"==t&&!(e instanceof Date||e instanceof RegExp)){const t=Array.isArray(e)?[]:{};for(const a in e)t[a]=v(e[a]);return${e.constructor}${JSON.stringify(t,Object.keys(e).sort())}}return${t}${String(e)}}function C(e){e=v(e);let t=5381,a=0;for(;a<e.length;)t=33*t^e.charCodeAt(a++);return t}const A=/^\/|\/$/g;function E(e){return t=>{if(t.id)return t.id;const a=e(t);return"string"==typeof a||"number"==typeof a?${a}:${C(a)}`}}const j=E((({baseURL:e=“”,url:t=“”,method:a=“get”,params:r,data:n})=>(e&&(e=e.replace(A,“”)),t&&(t=t.replace(A,“”)),a&&(a=a.toLowerCase()),{url:e+(e&&t?“/”:“”)+t,params:r,method:a,data:n})));function R(e,t={}){const a=e;if(a.storage=t.storage||I(),!w(a.storage))throw new Error(“Use buildStorage() function”);return a.generateKey=t.generateKey||j,a.waiting=t.waiting||{},a.headerInterpreter=t.headerInterpreter||i,a.requestInterceptor=t.requestInterceptor||h(a),a.responseInterceptor=t.responseInterceptor||m(a),a.debug=t.debug,a.defaults.cache={ttl:t.ttl??3e5,interpretHeader:t.interpretHeader??!1,methods:t.methods||[“get”],cachePredicate:t.cachePredicate||{statusCheck:e=>e>=200&&e<400},etag:t.etag??!1,modifiedSince:t.modifiedSince??!1,staleIfError:t.staleIfError??!1,update:t.update||{}},a.requestInterceptor.apply(),a.responseInterceptor.apply(),a}function T(e,t=“”){return S({find:a=>{const r=e.getItem(t+a);return r?JSON.parse®:void 0},remove:a=>{e.removeItem(t+a)},set:(a,r)=>{const n=()=>e.setItem(t+a,JSON.stringify®);try{return n()}catch®{const o=Object.entries(e).filter((([a])=>a.startsWith(t)&&e.getItem(a))).map((([e,t])=>[e,JSON.parse(t)]));for(const[t,a]of o)“cached”===a.state&&x(a)&&!y(a)&&e.removeItem(t);try{return n()}catch(t){const a=o.sort((([,e],[,t])=>(e.createdAt||0)-(t.createdAt||0)));for(const[t]of a){e.removeItem(t);try{return n()}catch(e){}}}e.removeItem(t+a)}}})}return console.error(“You are using a development build. Make sure to use the correct build in production”),console.error(“https://axios-cache-interceptor.js.org/#/pages/installing”),t})()}));

SyntaxError: Unexpected token ‘.’ at wrapSafe (internal/modules/cjs/loader.js:1070:16) at Module._compile (internal/modules/cjs/loader.js:1120:27) at Module._extensions…js (internal/modules/cjs/loader.js:1176:10) at Object.require.extensions.<computed> [as .js] (node_modules/ts-node/src/index.ts:851:44) at Module.load (internal/modules/cjs/loader.js:1000:32) at Function.Module._load (internal/modules/cjs/loader.js:893:16) at Module.require (internal/modules/cjs/loader.js:1042:19) at require (internal/modules/cjs/helpers.js:77:18) at Module._compile (internal/modules/cjs/loader.js:1156:30) at Module.m._compile (node_modules/ts-node/src/index.ts:858:23) at Module._extensions…js (internal/modules/cjs/loader.js:1176:10) at Object.require.extensions.<computed> [as .ts] (node_modules/ts-node/src/index.ts:861:12) at Module.load (internal/modules/cjs/loader.js:1000:32) at Function.Module._load (internal/modules/cjs/loader.js:893:16) at Module.require (internal/modules/cjs/loader.js:1042:19) at require (internal/modules/cjs/helpers.js:77:18) at Object.<anonymous> (src/lib/notifySms.ts:24:1) at Module._compile (internal/modules/cjs/loader.js:1156:30) at Module.m._compile (node_modules/ts-node/src/index.ts:858:23) at Module._extensions…js (internal/modules/cjs/loader.js:1176:10) at Object.require.extensions.<computed> [as .ts] (node_modules/ts-node/src/index.ts:861:12) at Module.load (internal/modules/cjs/loader.js:1000:32) at Function.Module._load (internal/modules/cjs/loader.js:893:16) at Module.require (internal/modules/cjs/loader.js:1042:19) at require (internal/modules/cjs/helpers.js:77:18) at Object.<anonymous> (src/test/integration/notifications.test.ts:43:1) at Module._compile (internal/modules/cjs/loader.js:1156:30) at Module.m._compile (node_modules/ts-node/src/index.ts:858:23) at Module._extensions…js (internal/modules/cjs/loader.js:1176:10) at Object.require.extensions.<computed> [as .ts] (node_modules/ts-node/src/index.ts:861:12) at Module.load (internal/modules/cjs/loader.js:1000:32) at Function.Module._load (internal/modules/cjs/loader.js:893:16) at Module.require (internal/modules/cjs/loader.js:1042:19) at require (internal/modules/cjs/helpers.js:77:18) at Object.implementationOfRequireOrImportForUnstableEsm [as requireOrImport] (node_modules/mocha/lib/nodejs/esm-utils.js:116:12) at Object.exports.loadFilesAsync (node_modules/mocha/lib/nodejs/esm-utils.js:103:34) at singleRun (node_modules/mocha/lib/cli/run-helpers.js:125:3) at Object.exports.handler (node_modules/mocha/lib/cli/run.js:374:5)`