graphqlEnvironment.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. const query = operation.text.replace(/\s+/g, ' ');
  31. return fetch('/api/graphql', {
  32. credentials: 'same-origin',
  33. method: 'POST',
  34. headers: {
  35. 'Content-Type': 'application/json',
  36. ...csrf.headers,
  37. },
  38. body: JSON.stringify({
  39. query,
  40. variables,
  41. }),
  42. }).then(response => {
  43. const json = response.json();
  44. json.then(obj => cache.set(queryId, variables, obj));
  45. return json;
  46. });
  47. };
  48. const environment: Environment = new Environment({
  49. network: Network.create(fetchQuery),
  50. store: new Store(new RecordSource()),
  51. });
  52. export default environment;