Apollo Cache 机制源码分析

889 阅读1分钟

context全局只有一个

原因:保证更新缓存后,使用同一个context数据源

const { apolloClient, currentProject } = useModel('@@qiankunStateFromMaster')

源码:

// To make sure Apollo Client doesn't create more than one React context
// (which can lead to problems like having an Apollo Client instance added
// in one context, then attempting to retrieve it from another different
// context), a single Apollo context is created and tracked in global state.
// We use React.createContext as the key instead of just React to avoid
// ambiguities between default and namespace React imports.
 
const cache = new (canUseWeakMap ? WeakMap : Map)<
  typeof React.createContext,
  React.Context<ApolloContextValue>
>();

export function getApolloContext() {
  let context = cache.get(React.createContext)!;
  if (!context) {
    context = React.createContext<ApolloContextValue>({});
    context.displayName = "ApolloContext";
    cache.set(React.createContext, context);
  }
  return context;
}

src/core/QueryManager.ts

transform方法实现type id 转换

缓存策略

**cache-first:**
 Apollo 的默认获取策略是缓存优先。如果您自己不设置获取策略,则将使用此策略。它有利于查询的快速响应时间,而不是获取最新数据。 

1.  您查询一些数据。Apollo 检查缓存中的数据。*如果缓存中存在所有数据,请直接跳至步骤 4。*
1.  如果缓存丢失了您要求的某些数据,Apollo 将向您的 API 发出网络请求。
1.  API 响应数据,Apollo 使用它来更新缓存。
1.  返回请求的数据。
**network-only:**
此策略永远不会从缓存中返回可能过时的信息。

1.  Apollo 向您的数据发出网络请求,而无需检查缓存。
1.  服务器使用您的数据进行响应并更新缓存。
1.  数据被返回。
****no-cache:****

跳过了更新缓存的步骤

1.  Apollo 向您的数据发出网络请求,而无需检查缓存。
1.  服务器响应并返回数据而不更新缓存