Skip to content

Instantly share code, notes, and snippets.

@lydemann
Created March 7, 2021 11:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lydemann/2ba4efb4102756ac7ff1f7c14c805e7f to your computer and use it in GitHub Desktop.
Save lydemann/2ba4efb4102756ac7ff1f7c14c805e7f to your computer and use it in GitHub Desktop.
graphql-helpers.ts
import { ApolloCache } from '@apollo/client/core';
import { DocumentNode } from 'graphql';
export interface EntityObject {
id: string;
}
export function createInCache<ReadQueryResponseT>(
toCreate: EntityObject,
readQuery: DocumentNode,
cache: ApolloCache<any>,
entityName: keyof ReadQueryResponseT
) {
const existingEntities = cache.readQuery<
Record<keyof ReadQueryResponseT, EntityObject[]>
>({
query: readQuery,
});
if (toCreate && existingEntities) {
cache.writeQuery({
query: readQuery,
data: {
[entityName]: [...existingEntities[entityName], toCreate],
},
});
}
}
export function removeFromCache<ReadQueryResponseT>(
toRemove: EntityObject,
readQuery: DocumentNode,
cache: ApolloCache<any>,
entityName: keyof ReadQueryResponseT
) {
const existingEntities = cache.readQuery<
Record<keyof ReadQueryResponseT, EntityObject[]>
>({
query: readQuery,
});
if (toRemove && existingEntities) {
cache.writeQuery({
query: readQuery,
data: {
[entityName]: existingEntities[entityName].filter(
(entity) => entity.id !== toRemove.id
),
},
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment