繁体   English   中英

反应中继磁盘缓存

[英]React relay disk cache

我已经使用 GraphQL API 响应本机应用程序,其中使用的是 react-relay 库。 我需要为应用程序实现磁盘缓存,我看到请求已经在运行时缓存,但是在重新加载应用程序后,请求再次从服务器重新加载数据,但需要从缓存中获取。

好的,这是我不得不自己想出的一个有点粗糙的解决方案:

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. 当然,这是完全不安全的,因此对于敏感信息来说,这是一个很大的禁忌。 此外,您可能需要考虑在某个时间点(登录、注销等)清除缓存,这样如果您有不同的用户,数据就不会混淆。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM