Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何在 apollo client 中实现基于 operation + variable 的缓存策略 #321

Open
xxleyi opened this issue Sep 11, 2021 · 0 comments
Open

Comments

@xxleyi
Copy link
Owner

xxleyi commented Sep 11, 2021

这个问题略微有些 hack,但是如果实现,又是比较好用,尤其适合实现粗粒度的策略。

import {fieldKeyArgs, fieldKeyArgsFunction} from './cacheField'

const addCacheKeyLink = new ApolloLink((operation, forward) => {
  // 将 Query 列的根字段动态添加 fieldKeyArgsFunction
  for (const e of operation.query.definitions[0].selectionSet.selections) {
    fieldKeyArgs[e.name.value] = fieldKeyArgsFunction
  }
  // 将 operation 的名字作为 apolloCacheKey 添加到 variables 中
  operation.variables[Symbol.for("apolloCacheKey")] = operation.operationName;
  return forward(operation);
});
# fieldCache.js
export const fieldKeyArgs = {};
export const fieldKeyArgsFunction = {
  keyArgs(_, context) {
    const variables = context.variables;
    const feildName = context.fieldName;
    const apolloCacheKey = variables[Symbol.for("apolloCacheKey")];
    return `${feildName}.${apolloCacheKey}`;
  }
};
import { InMemoryCache } from "@apollo/client";
import {fieldKeyArgs} from './cacheField'

export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: fieldKeyArgs,
    },
  },
});

上面这条路不通。换了个法子,使用工具从 server 端拿到所有 root query fields,预置 fieldPolicy,通过 hack 方式将 rootField 与 operationName 通过 weakMap 建立关联。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant