我最近遇到了一个场景,在这个场景中覆盖fetch可能是有利的。
我有什么将是一个进步的网络应用程序,将有离线功能。我遇到了一个问题,有几十个原始的fetch调用,现在我想将结果缓存到本地存储中。
if cache exists
invalidate cache if necessary
if cache valid
fetch from local storage
else
load from network
save results in local storage
else
load from network
save results in local storage一个潜在的问题是,本地存储可能不足以保存缓存的查询,这就是为什么我会考虑预先测试的解决方案。
如果我可以让它工作,那么我就不需要在整个代码中更改任何fetch调用。
const fetch = window.fetch;
window.fetch = function() {
// replaced fetch code here
}有像这样的东西吗?这看起来是个好主意吗?
发布于 2021-10-02 01:03:56
const fetch = window.fetch;
window.fetch = function() {
const obj = { data: 'json data' }; // replace with your own object
const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json' });
const init = { status: 200, statusText: 'success!' };
const response = new Response(blob, init);
return response;
}https://stackoverflow.com/questions/69382684
复制相似问题