Last active
August 4, 2022 10:01
-
-
Save FMCorz/540bdd3e740d69dbf84fa0dc17cea940 to your computer and use it in GitHub Desktop.
Fallback on cache when Axios reports a network error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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