(Turn) with five reasons / not GraphQL of

 

https://www.jianshu.com/p/12dff5905cf6

 

I have a blog / How how Gatsby to build a blog with Gatsby this article mentioned in the application GraphQL in Gatsby. In general, it is a trendy technology, the appropriate usage scenarios infinite power. Here we discuss the reasons with / without GraphQL it.

Brief GraphQL

 
GrahQL

GraphQL is Facebook2015年开源的数据查询规范. Today the vast majority are RESTful Web Service, that is, the main mode of communication by the client and the server or client initiates a request to a number of endpoint server (url) according to their needs. Because of the growing wealth of features, requirements for Web Application is complicated, some of the problems REST gradually exposed, people began to think about how to deal with these issues. GraphQL is a kind of representative. GraphQL name, Graph + Query Language, to show that it is designed is intended to represent the data in a manner similar to Figure: that unlike in REST, data is divided each API endpoint, but there is a hierarchy of relevance and They are grouped together.

For example, suppose such a providing user information REST API: <server> / users / <id>, and provide the user's API followers: <server> / users / < id> / followers, and the user object of interest API: <server> / users / <id> / followed-users. Traditional REST API call would require three to three out of this request message (assuming <server> / users / <id > does not contain information about followers and followed-users, Which Will A definite Redundancy IF IT BE does):
. 1 the GET < server> / users / <id>

{
 "user": {
    "id" : "u3k2k3k178",
    "name" : "graph_ql_activist", "email" : "[email protected]", "avatar" : "img-url" } } 

2 GET <server>/users/<id>/followed-users
3 GET <server>/users/<id>/followers

However, if you use GraphQL, once API request to obtain all the information and select only the information (such as user name do not only need to email, followers as long as the foremost five name, followed-users as long as the picture, etc.) required:

query {
  user (id : "u3k2k3k178") {
    name
    followers (first: 5) { name } followed-users { avatar } } } 

We will get a completely customized according to query, but not too much return results (usually a json object).

5 reasons to use GraphQL

The reason for using GraphQL, must be starting to discuss RESTful Service limitations and problems.

  1. Redundancy and redundancy data request (overfetching & underfetching)
  2. Flexible and strongly typed schema
  3. Interface check (Validation)
  4. Interface changes, maintenance and documentation
  5. Development efficiency

1 and the request data redundancy redundancy (overfetching & underfetching)

According to the example users API, we can imagine, REST call GET user information, even if we just want a twelve user information (such as name & avatar), via the API, we will get his entire message. The so-called overfetching refers in this case - the current request contains unnecessary information. This waste will to some extent affect the overall performance, after all, more information will be occupied bandwidth and resources to handle.

Similarly, we can see from the above example, in many cases, if we use RESTful Application, we often need to be closely linked and small amount of information on multiple server requests, call a plurality of API.

As an example, to get the ID is "abc1" and "abc2" two users of information, we may need two API call, one hundred users is one hundred GET call, which is not very baffling it? This situation is actually underfetching--API the response is not reasonable contain enough information.

However, in GraphQL, we only need to change the approach is very simple schema, you can solve with a GET call:

query {
  user (ids : ["ab1", "abc2", ...])
}

We open a new page, if it is RESTful Application, may request the data will soon have hundreds of HTTP Request, however GraphQL the Application you may need only one or two, which is equivalent to the complexity and heavy lifting handed over and server-side cache layer, instead of limited resources, and client-side speed-sensitive.

2 flexible and strongly typed schema

GraphQL are strongly typed. In other words, when we define the schema, similar to using SQL, are explicitly defined for each field type, for example:

type User {
  id: ID!
  name: String!
  joinedAt: DateTime!
  profileViews: Int! @default(value: 0)
}

type Query {
  user(id: ID!): User
}

Writing language GraphQL the schema, in fact, there is a special name - Schema Definition Language (SDL).

One big advantage of this matter is that at compile or build upon this Application, we can examine and deal with a lot of mis-typed the problem without the need to wait until runtime. At the same time, this way of writing, but also provides great convenience for developers. For example, when using YAML to define the API, writing itself is very troublesome - may not be the ideal auto-complete, syntax or semantics have not been able to find fault, the document also needs its own carefully written. Even if there are many tools (such as Swagger ) help, this is still a very daunting problem.

3 Interface check (Validation)

