Currently, I am utilizing apollo codgen to automatically generate types for my graphql queries in TypeScript. However, I have noticed that the generated types contain numerous instances of null
values, leading to an abundance of if
checks throughout my code. Is this typical practice when working with graphql cache updates in TypeScript?
this.props.mutate({
variables,
update: (proxy, { data }) => {
// Having to handle null values at every step
if (!data || !data.createContact || !data.createContact.contact) return;
let newContactEdge = {
node: { ...data.createContact.contact, __typename: 'Contact' },
__typename: 'ContactEdge',
};
// Reading from cache
let listCache = proxy.readQuery<ListContactsQuery>({ query: ChatAPI.queries.listContacts });
// Dealing with more null values
if (listCache && listCache.contacts && listCache.contacts.edges) {
proxy.writeQuery({
query: ChatAPI.queries.listContacts,
data: {
...listCache,
contacts: {
...listCache.contacts,
edges: [newContactEdge, ...listCache.contacts.edges],
},
},
});
}
},
})
This approach feels cumbersome as previously, checking if cache
was not null ensured that the data would be accessible without descending into nested null checks.
Below are the generated types for the 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 {
/**
* Retrieves all contacts for the current user
*/
contacts: ListContactsQuery_contacts;
}