Ferry provides the following methods for reading and writing data to the cache:
These methods are described in detail below.
All code samples below assume that you have initialized an instance of
readQuery method enables you to run a GraphQL query directly on your cache.
If your cache contains all of the data necessary to fulfill a specified query,
readQueryreturns a data object in the shape of that query, just like a GraphQL server does.
If your cache doesn't contain all of the data necessary to fulfill a specified query,
readQueryreturns null. It never attempts to fetch data from a remote server.
Let's assume we've created the following
reviews.graphql file and generated our GraphQL classes.
We can then read our Query like so:
You can provide GraphQL variables to
readQuery like so:
readFragment method enables you to read data from any normalized cache object that was stored as part of any query result. Unlike with
readQuery, calls to
readFragment do not need to conform to the structure of one of your data graph's supported queries.
For example, if we have the following
We could read the generated fragment like so:
idFields argument is the set of unique identifiers and their values for the object you want to read from the cache. By default, this is the value of the object's
id field, but you can customize this behavior.
In the example above:
- If a
Reviewobject with an
123is not in the cache,
- If the
Reviewobject is in the cache but it's missing either a
In addition to reading arbitrary data from the cache, you can write arbitrary data to the cache with the
Any changes you make to cached data with
writeFragment are not pushed to your GraphQL server.
These methods have the same signature as their
read counterparts, except they require an additional
For example, the following call to
writeFragment locally updates the
Review object with an
operationRequest streams that are listening to this data will be updated accordingly.
Combining reads and writes
writeQuery to fetch currently cached data and make selective modifications to it.
Since Ferry's generated classes are based on
built_value, we can easily create modified copies of them using the
rebuild method. Check out this post to learn more about
The example below updates the star rating for the cached
Review. Remember, this addition is not sent to your remote server.