Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import ApolloClient, { ApolloQueryResult, OperationVariables } from 'apollo-client';
  2. import { DocumentNode } from 'graphql';
  3. import ObjectHash from 'object-hash';
  4.  
  5. interface IQueryCache<T> {
  6. fetch: Promise<void>;
  7. response?: ApolloQueryResult<T>;
  8. error?: any;
  9. }
  10.  
  11. const cache = new Map<string, IQueryCache<any>>();
  12.  
  13. export function gqlQuery<T, TVariables = OperationVariables>(client: ApolloClient<any>, query: DocumentNode, variables: TVariables) {
  14. const key = ObjectHash({query: query.definitions, variables});
  15.  
  16. let cached: IQueryCache<T> | undefined = cache.get(key);
  17.  
  18. if (cached) {
  19. if (cached.error) {
  20. cache.delete(key);
  21. throw cached.error; // error occurred
  22. }
  23. if (cached.response) {
  24. cache.delete(key);
  25. return cached.response as ApolloQueryResult<T>; // request was successful
  26. }
  27. throw cached.fetch;
  28. }
  29.  
  30. cached = {
  31. fetch: client.query<T, TVariables>({query, variables})
  32. .then((resp: ApolloQueryResult<T>) => resp)
  33. .then((resp: ApolloQueryResult<T>) => {
  34. if (cached) {
  35. cached.response = resp;
  36. }
  37. })
  38. .catch((e: any) => {
  39. if (cached) {
  40. cached.error = e;
  41. }
  42. }),
  43. };
  44.  
  45. cache.set(key, cached);
  46.  
  47. throw cached.fetch;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement