|
@@ -1,6 +1,35 @@
|
|
|
-import {Environment, Network, RecordSource, Store} from 'relay-runtime';
|
|
|
|
|
|
|
+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;
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
-function fetchQuery(operation, variables): Promise<void> {
|
|
|
|
|
return fetch('/api/graphql', {
|
|
return fetch('/api/graphql', {
|
|
|
method: 'POST',
|
|
method: 'POST',
|
|
|
headers: {
|
|
headers: {
|
|
@@ -10,10 +39,15 @@ function fetchQuery(operation, variables): Promise<void> {
|
|
|
query: operation.text,
|
|
query: operation.text,
|
|
|
variables,
|
|
variables,
|
|
|
}),
|
|
}),
|
|
|
- }).then((response): Promise<void> => response.json());
|
|
|
|
|
-}
|
|
|
|
|
|
|
+ }).then(response => {
|
|
|
|
|
+ const json = response.json();
|
|
|
|
|
+ json.then(obj => cache.set(queryId, variables, obj));
|
|
|
|
|
+
|
|
|
|
|
+ return json;
|
|
|
|
|
+ });
|
|
|
|
|
+};
|
|
|
|
|
|
|
|
-const environment = new Environment({
|
|
|
|
|
|
|
+const environment: Environment = new Environment({
|
|
|
network: Network.create(fetchQuery),
|
|
network: Network.create(fetchQuery),
|
|
|
store: new Store(new RecordSource()),
|
|
store: new Store(new RecordSource()),
|
|
|
});
|
|
});
|