如何在 apollo 客户端缓存中使用 `schema`?

How can I use `schema` in apollo client cache?

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

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

const cache = new InMemoryCache();

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

下面的代码是类型模式定义。如您所见,我创建了 showErrorAlert return 类型的 Alert.

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

我使用下面的代码发送突变。如您所见,它不 return return 对象中的 duration。但是该应用程序可以正常运行,没有任何错误。似乎类型对应用程序没有影响。

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

来自docs

You can optionally set a client-side schema to be used with Apollo Client, through either the ApolloClient constructor typeDefs parameter, or the local state API setTypeDefs method... This schema is not used for validation like it is on the server because the graphql-js modules for schema validation would dramatically increase your bundle size. Instead, your client-side schema is used for introspection in Apollo Client Devtools, where you can explore your schema in GraphiQL.

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

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