Skip to content

Instantly share code, notes, and snippets.

@ro-savage
Created February 12, 2019 10:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ro-savage/0855aaadb8a869cdf684693876d757a0 to your computer and use it in GitHub Desktop.
Save ro-savage/0855aaadb8a869cdf684693876d757a0 to your computer and use it in GitHub Desktop.
Implement a cache and fetch with relay
// This code is untested. It may new some minor modifications to work
import RelayQueryResponseCache from "relay-runtime/lib/RelayQueryResponseCache";
import {
Environment,
Network,
RecordSource,
Store,
Observable
} from "relay-runtime";
const source = new RecordSource();
const store = new Store(source);
const oneHour = 60 * 60 * 1000;
const cache = new RelayQueryResponseCache({ size: 250, ttl: oneHour });
const fetchFunction = async (operation, variables, cacheConfig, uploadables, sink) => {
const queryID = operation.text;
const isMutation = operation.operationKind === "mutation";
const isQuery = operation.operationKind === "query";
const forceFetch = cacheConfig && cacheConfig.force;
const fromCache = cache.get(queryID, variables);
if (isQuery && fromCache !== null && !forceFetch) {
// Return data from cache
// Then continue
sink.next(fromCache);
}
const res = await fetch("/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
query: operation.text,
variables
})
});
const data = await res.json();
if (isMutation && data.errors) {
sink.error(data);
sink.complete();
return;
}
// Set cache
if (isQuery && data) {
cache.set(queryID, variables, data);
}
// Clear cache on mutations
if (isMutation) {
cache.clear();
}
sink.next(data);
sink.complete();
};
const executeFunction = (request, variables, cacheConfig, uploadables) => {
return Observable.create(sink => {
fetchFunction(request, variables, cacheConfig, uploadables, sink);
});
};
const network = Network.create(executeFunction);
export const environment = new Environment({
network,
store
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment