📜 ⬆️ ⬇️

What is this GraphQL?

I offer you the translation of the article by Sacha Greif "What is this GraphQL?"


If you are the same as me, you usually go through three stages when you learn about a new technology:



There is one trick to maintaining prudence in the era of rapidly developing technologies: to study new things between the second and third stages, as soon as the interest is affected, but so far the technology is not yet widespread.


That is why now is the time to find out what this GraphQL is, about which you hear everywhere.


The basics


In a nutshell, GraphQL is a syntax that describes how to request data , and is mainly used by the client to download data from the server. GraphQL has three main characteristics:



So how do you start learning GraphQL? How does it look in practice? How to start using it? Read on to find out!


Origin


Task


GraphQL was developed in a big old Facebook, but even much simpler applications may face the limitations of traditional REST APIs.


For example, imagine that you need to display a list of ( posts ), and under each post a list of , including user names and avatars. In fact, it is not difficult, you just change the posts API to contain an likes array, which will contain user objects.



But then, when developing a mobile application, it turned out that due to the loading of additional data, the application runs slower. So now you need two endpoint, one that returns records with likes, and the other without them.


Add another factor: it turns out, the records are stored in the MySQL database, and the likes in Redis! What to do now?!


Extrapolate this script to the many data sources and client APIs that Facebook deals with, and you will understand why the good old REST API has reached its limit.


Decision


Facebook has come up with a conceptually simple solution: instead of having a lot of "stupid" endpoint, it is better to have one "smart" endpoint that will be able to work with complex queries and give the data the form that the client requests.


In fact, the GraphQL layer is between the client and one or more data sources; it accepts customer requests and returns the necessary data in accordance with the transmitted instructions. Confused? Time metaphors!


Using the old REST model is like ordering a pizza, then ordering food delivery, and then calling the dry cleaner to pick up clothes. Three shops - three phone calls.



GraphQL is like a personal assistant: you can give him the addresses of all three places, and then just ask for what you need (“bring me my clothes, a big pizza and two dozen eggs”) and wait for them.



In other words, GraphQL is the standard language for talking with this magical personal assistant.



According to Google Images, a typical personal assistant is an alien with eight hands.


Components


In practice, GraphQL API is built on three main building blocks: on the schema (schema), queries (queries) and resolvers (resolvers).


Queries


(query and request are equally translated as “request.” In the following, query will be implied, unless stated otherwise - comment. ln.)


When you ask your personal assistant for something, you fulfill the request . It looks like this:


 query { stuff } 

We declare a new query using the query keyword, also asking about the stuff field. The great thing about GraphQL queries is that they support nested fields, so that we can go one level deeper:


 query { stuff { eggs shirt pizza } } 

As you can see, the client does not need to know where the data comes from when forming the request. He just asks about them, and the GraphQL server takes care of the rest.