Obviously, due to the strong type of use, we operate testing easier and stringent data received, the automated simplicity and effectiveness is also greatly improved. Check the structure of the query itself is also equivalent to automatically got in after the schema is complete, we even do not need to introduce any other tools or rely on, you can easily solve all the validation.

4 Interface changes, maintenance and documentation

RESTful Application inside, want to change once the API, regardless of additions and deletions range, change the range of values, or increase or decrease the number of API, changing the API url, very easy to become acts of beating.

If the changes API url (for example, / posts -> / articles), we think about those places you might want to change it? First of all client-side code will certainly have to change the API request of the endpoint; the middle of the caching service may also need to change the endpoint to be accessed; if load balancer, reverse proxy, it may also need to change; server end their own course, need to make the appropriate changes, it depends on their written application situation.

In contrast, GraphQL so much easier. GraphQL the Service, API endpoint is likely to have only one, there are less subject to change in case the URL path. Start to finish, the requesting party data only needs to explain what they need, without any express concern and to realize the back end. Data providers, such as server, as long as the data set of the requesting party is the parent, regardless of how their respective change, because the other side does not need to pull affect the whole body.

Under existing tools, REST API documentation is not overly difficult to write and maintain a degree, but with completely auto-generate and readability can be well guaranteed GraphQL compared to, or slightly less - even after all GraphQL other tools that we do not need much effort to introduce.

Another point, we all know that there is a REST API versioning: V1, V2, etc. it is very sad and very troublesome, and sometimes even consider backward compatibility. GraphQL In essence it does not exist, greatly reducing the redundancy. Increase in the data fields and the data types do not even need to make any changes to the requester, only needed to add corresponding queries.

In addition, with GraphQL of queries, we can analyze the data (Analytics) very accurately. For example, fields / objects under what specific circumstances in which queries are requested most / least frequently - unlike RESTful Application, if not complicated Analytics, we can only know the circumstances of each API requested rather than specific to their embedded data.

5 development efficiency

I believe the above said, these points have been fully able to explain GraphQL for the development efficiency can be improved how.

Then add a few points.

GraphQL have a very good ecosystem. Because of its convenient developers get up and running -> everyone competing to provide tools and support for it -> GraphQL become easier to use -> Cultural and Community Support flourished -> Like other good ... as open source projects, GraphQL has a very good positive feedback loop.

For a REST API, even just its users (Consumer), developers of new contact will take some time to become familiar with its logic generally require even realized. However GraphQL users do not even need to see something similar to the API documentation, because we can query directly query all domain type of query inside at all levels and their respective type, which have to say is very convenient:

{
  __schema {
    types {
      name
    }
  }
}

==> We can see all of the content type of query involved:

{
  "data": {
    "__schema": {
      "types": [
        {
          "name": "Query" }, { "name": "Episode" }, { "name": "Character" }, { "name": "ID" }, { "name": "String" }, { "name": "Int" }, { "name": "FriendsConnection" }, { "name": "FriendsEdge" }, { "name": "PageInfo" } { "name": "__Schema" }, { "name": "__Type" }, { "name": "__TypeKind" }, { "name": "__Field" }, { "name": "__InputValue" }, { "name": "__EnumValue" } } ] } } } 

For GraphQL, I have a very personal reason to prefer it: to test the API, compared to the more traditional Postman or write your own script for basic http call (or curl), I prefer to use insomnia this more elegant Tool of. And on top of this, it is very well supported GraphQL , it makes my development and testing experience to become better. (Postman still do not support GraphQL, although in essence we can use it to make GraphQL query call)

5 reasons not GraphQL

  1. Migration costs
  2. Performance sacrifice
  3. Lack of dynamic typing
  4. Simple question complicated
  5. Cache can solve many problems

1 Use and migration costs

If you are an existing RESTful Application transformed into GraphQL Application?

hmmm...

We need to think again. First, I will not say RESTful originally from end to end has a mature and efficient solutions to solve this crap up. The main problem of migration is that it changed the way we organize and exposure data from a fundamental way, that is to say for the application itself, from the data layer to the business logic layer, may have a very great impact. So it is not suitable for the existing complex system, "Li after the first break." SpringMVC ran a huge Web Application If you want to change the trendy GraphQL application? This is difficult to predict the cost and disruptive.

And, although we say GraphQL have good community support, but using GraphQL Essentially, it means you want to use React with NodeJS. So if you are not using or planning to use React and Node, GraphQL is not suitable.

2 Performance sacrifice

