【问题标题】:How can I use `schema` in apollo client cache?如何在 apollo 客户端缓存中使用“模式”?
【发布时间】:2019-11-12 16:48:30
【问题描述】:

我在 react 项目中使用 apollo-client 来管理 UI 状态。我为 apollo 突变定义了一个模式类型,但它似乎不起作用。

下面是我如何创建apollo client 实例。

const cache = new InMemoryCache();

export const createClient = () => {
  return new ApolloClient({
    cache,
    resolvers: {
      Mutation: {
        ...alertResolvers
      },
    },
    typeDefs: [alertTypeDefs]
  });
};

下面的代码是类型模式定义。如您所见,我创建了一个showErrorAlert 返回类型为Alert

export const alertTypeDefs = gql`
  type Alert {
    id: ID!
    message: String!
    type: String!
    duration: Int!
  }
  extend type Mutation {
    showErrorAlert(message: String!): Alert
  }
`;

我使用下面的代码发送突变。如您所见,它没有在返回对象中返回duration。但是该应用程序可以正常工作。该类型似乎对应用程序没有影响。

gql`
  mutation showErrorAlert($message: String!) {
    showErrorAlert(message: $message)  @client {
      id
      message
      type
    }
  }
`;

【问题讨论】:

    标签: graphql apollo react-apollo apollo-client


    【解决方案1】:

    来自docs

    您可以选择通过 ApolloClient 构造函数 typeDefs 参数或本地状态 API setTypeDefs 方法设置要与 Apollo Client 一起使用的客户端模式... 此模式不用于验证在服务器上,因为用于模式验证的 graphql-js 模块会大大增加你的包大小。相反,您的客户端架构用于 Apollo Client Devtools 中的自省,您可以在 GraphiQL 中探索您的架构。

    换句话说,为本地状态提供typeDefs 的唯一一点是在 Apollo Client Devtools 中启用通过 GraphiQL 查询本地状态。

    本地状态没有类型验证,但如果缓存中对象的一般形状与请求的形状不匹配,客户端会抛出异常。

    【讨论】:

    • 你应该如何查询存储在 Apollo 本地缓存中的 JSON 对象?假设该对象中有一些未知属性。
    猜你喜欢
    • 2020-08-07
    • 2017-03-18
    • 2021-04-21
    • 2020-11-03
    • 2018-02-05
    • 2023-03-07
    • 2019-03-24
    • 2019-04-02
    相关资源
    最近更新 更多