- So what’s this GraphQL thing I keep hearing about?
- Originally written by Sacha Greif
- The Nuggets translation Project
- Translator: lsvih
- Proofreader: Xiaoyusilen, Steinliber
What exactly is GraphQL that I always hear about?
When you hear about a new technology, you probably have the same three reactions I do:
1. Abandon
Another JavaScript library? I’ll just use JQuery anyway.
2. Interested in
Well, maybe I should check out this new library I’ve been hearing about.
3. The panic
Help! I have to learn this new library right away or I’ll be out of the game!
The way to stay sane in this fast-moving world is to learn something new with a second or third attitude, stay ahead of the curve and stay interested.
So now is the perfect time to learn about GraphQL, something you hear people talking about all the time!
basis
Simply put, GraphQL is a syntax that describes a method of requesting data, typically used by clients to load data from a server. GraphQL has the following three main features:
- It allows the client to specify exactly what data is required.
- It makes it easier to aggregate data from multiple sources.
- It uses a type system to describe data.
How to get started with GraphQL? How does it work in practice? How do you get started? To find out, read on!
Problems encountered
GraphQL was developed by Facebook to solve the data request problem of their huge, old architecture. But even apps that are much smaller than Facebook face some of the limitations of traditional REST apis.
For example, suppose you want to display a list of posts, and at the bottom of each post display a list of likes, including the user name and avatar. This requirement can be easily solved by simply adjusting your Posts API request to embed a list of likes including user objects, as shown below:
But now that you’re developing a mobile app, loading all that data obviously slows your app down. So you have to request two apis, one that contains the likes and one that doesn’t (just the article information).
Now let’s throw in another case: posts data is stored by the MySQL database, while likes data is stored by Redis. What do you do now?
Consider how many data sources and apis Facebook clients have to manage following this script, and you can see why good REST apis are currently being evaluated for their limitations.
Solution
Facebook came up with a conceptually simple solution: Instead of using multiple “stupid” nodes, a single “smart” node would perform complex queries and send data back as requested by the client.
Essentially, the GraphQL layer sits between the client and one or more data sources. It receives requests from the client and then pulls out the data you want based on your setup. Still don’t get it? Let’s use an analogy!
The REST model was like ordering a pizza, then having the convenience store deliver groceries, and then calling the dry cleaner to pick up your clothes. There are three stores, so you have to call three times.
GraphQL is in some ways like a personal assistant: you just give it the addresses of the three stores, tell it simply what you need (” Pick up my dry cleaner’s clothes and a large pizza and two eggs “), and sit back and wait for it to come back.
In other words, In order for you to communicate with this amazing personal assistant, GraphQL has built a standard language.
The photo above is from Google Images, and some personal assistants even have eight arms.
Theoretically, a GraphQL API consists of three parts: schema (types), queries (queries), and resolvers (resolvers).
Queries
The request you make to your GraphQL personal assistant is a query, which looks like this:
query {
stuff
}Copy the code
Here, we define a new query with the query keyword that will fetch the field called Stuff. The best part about GraphQL Queries is that they support multiple field nested Queries. We can go one level further:
query{
stuff {
eggs
shirt
pizza
}
}Copy the code
As you can see, the client does not need to care which “store” the data comes from when querying. You just need to request the data you want, and the GraphQL server will do all the rest.
It is also worth noting that the Query field can also point to an array. For example, here is a common pattern for querying a list of articles:
query {
posts { # this is an array
title
body
author { # we can go deeper!
name
avatarUrl
profileUrl
}
}
}Copy the code
The Query field also supports parameters. If I want to show a particular article, I can put the ID argument in the POST field:
query {
post(id: "123foo"){
title
body
author{
name
avatarUrl
profileUrl
}
}
}Copy the code
Finally, if I wanted the ID parameter to change dynamically, I could define a variable and reuse it in the Query field. (Note that we also define the variable name once in the query field.)
query getMyPost($id: String) {
post(id: $id){
title
body
author{
name
avatarUrl
profileUrl
}
}
}Copy the code
A good way to practice these methods is to use GitHub’s GraphQL API Explorer. For example, you could try the following query:
query {
repository(owner: "graphql".name: "graphql-js"){
name
description
}
}Copy the code
GraphQL autocomplete feature
When you try to enter a new field name called description below, you may notice that the IDE auto-completes the optional field name according to the GraphQL API. That’s great!
The Anatomy of a GraphQL Query
Read the excellent article Anatomy of a GraphQL Query to learn more about GraphQL queries.
Interpreters (Resolvers)
Even the best PA in the world can’t pick up the dry cleaning unless you give them an address.
Similarly, the GraphQL server doesn’t know what to do with an incoming query unless you use resolver to tell it.
A resolver tells GraphQL where and how to fetch the data for the corresponding field. For example, here’s the resolver from which we fetched the POST example earlier (using Apollo’s GraphQL-Tools) :
Query: {
post(root, args) {
return Posts.find({ id: args.id }); }}Copy the code
In this example, we put the resolver in the Query because we want to Query the POST directly at the root level. But you can also put resolvers in subfields, such as the query post author field, as follows:
Query: {
post(root, args) {
return Posts.find({ id: args.id }); }},Post: {
author(post) {
return Users.find({ id: post.authorId})
}
}Copy the code
Also, resolver doesn’t just return the contents of the database. For example, if you want to add a commentsCount attribute to your Post types, you can do so:
Post: {
author(post) {
return Users.find({ id: post.authorId})
},
commentsCount(post) {
return Comments.find({ postId: post.id}).count()
}
}Copy the code
The key thing to understand here is that with GraphQL, your API structure is decoupled from your database structure. To put it another way, the author and commentsCount fields probably don’t exist in our database at all, but we can “simulate” them with the power of Resolver.
As you can see, we can write whatever code you want in resolver. Therefore, you can arbitrarily modify the contents of a database by changing a resolver, a form also known as mutation resolver.
Type (Schema)
GraphQL’s type structure system makes a lot of things possible. My goal today is just to give you a quick overview rather than a detailed introduction, so I won’t go any further on that.
That being said, if you want to learn more about this, I recommend reading the official GraphQL documentation.
Q&A
Let’s pause and answer some common questions.
You definitely want to ask some questions, go ahead, don’t be shy!
How does GraphQL relate to a graphics database?
They really don’t matter, GraphQL has nothing to do with a graphics database like Neo4j. The “Graph” in the name comes from GraphQL using fields and subfields to traverse your API Graph; “QL” means “Query language”.
I’m happy with REST. Why did I switch to GraphQL?
If you haven’t hit the pain points GraphQL solves with REST, that’s a good thing!
But using GraphQL instead of REST has little impact on the user experience of your app, so switching isn’t a “life or death” decision. Having said that, I recommend that you try GraphQL on a small scale in your project if you get the chance.
Can I use GraphQL if I don’t use frameworks like React, Relay, etc?
Of course can! Because GraphQL is just a standard, you can use it on any platform, in any framework, and even in the client (Apollo has GraphQL clients for Web, iOS, Angular, and so on, for example). You can also make your own GraphQL server.
GraphQL was made by Facebook, but I don’t trust Facebook
Again, GraphQL is just a standard, which means you can implement GraphQL without a line of Code from Facebook.
Also, having Facebook support is a good thing for the GraphQL ecosystem. In this regard, I believe the GraphQL community is thriving enough that GraphQL will continue to thrive even if Facebook stops using it.
The whole “let the client request the data it needs” thing doesn’t sound very secure…
You’ll have to write your own resolver, so whether security issues arise at this level is entirely up to you.
For example, to prevent a DDOS attack when a client requests records over and over again, you can have the client specify a limit parameter to control how much data it accepts.
So how do I get started with GraphQL?
In general, a GraphQL-driven app requires at least two components:
- A GraphQL server to service your API.
- A GraphQL client to connect your nodes.
Read on to learn more about the tools available.
Now that you have a good idea of GraphQL, let’s take a look at the main platforms and products for GraphQL.
GraphQL server
Great oaks from little acorns grow, and the first brick in the building was a GraphQL server. GraphQL itself is just a standard, so it’s open to a wide variety of implementations.
GraphQL-JS (Node)
It was the original implementation of GraphQL. You can use it with Express-GraphQL to create your own API service.
GraphQL-Server (Node)
The Apollo team also has their own one-stop GraphQL server-side implementation. It’s not as widely used as GraphQL-JS, but its documentation and support are great, and you can make rapid progress with it.
Other platforms
GraphQL.org lists a list of GraphQL implementations on other platforms (PHP, Ruby, etc.).
GraphQL client
While you can query the GraphQL API just fine without using the client library, a corresponding client library will make your development a lot easier.
Relay
Relay is Facebook’s GraphQL tool. I haven’t used it yet, but I’ve heard that it’s largely tailored to Facebook’s own needs and may not be user-friendly to most users.
Apollo Client
The latest entrant in this field is Apollo, which is growing rapidly. A typical Apollo client stack consists of the following two parts:
- Apollo-client, which lets you run GraphQL queries in your browser and store data. (It also has its own developer plugin).
- Connectors to the front-end frameworks you use (e.g. React-apollo, Angular-Apollo, etc.).
In addition, Apollo clients use Redux to store data by default. That’s great, because Redux itself is a great state-management library with a rich ecosystem.
Apollo plugin for Chrome developer Tools
Open source App
While GraphQL is still new, it is already being used by a number of open source apps.
VulcanJS
First of all I should say that I am the main maintainer of VulcanJS. I created VulcanJS so that people can take full advantage of the React/GraphQL stack without having to write too much boilerplate code. Think of it as “Rails for the modern Web ecosystem,” allowing you to build your CRUD app in just a few hours. (Instagram Clone, for example)
Gatsby
Gatsby is a React static website generator that is currently based on GraphQL version 1.0. It looks like a strange chowder at first glance, but it’s actually quite powerful. In the construction process of Gatsby, data can be obtained from multiple GraphQL apis and then used to create a fully static React app without a back end.
Other GraphQL tools
GraphiQL
GraphiQL is a great browser-based IDE that makes it easy for you to do GraphQL endpoint queries.
GraphiQL
DataLoader
Since GraphQL queries are typically nested, a single query may invoke many database requests. To avoid performance impact, you can use some batch import/export frameworks and cache libraries, such as DataLoader developed by Facebook.
Create GraphQL Server
Create GraphQL Server is a simple command line tool that allows you to quickly build GraphQL servers based on Node Server and Mongo database.
GraphQL service
Finally, here’s a list of GraphQL BAAS companies that have everything ready for you on the server side. This might be a good way to give the GraphQL ecosystem a try.
GraphCool
A flexible back-end platform service made up of GraphQL and AWS Lambda that offers a developer free plan.
Scaphold
Another GraphQL BAAS platform, which also offers free plans. It offers more functionality than GraphCool. (such as custom user roles, callback hooks for general operations, etc.)
Here are some resources to help you learn GraphQL.
GraphQL.org
The official website of GraphQL has a lot of great documentation for you to learn.
LearnGraphQL
LearnGraphQL is a course co-produced by Kadira staff.
LearnApollo
LearnApollo is a free course created by GraphCool that is a great addition to LearnGraphQL.
Apollo blog
Apollo’s blog has tons of dry stuff, lots of great articles about Apollo and GraphQL.
GraphQL weekly
A newsletter curated by the Graphcool team that includes any information about GraphQL.
Hashbang weekly
Another good briefing, in addition to GraphQL, also covers React, Meteor.
Awesome GraphQL
A comprehensive listing of links and resources for GraphQL.
How do you put GraphQL into practice? Here are some ways you can try:
Apollo + Graphcool + Next.js
If you’re familiar with next.js and React, this example will help you quickly set up your GraphQL endpoint using Graphcool and perform queries using Apollo on the client side.
VulcanJS
The Vulcan tutorial will walk you through creating a simple GraphQL data layer with both a server and client part. Since Vulcan is a one-stop platform, this no-configuration approach is a great way to get started. If you need help, visit our Slack column!
GraphQL & React tutorial
The Chroma blog has a six-part tutorial on how to build a React/GraphQL app using component-driven development.
conclusion
When you first get to GraphQL, it might seem very complicated, because it spans so many areas of modern software development. But if you take a little time to understand how it works, I think you can find a lot of good things about it.
So whether you end up using it or not, I believe it’s worth learning more about GraphQL. More and more companies and frameworks are embracing it, and in a few years it may become another important part of Web development.
Agree with? Don’t agree with? Have any questions? Leave a comment and let us know what you think. If you still like this article, please go to 💚 or share it with someone else.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. Android, iOS, React, front end, back end, product, design, etc. Keep an eye on the Nuggets Translation project for more quality translations.