我有一个带有GraphQL应用程序接口的react原生应用程序,其中用法是react-relay库。我需要对应用程序实现磁盘缓存,我看到请求已经在运行时缓存,但在重新加载应用程序后,请求再次从服务器重新加载数据,但需要从缓存中获取数据。
发布于 2021-11-19 10:40:42
好吧,这是我自己想出来的一个有点粗糙的解决方案:
import {
Environment,
Network,
QueryResponseCache,
RecordSource,
Store,
} from 'relay-runtime';
const oneMinute = 60 * 1000;
const cacheTtl = oneMinute * 1440; // 24 hours
const cache = new QueryResponseCache({ size: 500, ttl: cacheTtl });
// Restore cache from localStorage
const localStorageCacheResponses = localStorage.getItem('relay-cache');
if (localStorageCacheResponses) {
cache._responses = new Map(Object.entries(JSON.parse(localStorageCacheResponses)));
console.log('cache restored');
}然后,在更新缓存时:
// Update cache on queries
if (isQuery && json) {
cache.set(queryID, variables, json);
}
// Clear cache on mutations
if (isMutation) {
console.log('cache cleared');
cache.clear();
}
// Update localStorage cache copy (for persistent cache storage between sessions)
localStorage.setItem('relay-cache', JSON.stringify(Object.fromEntries(cache._responses)));您可以随意使用您喜欢的任何持久存储解决方案。我用的是localStorage,因为webapp。当然,这是完全不安全的,所以对敏感信息来说是一个很大的禁忌。此外,您可能需要考虑在某些时候(登录、注销等)清除缓存,这样如果您有不同的用户,数据就不会混淆。
https://stackoverflow.com/questions/43413740
复制相似问题