graphqlEnvironment.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import {
  2. Environment,
  3. Network,
  4. RecordSource,
  5. Store,
  6. QueryResponseCache,
  7. // Types
  8. CacheConfig,
  9. ObservableFromValue,
  10. GraphQLResponse,
  11. RequestParameters,
  12. FetchFunction,
  13. Variables,
  14. } from 'relay-runtime';
  15. // 100 cache entries, 300 seconds until cache is invalid.
  16. export const cache = new QueryResponseCache({size: 100, ttl: 300000});
  17. export const fetchQuery: FetchFunction = (
  18. operation: RequestParameters,
  19. variables: Variables,
  20. cacheConfig: CacheConfig
  21. ): ObservableFromValue<GraphQLResponse> => {
  22. const queryId: string = operation.name;
  23. const cachedData: GraphQLResponse = cache.get(queryId, variables);
  24. const forceLoad: boolean = cacheConfig && cacheConfig.force;
  25. if (!forceLoad && cachedData) {
  26. // Return promise to keep returns consistent
  27. return new Promise(resolve => resolve(cachedData));
  28. }
  29. return fetch('/api/graphql', {
  30. method: 'POST',
  31. headers: {
  32. 'Content-Type': 'application/json',
  33. },
  34. body: JSON.stringify({
  35. query: operation.text,
  36. variables,
  37. }),
  38. }).then(response => {
  39. const json = response.json();
  40. json.then(obj => cache.set(queryId, variables, obj));
  41. return json;
  42. });
  43. };
  44. const environment: Environment = new Environment({
  45. network: Network.create(fetchQuery),
  46. store: new Store(new RecordSource()),
  47. });
  48. export default environment;