graphql - GraphQL Schema 上的计算字段或使用 Apollo Client 进行查询

标签 graphql apollo-client

我有一个返回两个字段的 GraphQL 查询,titleDetitleFr,代表两种不同语言的帖子标题。

我想在客户端有第三个字段(因此可能是本地状态定义的)以在 title 中存储当前语言的标题。然后,我的应用程序应该能够始终仅调用 title 并获取当前语言的标题。

在 Apollo(本地状态)或 GraphQL 中是否有等效的计算字段,这将允许我调用 title,它检查在 Apollo Local State 中全局设置的语言环境(所以另一个查询)和然后根据那个返回 titleDetitleFr

我还没有太多地使用 GraphQL 和 Apollo。我知道如何在其他本地状态管理器中解决这个问题,例如NgRx、Vuex、Redux 以及 getters/selectors 的概念。

我的目标是从我的应用程序组件中抽象出 titleDe/Fr 逻辑,因此它们不需要具有所有语言属性的模型,并且只能调用简化的 title 属性,它将返回基于全局设置语言环境的正确字符串。

最佳答案

您可以使用 Apollo 本地状态轻松添加其他字段。来自docs :

Local resolvers are very similar to remote resolvers. Instead of sending your GraphQL query to a remote GraphQL endpoint, which then runs resolver functions against your query to populate and return a result set, Apollo Client runs locally defined resolver functions against any fields marked with the @client directive.

这是一个简单的例子:

const GET_LOCALE = gql`
  query GetLocale {
    locale @client
  }
`;

const client = new ApolloClient({
  cache,
  link,
  resolvers: {
    Article: { // or whatever your actual type is called
      title: (article, _args, { cache }) => {
        const { locale } = cache.readQuery({ query: GET_LOCALE });
        switch (locale) {
          case 'de': return article.titleDe
          case 'fr': return article.titleFr
        }
      },
    },
  },
});

// Initialize the cache after creating it
cache.writeData({
  data: {
    locale: getPreferenceOrProvideDefault(),
  },
});

这里我们也将 locale 存储在本地状态中,并使用 readQuery 在我们的解析器中获取它。但是,您也可以直接从其他地方(例如 localStorage)获取首选项。

请注意,您仍然需要在查询中请求这些字段——即您的 title 字段将不会扩展为适当的服务器端字段集。

关于graphql - GraphQL Schema 上的计算字段或使用 Apollo Client 进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56073110/

相关文章:

reactjs - Apollo 缓存 - 缺少为查询字段名称返回的类型 undefined object 的选择集

javascript - GraphQL Args 错误 : argument type must be Input Type but got: function GraphQLObjectType(config) {

javascript - "StringQueryOperatorInput"类型是什么?我怎样才能摆脱这个恼人的 graphql 错误?

graphql - 更新特定列表/数组索引的 Apollo 本地缓存

reactjs - 无法使用@testing-library/user-event 使用新值更新文本区域

使用服务器发送事件和事件源的 GraphQL 订阅

node.js - 如何在 GraphQL 中执行突变?

用于 C++ 和 .NET 的 GraphQL 客户端

javascript - Apollo 客户端 useMutation 数据总是返回 undefined

vue.js - 从 apollo 缓存中读取查询,该查询尚不存在,但所有信息已存储在缓存中