lisaogren / axios-cache-adapter

Caching adapter for axios. Store request results in a configurable store to prevent unneeded network requests.
MIT License
726 stars 107 forks source link

It is not caching GET request having query strings #241

Closed AbhishekPrajapati closed 3 years ago

AbhishekPrajapati commented 3 years ago

It caches GET requests but when any GET request has query string, It is not caching.

Example URL is like: 'api/candidates?active=true'

const cachedAPIs = [
  "api/candidates",
  "api/candidates?active=true"
];

  const storageInfo = localforage.createInstance({
        driver: [
            localforage.LOCALSTORAGE,
        ],
        name: 'my_cache'
    });

    const cache = setupCache({
        maxAge: 15 * 60 * 1000,
        store: storageInfo,
        key: req =>  req.url.replace(window.APP_CONFIG.API_URL, ''),
        exclude: {
            filter: (req, a) => {
                if (req.method.toLowerCase() === 'get' && cachedAPIs && cachedAPIs.indexOf(req.url.toLowerCase()) != -1) {
                    return false;
                }
                return true;
            }
        },
        clearOnStale: true,
    });
Am I missing anything?
ghost commented 3 years ago

Hey @AbhishekPrajapati

Thanks for using axios-cache-adapter.

By default requests with query parameters are excluded from cache. You need to set the exclude.query option to false.

const cache = setupCache({
    maxAge: 15 * 60 * 1000,
    store: storageInfo,
    key: req =>  req.url.replace(window.APP_CONFIG.API_URL, ''),
    exclude: {
        query: false, // allow to cache requests with query parameters
        filter: (req, a) => {
            if (req.method.toLowerCase() === 'get' && cachedAPIs && cachedAPIs.indexOf(req.url.toLowerCase()) != -1) {
                return false;
            }
            return true;
        }
    },
    clearOnStale: true,
});

Be advised, the query parameters are serialized and used in the cache key so requests to the same URL with different query parameters are cached separately 🙂

I'll let you close the issue if all is good.

Cheers

ghost commented 3 years ago

Check out the full list of options: https://github.com/RasCarlito/axios-cache-adapter#setupcacheoptions

AbhishekPrajapati commented 3 years ago

Yeap @RasCarlito, That is working properly by setting exclude.query option to false.

I appreciate your quick response.