| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import {
- Environment,
- Network,
- RecordSource,
- Store,
- QueryResponseCache,
- // Types
- CacheConfig,
- ObservableFromValue,
- GraphQLResponse,
- RequestParameters,
- FetchFunction,
- Variables,
- } from 'relay-runtime';
- // 100 cache entries, 300 seconds until cache is invalid.
- export const cache = new QueryResponseCache({size: 100, ttl: 300000});
- export const fetchQuery: FetchFunction = (
- operation: RequestParameters,
- variables: Variables,
- cacheConfig: CacheConfig
- ): ObservableFromValue<GraphQLResponse> => {
- const queryId: string = operation.name;
- const cachedData: GraphQLResponse = cache.get(queryId, variables);
- const forceLoad: boolean = cacheConfig && cacheConfig.force;
- if (!forceLoad && cachedData) {
- // Return promise to keep returns consistent
- return new Promise(resolve => resolve(cachedData));
- }
- return fetch('/api/graphql', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- query: operation.text,
- variables,
- }),
- }).then(response => {
- const json = response.json();
- json.then(obj => cache.set(queryId, variables, obj));
- return json;
- });
- };
- const environment: Environment = new Environment({
- network: Network.create(fetchQuery),
- store: new Store(new RecordSource()),
- });
- export default environment;
|