| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- import {
- Environment,
- Network,
- RecordSource,
- Store,
- QueryResponseCache,
- // Types
- CacheConfig,
- ObservableFromValue,
- FetchFunction,
- QueryPayload,
- RequestNode,
- Variables,
- } from 'relay-runtime';
- // 100 cache entries, 300 seconds until cache is invalid.
- const cache = new QueryResponseCache({size: 100, ttl: 300000});
- export const fetchQuery: FetchFunction = (
- operation: RequestNode,
- variables: Variables,
- cacheConfig: CacheConfig
- ): ObservableFromValue<QueryPayload> => {
- const queryId: string = operation.name;
- const cachedData: QueryPayload = cache.get(queryId, variables);
- const forceLoad: boolean = cacheConfig && cacheConfig.force;
- if (!forceLoad && cachedData) {
- return 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;
|