It is also worth noting that the request fields can be arrays . For example, here’s a generic message list query template:


 query { posts { #   title body author { #     name avatarUrl profileUrl } } } 

Query fields can also contain arguments. For example, if you want to display a specific post, you can add an id argument to the post field:


 query { post(id: "123foo"){ title body author{ name avatarUrl profileUrl } } } 

Finally, if you want to make the id argument dynamic, you can define a variable and then use it in the query (note, we also made the query named ):


 query getMyPost($id: String) { post(id: $id){ title body author{ name avatarUrl profileUrl } } } 

A good way to try all this in practice is to use the Graphit API Explorer from GitHub. For example, let's try the following query:


 query { repository(owner: "graphql", name: "graphql-js"){ name description } } 


GraphQL and autocompletion in action


Note that when you enter a field name, the IDE automatically suggests you possible field names, obtained using the GraphQL API. Dexterously!



Anatomy of GraphQL Queries (English)


You can learn more about GraphQL queries in the excellent article "Anatomy of GraphQL Queries" (eng) .


Resolvers


Even the best personal assistant in the world will not be able to bring your items from the dry cleaner unless you give him an address.


Similarly, the GraphQL server cannot know what to do with an incoming request if it is not explained to it using a resolver .


Using GraphQL recognizer understands how and where to get the data corresponding to the requested field. For example, a recognizer for a record field might look like this (using a schema generator from the Apollo GraphQL-Tools set ):


 Query: { post(root, args) { return Posts.find({ id: args.id }); } } 

We place our resolver in the Query section because we want to receive a ( post ) in the root of the response. But we can also create resolvers for subfields, such as for the author field:


 Query: { post(root, args) { return Posts.find({ id: args.id }); } }, Post: { author(post) { return Users.find({ id: post.authorId}) } } 

Please note that your discriminators are not limited in the number of returned objects. For example, you want to add the commentsCount field to the Post object:


 Post: { author(post) { return Users.find({ id: post.authorId}) }, commentsCount(post) { return Comments.find({ postId: post.id}).count() } } 

The key concept here is that the GraphQL query schema and the structure of your database are in no way connected . In other words, the author or commentsCount fields may not exist in the database, but we can "simulate" them thanks to the power of the resolvers.


As shown above, you can write any code inside the recognizer. So you can change the contents of the database; such recognizers are called mutations .


Schema


All this is made possible by the GraphQL typed data scheme. The purpose of this article is to give a brief overview rather than an exhaustive introduction, so there will not be details in this section.


I urge you to look into the GraphQL documentation if you want to learn more.



Frequently asked Questions


Let's take a break to answer a few general questions.


Hey, you are in the back row. Yes you. I see you want to ask something. Go ahead, do not be shy!


What do graphQL and graph databases have in common?


Nothing in common. In fact, GraphQL has nothing to do with graph databases of type Neo4j . The “Graph” part reflects the idea of ​​getting content by going through the API graph using fields and subfields; The part "QL" is decrypted as "query language" - "query language".


I am completely satisfied with REST, why should I switch to GraphQL?


If you have not reached the pain points of the REST API, the solution of which is GraphQL, then do not worry.


Using GraphQL on top of REST most likely will not force you to make any complex changes to the rest of the API and break the accumulated user experience, so the transition will not be a matter of life and death in any case. So it is definitely worth trying GraphQL in a small part of the project, if possible.


Can I use GraphQL without React / Relay / LibraryName?


Of course! GraphQL is just a specification, you can use it with any library on any platform, using a ready-made client (for example, Apollo has clients for web, iOS, Angular and others) or manually sending requests to the GraphQL server.


GraphQL was created by Facebook, and I do not trust Facebook.


Once again, GraphQL is just a specification, which means that you can use it without using a single line of code written by Facebook.


Having Facebook support is definitely a good plus for the GraphQL ecosystem. But at the moment the community is big enough to support GraphQL even if Facebook stops using it.


Somehow "letting a customer ask for the data he needs" doesn't look safe.


As you write your recognizers, you can solve any security problems at this level.


For example, if you allow a client to use the limit parameter to specify the number of documents he requests, you will most likely want to control this number to avoid denial of service attacks when the client requests millions of documents again and again.


So what do you need to get started?


In fact, you only need two components to get started:




Now that you understand how GraphQL works, you can talk about the main players in this area.


GraphQL Servers


The first thing you need to work is the GraphQL server. GraphQL itself is just a specification, so the doors are open to competing implementations.


GraphQL-JS (Node)


This is a link to the original implementation of the GraphQL specification. You can use it with express-graphql to create your own API server (English) .


GraphQL-Server (Node)


The Apollo command has its own implementation of the GraphQL server. It is not yet as complete as the original, but is very well documented, well maintained and developed rapidly.


Other platforms


The official site has a list of implementations of the GraphQL specification for various platforms (PHP, Ruby, and others).


GraphQL clients


Of course, you can work with the GraphQL API directly, but a special client library can definitely make your life easier.


Relay


Relay is Facebook’s own toolkit. It was designed to meet the needs of Facebook and may be a bit redundant for most users.


Apollo client


Quickly took his place a new member in this area - Apollo . A typical client consists of two parts:



By default, Apollo-client saves data using Redux , which itself is a fairly authoritative state-management library with a rich ecosystem.



Apollo extension for Chrome DevTools


Open source applications


Although GraphQL is a fairly new concept, there are already some promising open source applications that use it.


VulcanJS



I (the author of the original article - approx. Lane) is the leading developer of VulcanJS . I created it to give people the opportunity to try the power of the React / GraphQL stack without having to write a lot of boilerplate code. You can take it as “Rails for a modern web-ecosystem” because it allows you to create CRUD applications (for example, an Instagram clone ) for a few hours.


Gatsby


Gatsby is a static site generator for React, which since version 1.0 also uses GraphQL. Despite the fact that this may seem like a strange combination at first glance, this is actually quite a powerful idea. During the build process, Gatsby can extract data from several GraphQL APIs, then use them to create a completely static client React application.


Other tools for working with GraphQL


GraphiQL


GraphiQL is a very convenient browser-based IDE for creating and executing queries to endpoint am GraphQL.



Dataloader


Due to the nested nature of GraphQL queries, one query can easily call dozens of database calls. To reduce the load, you can use caching tools like the DataLoader library developed by Facebook.


Create GraphQL Server


Create GraphQL Server is a console program that allows you to quickly and easily generate a Node-based server using a Mongo database.


GraphQL-up


Similar to Create GraphQL Server, GraphQL-up allows you to quickly create a GraphQL backend, but based on the Graphcool service.


GraphQL Services


Finally, there are a number of companies providing "GraphQL-backend-as-a-service"; they will take care of the server part for you, and this can be a good way to dive into the GraphQL ecosystem.


Graphcool


A flexible backend platform that integrates GraphQL and AWS Lambda, which has a free data plan for development.


Scaphold


Another GraphQL-backend-as-a-service with a free data plan. It offers many features like Graphcool.



There are already a lot of resources in GraphQL.


(Also offer resources in Russian in the comments - approx. Lane.)


GraphQL.org (eng)


GraphQL's official website has great documentation to get you started.


LearnGraphQL (English)


LearnGraphQL is an online course created by Kadira .


LearnApollo (eng)


A good continuation of LearnGraphQL, LearnApollo is a free course created by Graphcool .


Apollo Blog (Eng)


The Apollo blog has a ton of detailed, well-written posts about Apollo and GraphQL in general.


GraphQL Weekly (eng)


GraphQL newsletter newsletter, supervised by the Graphcool team.


Hashbang Weekly (eng)


Another big newsletter, which in addition to GraphQL also covers React and Meteor.


Freecom (eng)


A series of tutorials describing how to create an Intercom clone using GraphQL.


Awesome GraphQL (eng)


Quite an exhaustive list of links and resources for GraphQL.



How can you apply newly acquired knowledge of GraphQL in practice? Here are some recipes you can try:


Apollo + Graphcool + Next.js


If you are already familiar with Next.js and React, this example will allow you to set up a GraphQL endpoint with Graphcool and then send it requests with Apollo.


VulcanJS


The Vulcan tutorial will help you create a simple GraphQL data layer on the server and on the client. Since Vulcan is an all-in-one platform, this is a good way to get started without any configuration. If you need help, do not hesitate to contact our channel Slack (English) !


GraphQL & React Tutorial


The Chroma blog has a six-part guide on how to create a React / GraphQL application using a component-oriented development approach.



Conclusion


GraphQL may seem complicated at first, because it is a technology that affects many areas of modern development. But taking the time to understand the basic concepts, I think you will understand that a lot of this makes sense.


Whether you decide to use it or not, I think it's worth the time to get familiar with GraphQL. More and more companies and structures are starting to use it, and it may well become one of the key building blocks in web development over the next few years.


Do you agree? Do not agree? Questions? Let me know here in the comments.


')

Source: https://habr.com/ru/post/326986/


All Articles