Skip to content

Instantly share code, notes, and snippets.

@nicolasdanelon
Forked from FMCorz/store.js
Created August 14, 2018 13:12
Show Gist options
  • Save nicolasdanelon/4be4c285d0e7713228e100248db699cd to your computer and use it in GitHub Desktop.
Save nicolasdanelon/4be4c285d0e7713228e100248db699cd to your computer and use it in GitHub Desktop.
Fallback on cache when Axios reports a network error
import Axios from 'axios';
import { setupCache } from 'axios-cache-adapter';
import exclude from 'axios-cache-adapter/src/exclude';
// Define the cache adapter.
const cacheAdapter = setupCache({
clearOnStale: false,
});
const getKey = cacheAdapter.config.key;
const cacheStore = cacheAdapter.store;
// Our adapter factory which handles network errors.
const myAdapter = function(adapter) {
return async function(req) {
const isExcluded = exclude(cacheAdapter.config, req);
let res;
try {
res = await adapter(req);
} catch (e) {
if (e.request && (req.cache && req.cache.useOnNetworkError) && !isExcluded) {
// Mimic the behaviour of axios-cache-adapter, but directly get from store.
res = await cacheStore.getItem(getKey(req));
if (res && res.data) {
res = res.data;
res.config = req;
res.request = {
networkError: true,
fromCache: true
};
return res;
}
}
throw e;
}
return res;
};
};
const axios = Axios.create({
adapter: myAdapter(cacheAdapter.adapter),
cache: {
useOnNetworkError: true
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment