What is GraphQL?

A query language which unifies the communication between client and server side. It allows the client side to describe exactly the data it needs, in a single request.

The most common approach across the web in the last few years has been the REST architectural style. However, this approach brings some limitations for high data demand applications. In a RESTful system, we need to make multiple HTTP requests to grab all the data we want, which has a significant performance impact. What if there was a way to request multiple resources in a single HTTP request?

What is a GraphQL schema?

For GraphQL to understand our requests we need to define a schema. And a GraphQL schema is nothing else than a group of queries and mutations. You can think of queries as resources to retrieve from the database and mutations as any kind of update to your database. We’ll create as an example a BlogPost and a Comment Mongoose model, and we will then create some queries and mutations for it. We won’t go into much detail here since mongoose isn’t the focus of this article. You can find the two models in models/blog-post.js and models/comment.js.

Like with Mongoose, in GraphQL we need to define our data structure. The difference is that we define for each query and mutation what type of data can enter and what is sent in the response. If these types don’t match, an error is thrown. Although it can seem redundant, since we’ve already defined a schema model in mongoose, it has great advantages, such as:

  1. You control what is allowed in, which improves your system security
  2. You control what is allowed out. This means you can define specific fields to never be allowed to be retrieved. For example: passwords or other sensitive data
  3. It filters invalid requests so that no further processing is taken, which can improve the server’s performance

You can find the source code for the GraphQL types in graphql/types/

Here, we’re defining the blog post output GraphQL type, which we’ll use further when creating the queries and mutations. Note how similar the structure is to the mongoose model BlogPost. It can seem duplication of work, but these are separated concerns. The mongoose model defines the data structure for the database, the GraphQL type defines a rule of what is accepted in a query or mutation to your server.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License