Query and transformation collocation in Apollo Client
GraphQL allows to query what you need and get exactly that. But what’s about the shape?
Does the following picture look familiar to you?
There are a lot of useless one-field wrapper objects which you have to manually unwrap in your component code.
We at APIs.guru decided to fix this problem by introducing the concept of query and transformation collocation. What does that mean? Look at the example bellow:
The idea is to specify the transformation of the result by using
@_ directives. That’s basically is what we call query and transformation collocation.
@_ directive you can use the majority of lodash transformations (that’s why the library is called GraphQL Lodash).
You can play with this in our demo: https://apis.guru/graphql-lodash/. You can find a few interesting examples there hidden under “Saved queries” dropdown.
Usage in production
This looks pretty impressive in the demo. But how to use it in production? First, we don’t think it should be used on the server as it will break the contract between server and client. That will definitely break all the client-side tools.
In terms of client-side usage, the two most popular GraphQL clients (Apollo Client and Relay) have caching layer which relies on the response structure. This requires transformation to be applied after the caching stage.
Usage with Apollo Client
Apollo Client is a fully-featured, production ready caching GraphQL client for every server or UI framework build with developer experience and simplicity in mind. That’s why it was quite easy to get GraphQL Lodash working with it.
For the sake of convenience, let’s write a simple wrapper function which we will use instead of original
graphql enhancer function from
This wrapper is pretty simple. It uses
graphqlLodash (line 5) to get
@_ directives) and
transform function from the original query. Wrapper returns another function which will be used to enhance components. Our enhancer just calls original
graphql component enhancer from
react-apollo passing it stripped query. So your server will receive just regular query without all those funky directives.
The main trick is using
props callback to apply transformations (line 13). Just in case it is needed, we still keep original non-transformed data by putting it into
Here is a simple component demonstrating this idea:
As you can see, our component receives already transformed data so there is no need to unwrap it manually.
Notice, that on the last line
MyComponent is enhanced with our
gqlLodash wrapper instead of original
You can play with the code on CodeSandbox bellow: