Skip to content

Instantly share code, notes, and snippets.

@lucasconstantino
Created March 29, 2017 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasconstantino/7e355022df9e68d3dce20d17ac3fcf92 to your computer and use it in GitHub Desktop.
Save lucasconstantino/7e355022df9e68d3dce20d17ac3fcf92 to your computer and use it in GitHub Desktop.

Title options:

  • GraphQL hoje para aplicações client-side que ainda dependem de APIs REST.
  • GraphQL today using Apollo for applications that still depend on REST apis
  • Wrapping REST apis with GraphQL using Apollo stack

GraphQL today using Apollo for applications that still depend on REST APIs

Even though people using GraphQL are often extremely excited about the technology, it's popularity is still growing slowly. Developers working on client-side applications are the ones to benefit the most from GraphQL, but migrating a backend from a working REST API might not be economically justifiable for most teams. What most don't realize, though, is that it is not completely necessary to make the switch on both sides before adopting the technology. The main JavaScript implementation of a GraphQL server runs just fine on the browser, and Apollo makes it easy as cake to start using it today.

If you plan to use Relay to achieve the same goal, you should definitely check this post on the official GraphQL blog.

Who/what is Apollo?

GraphQL is ultimately only a protocol, meaning there are dozens of projects for both client and server side implementations of it. Apollo, in the other hand, is a suite of open-source tools & products built by (very nice folks at) the Meteor Development Group.

Among these projects, there is graphql-tools, which facilitates the creation of a executable schema, and apollo-client, which presents itself as "The fully-featured, production ready caching GraphQL client for every server or UI framework". Quite bold, huh?

Resolving GraphQL in the browser

The first problem to be solved here is how to run a GraphQL server/resolver in the client-side. To be honest, it is not much of a problem really. As I said before, the main JavaScript implementation of GraphQL works in the browser, and all we have to do is use it as we would in a Node server. So let's go on with it.

Installation

We are going to need two schema building tools:

https://gist.github.com/2528ae10bcd405a2952f59ece2368764

Missing NPM in the command? You should definitely give Yarn a try ;)

Building the GraphQL Schema

First things first. Building a schema is rather easy with graphql-tools. You start by defining a schema using the GraphQL schema language as follows:

https://gist.github.com/92934a82d706a16f447224746529702e

What we are saying here is that our schema has a single type called Query and that this is the root query type, meaning it's fields are queryable at the top level of the schema - in this case, the helloWorld field, which resolves to a string.

Then you define resolvers as a nested object that maps type and field names to resolver functions:

https://gist.github.com/35979d380b409d1a0e769ff4476d4bae

More info on graphql-tools resolver maps can be found on this guide.

Finally, you combine the type definitions and the resolvers into an executable schema using makeExecutableSchema helper:

https://gist.github.com/a38680914b88d4a705bedd428113912b

Apollo has a documentation section on modularizing the schema, and I've also worked on the subject and created a project which might be useful, though it is in early stages: graphql-modules. During this tutorial, though, we'll have only one file to keep things simple.

Executing queries

After we've managed to create an executable schema, we can resolve queries against it using the official graphql-js project as follows:

https://gist.github.com/aaadc41a32944128339d4100a34dfe1b

Done! We can resolve GraphQL. The code so far can be bundled using webpack or whatever tool you use to build your code to be executed in the browser, and it will work just fine.

I've created a repository to serve as code reference for this post. It's available on GitHub, it has a ready to use building system and node server for you to try the code presented here. Checkout the tag 1-hello-world to see this check point.

Resolving using REST API calls

Now that you have a way to resolve GraphQL queries in the browser, we can move forward and add a more advanced schema, with resolvers that map to REST requests.

To keep up with simplicity, I'll use an online fake REST API called JSONPlaceholder. It has a rough blog schema, with posts, users, comments, etc, which is just perfect for our use case.

First of all, let's update our schema to define these new types:

https://gist.github.com/96867b62c7f8e914fa8af1af54d55a76

Now, we'll update the resolver map as follows:

https://gist.github.com/fae76ac7b2d8b9a9d7d5ac68eb130b4c

Note that to fetch REST endpoints we are using Fetch API. You can polyfill it if you need with whatwg-fetch, but it is already available on all major browsers.

No we can query posts:

https://gist.github.com/ee542e670ed503398443b8a1c35b4346

Checkpoint: checkout to tag 2-rest-resolvers on the code reference repo to try this out on your browser.

Ok, that's pretty cool. What if we wanted to get a single post from the API, though? Well, easy enough. Here is how we could make a query for the post with id 1:

https://gist.github.com/acc55408767b37fbc04db658d14dc8e0

Now, having a look at our mocked API for posts, we can see that it returns yet a fourth property on each post object: the userId. That's a good time for...

Resolving relations

Relations in GraphQL are simply more resolvers, as I expect you already know. Follow up as we add the Post's author field to the schema, as well as the User's posts field, together with their resolvers:

https://gist.github.com/edfc17abf33ac580af0d5ff9ea17ea1a

To remember what function parameters we are using this relation resolvers, have a look at the resolver function signature.

Ok, things are becoming really interesting. Now we can make GraphQL work it's magic, doing crazy stuff such as "grabbing the posts with the same author as post 1":

https://gist.github.com/4d6cee69fedffd19936ef179313fc8f7

Oooh, that's truly amazing! I'll just take break for a coffee and contemplate such good work we've accomplished so far...

Meanwhile, another checkpoint for you to run: 3-relationship-resolvers.

Now, mutations!

Mutations in GraphQL are just more field resolvers, only with some additional behavior. Having that said, to create addPost mutation we will basically create a resolver that fetches using the HTTP method POST as follows:

https://gist.github.com/4e7a51086cbc0bac564f7b59a295c8b8

Side note about the code above: our mocked API accepts POST requests, but returns only the supposedly generated id in the response, nothing more.

Our mutation queries then have to be identified as such:

https://gist.github.com/34749e5894e156f3c8fe903d2535c772

One more checkpoint and we're done: 4-mutation-resolvers.

Apollo Client

Ok, I know that running a static query stored in a variable in the index.js of our application isn't going to be enough for long. The next step is integrating what we already have with Apollo Client ("The fully-featured, production ready caching GraphQL client for every server or UI framework". Again: long description, not modest, but quite accurate).

Installation

https://gist.github.com/a3e09f95ba4e184cfbcc9eabc1603f96

Creating the client

To create an Apollo Client instance you must instantiate the ApolloClient class with a configuration object containing, at least, the network interface which the client will use to make GraphQL requests. Usually, in a front-end/back-end application this means using the included helper createNetworkInterface, which would basically send POST requests to a backend on the same domain of the running application. It looks pretty much like this:

https://gist.github.com/a86a1071c879e0c3df2a3b5267690288

And, to perform a query, something like this:

https://gist.github.com/4472983f136d871f67a8009ff7ea4621

If you are interested, you can find out more on the Network layer of the Apollo Client.

The code above would be just fine if we had a backend serving GraphQL - which we don't. Good enough we've being building our own wrap around the REST API just earlier in this post. What we now have to do is make ApolloClient use the GraphQL schema and resolver as were we doing before:

https://gist.github.com/a550d59c188b9403414d29d8b1a11262

Ok, what the heck is going on here?

First, we are instantiating ApolloClient with a completely custom networkInterface. It consists of an object with the single required method query, which will be called by the client to resolve queries. This method will receive a single argument; an ApolloClient Request Interface.

Second, we use an available helper, printAST, to process this request object back into a valid GraphQL query string (much similar to the ones we were statically using before).

Third, we extract other import things from this request object, such as an operationName and possible variables to provide the resolver with.

Last but not least, we run the query against the schema as have we done before, providing it with the schema, the query, the initial root, a context (null here, for we don't need it yet), the variables, and the operation name, in that exact arguments order. Most of the arguments are not mandatory, as we've seen this same function be executed with only the first two just a few words back in this post.

If you have any question about the query execution part, have a look at GraphQL's official documentation on query execution.

We can now use the client as we normally would:

https://gist.github.com/8cb67cd5d9965bc6a12865fbec650904

Time for the final checkpoint: 5-apollo-client.

Conclusion

This is pretty much it. I hope you all found your way in this wandering of GraphQL learning, and above all, I hope you are now able to start using GraphQL today, no more excuses allowed.

Post credit scene

Ok, if you are really just starting with GraphQL you might not even know what to do with this ApolloClient we've ended up with. Our index.js is still just resolving a single query. My bad. I understand that if you are here, you probably do already use React, Angular, or even Vue (but only if you are a true hipster). If that's the case, here are the libraries you are looking for:

See ya!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment