Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ApolloClient, { ApolloQueryResult, OperationVariables } from 'apollo-client';
- import { DocumentNode } from 'graphql';
- import ObjectHash from 'object-hash';
- interface IQueryCache<T> {
- fetch: Promise<void>;
- response?: ApolloQueryResult<T>;
- error?: any;
- }
- const cache = new Map<string, IQueryCache<any>>();
- export function gqlQuery<T, TVariables = OperationVariables>(client: ApolloClient<any>, query: DocumentNode, variables: TVariables) {
- const key = ObjectHash({query: query.definitions, variables});
- let cached: IQueryCache<T> | undefined = cache.get(key);
- if (cached) {
- if (cached.error) {
- cache.delete(key);
- throw cached.error; // error occurred
- }
- if (cached.response) {
- cache.delete(key);
- return cached.response as ApolloQueryResult<T>; // request was successful
- }
- throw cached.fetch;
- }
- cached = {
- fetch: client.query<T, TVariables>({query, variables})
- .then((resp: ApolloQueryResult<T>) => resp)
- .then((resp: ApolloQueryResult<T>) => {
- if (cached) {
- cached.response = resp;
- }
- })
- .catch((e: any) => {
- if (cached) {
- cached.error = e;
- }
- }),
- };
- cache.set(key, cached);
- throw cached.fetch;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement