graphqlEnvironment.ts 1.2 KB

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