首页 > 解决方案 > 使用 TypeScript 空值检查的 Apollo 缓存更新

问题描述

我正在使用apollo codgen为我的 graphql 查询生成类型并使用 TS,我发现生成的类型中有很多null值,这样我的代码就会变成大量的if检查。这是人们用 TS 编写他们的 graphql 缓存更新的方式吗?

this.props.mutate({
  variables,
  update: (proxy, { data }) => {
    // nulls all the way down so guarding against them with early return
    if (!data || !data.createContact || !data.createContact.contact) return;
    let newContactEdge = {
      node: { ...data.createContact.contact, __typename: 'Contact' },
      __typename: 'ContactEdge',
    };

    // read from cache
    let listCache = proxy.readQuery<ListContactsQuery>({ query: ChatAPI.queries.listContacts });

    // again nulls all the way down
    if (listCache && listCache.contacts && listCache.contacts.edges) {
      proxy.writeQuery({
        query: ChatAPI.queries.listContacts,
        data: {
          ...listCache,
          contacts: {
            ...listCache.contacts,
            edges: [newContactEdge, ...listCache.contacts.edges],
          },
        },
      });
    }
  },
})

这只是感觉不对,在我知道 ifcache不为空之前,数据就会在那里并且不必一直检查。

作为参考,这里是生成的类型ListContactsQuery

export interface ListContactsQuery_contacts_edges {
    __typename: "ContactEdge";
    /**
     * The item at the end of the edge.
     */
    node: ListContactsQuery_contacts_edges_node | null;
}
export interface ListContactsQuery_contacts {
    __typename: "ContactConnection";
    /**
     * A list of edges.
     */
    edges: (ListContactsQuery_contacts_edges | null)[] | null;
}
export interface ListContactsQuery {
    /**
     * Gets all contacts for the current user
     */
    contacts: ListContactsQuery_contacts;
}

标签: typescriptgraphqlapolloapollo-client

解决方案


有点晚了,但仍然有人可能会发现它很有用。要减少Maybe<>客户端上的空检查数量(或更确切地说是类型数量),您必须适当地设置服务器端架构。例如在 GraphQL .net 中:

    Field<ListGraphType<RoleType>>()
            .Name(QueryName.Roles)
            .Resolve(context => AuthRoleRepo.LoadAllAuthRoles())
            .RequirePermission(Const.Roles.Admin);

变成

    Field<NonNullGraphType<ListGraphType<NonNullGraphType<RoleType>>>>()
            .Name(QueryName.Roles)
            .Resolve(context => AuthRoleRepo.LoadAllAuthRoles())
            .RequirePermission(Const.Roles.Admin);

请注意NonNullGraphType为返回类型指定的所有内容。ListGraphType<RoleType>=>NonNullGraphType<ListGraphType<NonNullGraphType<RoleType>>>


推荐阅读