typescript - 使用 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;
}
解决方案
有点晚了,但仍然有人可能会发现它很有用。要减少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>>>
推荐阅读
- node.js - 节点 - Cheerio - 查找包含特定文本的元素
- python - Selenium 显式等待分页
- rust - 如何在 actix-web 中使用 tokio_postgres
- javascript - 当我鼠标离开菜单时,我无法点击某个地方
- visual-studio-code - VSCode快捷方式选择两个括号/括号之间的代码块?
- java - Completable Future - 使用 Completable Future 我正在尝试来自两个不同文件的数据
- javascript - 打字稿中未捕获的参考错误(VS 2019)
- amazon-web-services - 无法在 AWS 控制台中找到数据库
- arrays - MongoDB 聚合填充/替换 ObjectId 数组
- python - Beautiful Soup 中 find_all 方法的返回类型是什么?