Performance This thing is so many people are complaining about. As we said earlier, GraphQL solution, equivalent to the complexity and heavy lifting from the user's eyes, moved to the back-end - many times, is the database.

To discuss this, we must first mention that, in order to support GraphQL queries For queries, developers need to write data resolvers.

For example, such a schema:

type Query {
  human(id: ID!): Human
}

type Human {
  name: String
  appearsIn: [Episode]
  starships: [Starship]
}

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

type Starship {
  name: String
}

For human, we need a most basic resolver:

Query: {
  human(obj, args, context, info) {
    return context.db.loadHumanByID(args.id).then(
      userData => new Human(userData)
    )
  }
}

Of course, this does not end, for different types of requests, we not only had to write different resolver-- CRUD REST API, we have to take care of, may have to write more resolver according to business needs.

The impact caused by this matter, in addition to the developer to write a lot of boilerplate code, it also could lead to poor query performance. A RESTful Application, due to the uncertainty of each API, we can for each API logic, very good to optimize their performance, so even if there is a certain degree of overfetching underfetching, performance / front and rear ends are maintained at acceptable range Inside. However, some want a more universal GraphQL, it may be because of a complex hierarchical structure and many domains have a great amount of data query run many resolvers, so that the database query performance becomes a bottleneck.

3 lack of dynamic typing

Strongly typed schema is certainly very labor-saving, but sometimes if we want some freedom (flexibility) it?

For example, sometimes when the requested data, the requesting party does not intend to define all the domain hierarchy and the type that you need. Let's say we want to simply print some data, or get a part of a user of the fields directly, using the remaining part may or may not be saved after use, but does not determine the rest do not care about those specific fields- - extra parts may be used as additional info, some fields are used if there is no skip.

This is just an example, but the example is not a dead end - because sometimes we want objects of properties already likely to be dynamic, and we may even be determined by its properties / fields it is a kind of object.

How we want to deal with this problem? A somewhat absurd realistic approach is to Riga Type a JSON string field, to provide all relevant information so that you can deal with this situation. But this is not a reasonable thing to do?

4 simple questions complicated

The most notable example is the error handling. The case of the REST API, we need to parse the contents of Response, just look at HTTP status code and message, will be able to know whether the request is successful, about what the problem is, error handling procedure is also very easy to write.

However, under GraphQL scene, hmmm ...

As long as the Service itself is still operating normally, we get HTTP status 200, and then check the response of the need for specialized content to know whether there is error:

 {
      "errors": [
        {
          "message": "Field \"name\" must not have a selection since type \"String\" has no subfields.",
          "locations": [
            {
              "line": 31, "column": 101 } ] } ] } 

Another layer of complexity.

At the same time, a simple Application, use GraphQL actually very troublesome - such as resolvers mentioned earlier, it requires a lot of boilerplate code. In addition, there are a variety of Types, Queries, Mutators, High-order components need to write. By comparison, but rather better REST API to write and maintain.

5 cache can solve many problems

After writing over HTTP related program should know, HTTP itself is covered by caching of , not to mention the people in order to improve performance RESTful Application of and for the cache efforts made.

And the number of requests for overfetching redundancy problem, assume that our entire application doing enough reasonable design, and because of the fixed and simple REST API, the cache has been able to reduce a lot of very good traffic.

However, if you choose to use GraphQL, we do not so straightforward caching solutions. First, only the case of a API endpoint of each query may be different, we can not very easily categorized on the request to do caching. Of course not to say that really do not have ready-made tools, such as Appollo client provides a InMemoryCache and, no matter how many queries, there is always a hot queries and cold ones, then the pattern is always there. For some specific query we also can be directed to the cache, for example PersistGraphQL is such a tool. However, doing so is in fact equivalent to extract from the queries in the original part of the REST API is similar, and add another layer of complexity, whether for development or for the performance, which may have impact can not be ignored.

to sum up

GraphQL biggest advantage is that it is possible to greatly improve the efficiency of the developer, and is designed to simplify the complexity of the front end of the data layer, and such that the front and rear end view of the organization of data coincide. When only use, need to look at scale, performance, tech requirements stack, migration, etc., and do a reasonable trade-off, otherwise it may not only failed to improve developer productivity, and have actually create more problems.

References



Author: freenik
link: https: //www.jianshu.com/p/12dff5905cf6
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Guess you like

Origin www.cnblogs.com/stableboy/p/11226329.html