-
-
Save sandeepone/437186a2a5d47945d7c8220e8d337a4a to your computer and use it in GitHub Desktop.
Implement a cache and fetch with relay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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