graphqlEnvironment.ts 1.4 KB

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