当前位置:网站首页>Why don't we use graphql? - Wundergraph
Why don't we use graphql? - Wundergraph
2020-11-09 00:39:00 【On jdon】
In my submission GraphQL Will change the world . future , You can use GraphQL Query any system in the world . I'm building this future . that , Why do I object to the use of GraphQL?
My personal worry is , The current community adopts GraphQL The reason is actually the same as GraphQL irrelevant . If we want to promote the adoption of , We should be honest and take off the rose colored glasses . This article is right Kyle Schrade Of “ Why use GraphQL” The response of the (https://www.apollographql.com/blog/why-use-graphql/), I don't mean to criticize the article directly , In my submission Kyle The article should be named “ Why use Apollo”.
REST shortcoming
Author points out REST API It has some disadvantages , as well as GraphQL How to solve all these shortcomings : Multiple requests over fetching multiple resources , A waterfall network request based on nested data will be generated , To get these nested data , Every client needs to access every service that provides these nested data .
Excessive requests can be resolved by writing another REST API As the appearance of a specific user interface . With Next.JS For example . Next , You can use very lightweight syntax to define API. You can wrap these calls into API And make them on the server side , Instead of making multiple requests from the client .
Using this method can also solve over acquisition and insufficient acquisition , Because you can manipulate the data before sending it back to the client . The pattern described is called “ The front end of the back end ”(BFF). It's not limited to Next.JS A complete stack framework like this . You can also build BFF.
Use BFF Pattern , The client itself does not have to know the location of each service . however , The implementation of BFF Developers need to understand the service landscape . I hope you have open access to all services API standard , These specifications are well introduced in the developer portal . If you do this , To write BFF It should be easy .
Use GraphQL, Still need a developer to implement the parser . Implement parser and build BFF It's almost the same task , The logic is very similar . that , What's the real difference ?
BFF Easy to implement , Because there are more tools available . for example , If you will Next.JS Such a framework is related to swr hook ( Invalid on revalidation ) Use a combination of , You can use it automatically Etags Cache , And it can make the cache invalid . This reduces the amount of data sent between the server and the client . And GraphQL comparison , It has less data , Because you didn't send the query payload , And if the response is still valid , The server will use 304( not changed ) To respond . Besides , You don't have to use something like Apollo Such a heavyweight client .Vercel The library of swr Very small , Very easy to use . It has a pair of pagination , Hook support , And it helps navigate back and forth very efficiently .
GraphQL Keep the query , But there's an extra overhead to do this . If you don't use something like Relay Such a client ( Queries are retained by default ), You must do it yourself or use a third-party library to implement it . And use Next.JS Of BFF Methods compared , Getting the same result on the front end involves more complexity . How will you use GraphQL Realization Etags? If no changes have been made , How to make GraphQL Server return 304 The status code ? You don't have to convert all queries to GET Please ? If so , Your GraphQL Whether the client and server support this function easily ?
In terms of user experience and ease of development ,BFF No doubt the winner . Less data transfer between client and server . Easy to implement . Smaller customers , Fewer moving parts .
But there is a trap . You have to build one for each front end BFF. If you have a lot of , Then it could take a lot of work . You have to maintain all BFF. You have to operate on it . You have to protect them .
If you get the benefits of both without compromising , Wouldn't that be nice ? That's exactly what it is. WunderGraph The meaning of , It's using GraphQL structure BFF Framework .
There are no more versions of API
In the next paragraph ,Kyle Continue to explore the version API The issues involved . He was absolutely right , because API Too many versions make tracking very difficult . Then he came to the conclusion , stay GraphQL in , There is only one version of the graphics , And you can track changes in the schema registry , This is a Apollo The payment function of . therefore , You won't have any problems with version control , He said .
It's hard for me to come to the same conclusion . Just because GraphQL The schema itself does not support version control , It doesn't mean the problem disappears . If you're not right REST API Version control , You'll get the same effect . actually , Many experts say , If not, you should never try to introduce API edition . That said , What prevents you from running both versions of GraphQL Pattern ? I'm not saying it's a good idea , But it's technically feasible .
If there are too many REST API Version of the problem , So throw something like GraphQL Before new tools like that , Maybe you should take a look at the organization first . What's the reason there are so many versions ? Maybe a process change or a new team structure will help ?GraphQL Will never solve your version problem . contrary , I think it actually makes things worse .
Do you have to support mobile apps ? You should be aware of , It takes time to deliver local applications . You have to wait for App Store approval , And many users can be expected to never ( Or slowly ) Install a new version . What if you want to make a major change in this situation without breaking the customer ? impossible . You have to introduce such changes in an uninterrupted manner .
stay GraphQL In this case, the development pattern will mean that you are not in favor of using old fields and adding new fields . New customers use new fields , And the number of customers you want to use the old fields will be less and less . Hope you have a system that forces your users to download a new version at some point in time . otherwise , You may be forced to support fields that are not recommended indefinitely . If that's the case ,GraphQL The abandoned model of can't help you at all .
Use REST, You can create a new endpoint or another version of an existing endpoint . The problem is the same , The solution looks a little different .
To be clear , If you can't control the development on the customer side , You really need some kind of version control . If you have only one Web Applications , This function is not required . But then again ,GraphQL Maybe it's too killer .
Smaller loads
In this paragraph , Original author Kyle claim RESTful API Partial response is not allowed .
This is wrong . This is an example :
GET /users?fields=results(gender,name) |
author Kyle What does it actually mean ? I'm sure he knows part of the response . I think what he's trying to say is that someone needs to implement a partial response . actually , When you select a subfield from a resource , For it GraphQL It looks very familiar . Use GraphQL, We can use this function immediately .
On the other hand , Use BFF Method , You don't need this method . Just return the required data accurately . Again , image Next.JS Such a full stack framework makes it easier to implement this process , Make caching easier , And give you free access based on Etag Cache failure of .
Summarize this section ,GraphQL Can provide you with the exact data you need . Part of the response can achieve the same result .BFF With the additional cost of implementation and maintenance , But with better UX and DX.
Strict type interface
In this paragraph ,Kyle Solved the problem of not strictly typing REST API The problem of . He talked about API The problem of , These questions are not clear , If you get an array of posts or other content , So how query parameters complicate the situation . He also pointed out that , because GraphQL Having a strict type system , So there won't be this problem .
In my submission Kyle It's a matter of organization , You need an organizational solution .
When you allow developers to deploy REST API Instead of Publishing Open API Specification(OAS) Or something like that , You will encounter the kind of problem he described . Use OAS, It's easy to describe all the resources .OAS It also allows you to describe the OAuth2 Flow and required range . Besides , You can describe the exact types of query parameters and validation rules , This is a GraphQL The missing features .
from GraphQL Look at , Cannot describe Authentication , Authorization and input validation .GraphQL Lack of these features , because Facebook The inventors of the invention solved this problem at different levels . They don't have to add these features to GraphQL. You can add custom directives to the architecture , To achieve something similar to OAS Result , But this will be a custom implementation that you will have to maintain .
You may think that OAS No guarantee API The response to the specification . You're right . however GraphQL How patterns guarantee anything ?
GraphQL Introspection is going to be specific GraphQL Queries are sent to the server for information about GraphQL The operation of the information of the pattern .GraphQL The server is free to choose any type you want . If you send a query , Then the server can use the introspective response to the inconsistency GraphQL Pattern response to answer .
With Apollo The league, for example . You upload the schema to the schema registry , Then the wrong version of GraphQL The server . If you change the type of the field , The client may be confused .
When we talk about GraphQL When the type security in , Actually, it means that we believe GraphQL The behavior of the server is fully consistent with the behavior advertised by the introspective query response . Why can't we trust in the same way Open API standard ? I think we can . If we don't , That's the personnel problem , It's not about technology .
Better client performance
The next paragraph briefly introduces GraphQL How to improve client performance and reduce network round trip times .
In my submission , And the heavyweight GraphQL Compared with the client side , I have fully explained BFF Is much more powerful , And from “ Outdated revalidation patterns ” How much profit did you get from .
in other words ,GraphQL It does reduce the number of requests and the overall data transfer . however , You should always consider that GraphQL The cost of adding clients to the front end .
Reduce logging and browsing API Time for
The next section describes how to make OAS Tools like that are used for RESTful API Develop and maintain multiple OAS The challenge of .Kyle Will single GraphQL Patterns and distributions in multiple git In the repository Swagger The documents are compared .
I think it's obvious , Navigation single GraphQL Model than sitting in git View multiple OAS Documents are much simpler . however , To be fair , We have to compare one apple to another . If you want to improve developer productivity , Will not OAS Paste the document into git Repository , It's named every day . You are running a developer portal , You can search for API And navigate between them .
OAS Depend on JSON-Schema, This feature has amazing features : You can refer to an object type in another document . You can use OAS Divided into multiple files , if necessary , They can be quoted from each other . There are also tools that can make multiple OAS The files are merged into one OAS In the document . then , You can use this document , And input it into the developer portal , The portal allows you to view all of API. please remember , Setting up all of these costs extra . You need to run a development portal or purchase a . You have to describe all of API, At least at the beginning , It could be a burden .
One thing to add is , There are many frameworks that allow you to describe the architecture in your favorite programming language , For example, by defining objects or classes . then , You will get an auto generated Open API standard , The specification will provide .
Let's combine it with GraphQL Compare . There are basically two ways , First of all SDL, And then there's the code . Either way , In the end, you'll get one GraphQL Pattern , The schema describes all types and fields , And allows you to comment on it .
that , What's the difference ?OAS With more overhead to set up . On the other hand ,OAS With built-in supporting documentation sample use cases , Authentication and authorization and input validation rules .
please remember ,GraphiQL There are not many GraphQL The concept of patterns . If you have more than one GraphQL( tiny ) service , You have to run or buy specialized components , for example , Be similar to REST API Developer portal architecture registry .
An additional paragraph I would like to highlight is API Use cases . Just because you have OAS or GraphQL Pattern , It doesn't mean your API Well documented .API Users can use the API What do you do ? How they use it ? What is a good use case ? What's wrong with it ? Where to ask for help ? How to authenticate users ? I need it API Key ? Use one that can help API User use API To record your API, Much more than adding descriptions to types and fields .OAS Allows you to add sample payloads and describe them .GraphQL Missing this feature . stay Stripe See the last positive example . They go far beyond Swagger or GraphQL Playground The range that can be achieved .
On the other hand , If you look at GitHub Public GraphQL API, You will not find a single sample query . Suppose you want to get information about the repository and all its problems . You have to open GraphiQL And start searching for . however ,GraphiQL The search function in doesn't really help you . Someone needs to sit down and write sample queries and about how to use API The use case . otherwise , It's really hard to get started .
therefore , Although the community has been saying “ GraphQL Self recording ”, But this feature alone doesn't provide useful API.OAS Provides you with tools to add use cases , But you still have to write them . Whatever tool or language you choose , It takes effort to make API It works for other people .
Support for traditional applications
In this passage , The author says , Keep the old version of... For mobile applications REST API A lot of pain . His conclusion is , Because we only use a single GraphQL The server , So there won't be this problem .
I'm sorry , Again, I came to a completely different conclusion . If you set the rule to disable version control , You can add new endpoints or exchange implementations of existing endpoints . under these circumstances ,GraphQL and REST There is no difference between . about REST and GraphQL API for , Supporting older applications is a challenge . You need to find a way to not break the contract between the client and the server . Whether the server is public REST or GraphQL It doesn't matter , The problem is the same .
Better error handling
About error handling , The author describes a scene , That is to say, with a single GraphQL Compared with , The client must do 3 A follow-up REST API call .
Use GraphQL, The logic for parsing part of the data is in the server . The client needs to have additional logic to respond appropriately to part of the response .
With the help of REST, The logic for getting part of the data can be on the client side or BFF in . Either way , Its logic is more or less the same as GraphQL identical , Just somewhere else . obviously ,REST API Use cases also require logic in the client to handle part of the response . This logic is almost the same as GraphQL The logic in use cases is the same .
Nothing can stop you from REST The response returns specific information about the cause of the failure .OAS Allow union types , So you're free to provide customers with rich information about partial responses . This is similar to Sascha Solomon(https://sachee.medium.com/200-ok-error-handling-in-graphql-7ec869aec9bc) Describe the concept of response Association .
GraphQL Do you really have better error handling ? In my submission OAS and GraphQL They all provide you with good tools , Handling errors in a very user-friendly way . Developers should make full use of these tools . There is no free lunch .
Conclusion
Kyle It is concluded in the full text that ,GraphQL yes API The future of , Because it's in performance , Payload size , Excellent developer time and built-in documentation .
I agree with GraphQL yes API The future of , But for different reasons .
Better performance and smaller payload size are not GraphQL The unique function of . You can use other tools to get better results , Or it has to expand GraphQL, For example, using Relay To get persistent queries . In order to learn from GraphQL Get real benefits from documentation , What you are sure to do is not just add descriptions to the architecture .
Once the dust has settled , The hype disappeared , We have to look at the facts . We should not try to convince the world that GraphQL. Use GraphQL There are many advantages , But according to your use case , You may not really benefit from it . Rather than GraphQL It's the Holy Grail , It's a more subtle response .
The best way to solve this problem is to look at the problem first , Then make a unique comparison of the possible tools to solve the problem . If your organization cannot achieve REST API, that GraphQL How can we solve this problem ? Maybe something in your organization has to change ? On the other hand , If it's not an organizational problem , And you're absolutely sure REST Not a good choice for your use cases , So I'll bet , You will love it GraphQL.
GraphQL It's almost useless in itself . It is GraphQL A tool makes GraphQL So powerful . It's the community , It is our ! image Apollo,Hasura,The Guild,FaunaDB,Dgraph,GraphCMS Companies like that , I hope too WunderGraph So it is , They make GraphQL So powerful . It is GraphiQL, Various GraphQL client , Pattern stitching , union . The whole tool ecosystem is GraphQL Why it's the next big thing .
More tools and services will strengthen the ecosystem . Stronger ecosystems will lead to more adoption of , This will attract more companies for GraphQL Ecosystem add services and tools , It's a very positive cycle .
GraphQL In this respect with Kubernetes Very similar .Docker( Container runtime ) Is not enough . The complex Syscall Packaged as easy to use API It's the enabling factor , But to create a rich ecosystem , Need a scheduler , The scheduler should be expressive enough and easy to extend .
GraphQL Provides a Docker As simple as language to define and use API. If you've seen a few lines before Javascript and JSON, be GraphQL Will immediately make you feel familiar with . But it's similar to Docker, The language itself is not powerful . It's extensibility and the tools around it .
When Kyle ask “ Why GraphQL” when , I think what he actually meant was “ Why Apollo”. The answer is simple . No one wants to surround REST API Building a rich ecosystem . Try to open up API Specification generation React.JS client . And GraphQL What the customer gives you is compared to , It's a bad experience . No one has come up with a good business model to solve this problem . Input GraphQL, You'll get plenty of tools to abstract out problems you don't want to deal with .
REST API The relevance to the described use cases will be reduced , Not because GraphQL It's advanced . It is to make GraphQL Tools and ecosystems to continue to gain market share . And REST comparison ,GraphQL Ecosystems are expanding very fast .
Hypermedia API Presented on the server Web There has always been a huge role in applications , And still plays an important role . however , The Internet is moving forward . The native experience users expect from the site .Jamstack Taking over the front end . With server-side rendering and dynamic Javascript The client-side hybrid model is the implementer of these applications .
RESTful API Good at solving a range of different problems . They don't disappear , On the contrary ! For this type of application that the industry is changing , They are not the right tools . In my submission REST API It's internal API, partners API Ideal tool for server to server communication . This is a GraphQL stay REST Areas where aspects don't really bring any benefits . And RPC Together , It will have a bright future in this field .
版权声明
本文为[On jdon]所创,转载请带上原文链接,感谢
边栏推荐
- Copy the picture
- Huawei HCIA notes
- 理论与实践相结合彻底理解CORS
- Why need to use API management platform
- Platform in architecture
- 常见特征金字塔网络FPN及变体
- VIM 入门手册, (VS Code)
- Have you ever thought about why the transaction and refund have to be split into different tables
- App crashed inexplicably. At first, it thought it was the case of the name in the header. Finally, it was found that it was the fault of the container!
- A few lines of code can easily transfer traceid across systems, so you don't have to worry about losing the log!
猜你喜欢
大数据软件学习入门技巧
使用递增计数器的线程同步工具 —— 信号量,它的原理是什么样子的?
Decorator (1)
Copy on write collection -- copyonwritearraylist
Why need to use API management platform
Several common playing methods of sub database and sub table and how to solve the problem of cross database query
c++11-17 模板核心知识(二)—— 类模板
App crashed inexplicably. At first, it thought it was the case of the name in the header. Finally, it was found that it was the fault of the container!
LeetCode-11:盛水最多的容器
老大问我:“建表为啥还设置个自增 id ?用流水号当主键不正好么?”
随机推荐
对象
How does semaphore, a thread synchronization tool that uses an up counter, look like?
使用容器存储表格数据
On buffer overflow
实现图片的复制
使用递增计数器的线程同步工具 —— 信号量,它的原理是什么样子的?
Fiddler无法正常抓取谷歌等浏览器的请求_解决方案
LeetCode-11:盛水最多的容器
Huawei HCIA notes
14. Introduction to kubenetes
基于链表的有界阻塞队列 —— LinkedBlockingQueue
The interface testing tool eolinker makes post request
Salesforce connect & external object
AQS 都看完了,Condition 原理可不能少!
App crashed inexplicably. At first, it thought it was the case of the name in the header. Finally, it was found that it was the fault of the container!
Dynamic relu: Microsoft's refreshing device may be the best relu improvement | ECCV 2020
C/C++编程笔记:指针篇!从内存理解指针,让你完全搞懂指针
1.操作系统是干什么的?
链表
centos7下安装iperf时出现 make: *** No targets specified and no makefile found. Stop.的解决方案