Ever since Facebook open-sourced GraphQL, it’s popularity has been continuously increasing to a point today where it’s almost everywhere. But what makes it so popular? How it compares to the REST Based Architecture and is it going to replace REST APIs completely? Here’s something i think about GraphQL
自从Facebook开源GraphQL以来,它的受欢迎程度一直持续增长,直到今天几乎无处不在。 但是什么使它如此受欢迎? 它与基于REST的体系结构相比如何?它将完全取代REST API吗? 这是我对GraphQL的一些思考
When I first started learning GraphQL ,with zero knowledge about the same. I’ve had this idea in mind that I’m going to learn something which is entirely different from the world of Rest APIs. But halfway through my path learning GraphQL , I realized that even before starting to learn it, I developed some really impractical ideas about same and the biggest of them being
当我第一次学习GraphQL时,对它的知识为零。 我已经想到了这一点,即我将要学习与Rest API世界完全不同的东西。 但是在学习GraphQL的过程中,我意识到即使在开始学习GraphQL之前,我仍对它们产生了一些不切实际的想法,其中最大的想法是
GraphQL is something on its own and doesn’t uses things we’re really familiar with in REST APIs.
GraphQL本身就是一个东西,它不使用我们在REST API中真正熟悉的东西。
Which is very far from the reality and funny but that’s how it appears to the people who’ve never touched GraphQL and just seen it working on the surface.
这与现实相去甚远,而且很有趣,但这就是从未接触过GraphQL并只是从表面看到它的人们所看到的样子。
If i were to define it now in the most simple terms, I would say it’s just a Specification . A really cool way of using our existing web technologies. Under the hood, GraphQL queries are simply a HTTP Post request to an API’s endpoint. Yes, it’s a Post request to an endpoint designed to work with a request including GraphQL queries, let’s quickly see an example by building a GraphQL server
如果我现在用最简单的术语来定义它,我会说这只是一个Specification 。 使用我们现有的网络技术的一种非常酷的方式。 在后台,GraphQL查询只是对API端点的HTTP Post请求。 是的,它是到端点的Post请求,旨在与包括GraphQL查询的请求一起使用,让我们通过构建GraphQL服务器来快速查看示例
For the sake of simplicity I’ll be using Node but since GraphQL is a runtime in itself. It doesn’t matter what language we’re using to build an API. Lets install the dependencies real quick
为了简单起见,我将使用Node,但是由于GraphQL本身就是一个运行时。 用来构建API的语言无关紧要。 让我们快速安装依赖项
yarn add apollo-server moment
yarn add apollo-server moment
And build a simple GraphQL API
并构建一个简单的GraphQL API
const { ApolloServer, gql } = require("apollo-server"); const moment = require("moment"); const server = new ApolloServer({ resolvers: { Query: { getDateTime: () => ({ date: moment().format("MMM DD YYYY"), isoString: new Date().toISOString(), }), }, }, typeDefs: gql` type dateTime { date: String! isoString: String! } type Query { getDateTime: dateTime } `, }); server .listen(4000) .then(() => console.log( `Application worker ${process.pid} is running a server at http://localhost:4000` ) );To run a query
运行查询
Yes that’s exactly right and if you’ve ever touched on GraphQL playground you know it, but this is what i was talking about above. Under the hood a GraphQL client (Consider the GraphQL playground) sends a post request to the specified API endpoint/channel with a body similar to above. The GraphQL runtime is already aware how to handle the request because it has a sense of schema for the data it’s going to get and send back.
是的,这是完全正确的,如果您曾经接触过GraphQL游乐场,就知道了,但这就是我上面所说的。 在后台,一个GraphQL客户端(考虑GraphQL游乐场)使用与上面类似的主体向指定的API端点/通道发送发布请求。 GraphQL运行时已经知道如何处理该请求,因为它对将要获取和发送回的数据具有架构意识。
This, however often leads to an unexpected behaviors when you’re returning a value for something you haven’t specified in the type definitions, GraphQL tries automatically type cast the value and blow up if it doesn’t works.
但是,当您为类型定义中未指定的内容返回值时,这通常会导致意外的行为,GraphQL会尝试自动对类型值进行强制类型转换,如果无效则将其炸毁。
Quick note — Every request to the GraphQL API is classified as a query, including Mutation, subscriptions and query itself if you know what they are.
快速说明—对GraphQL API的每个请求都被归类为查询,包括Mutation,订阅和查询本身(如果您知道它们是什么)。
No there’s a lot more to it and a lot more really, GraphQL brings more power to your APIs (especially to the clients) by allowing them to query only specific fields and hence they can only query the data needed and ignore the rest, which results in smaller transfer size, less bandwidth and latency. Let make changes to our code from above and see it in action
没有更多的东西,而且还有更多的东西,GraphQL通过允许它们仅查询特定字段而为您的API(尤其是客户端)提供了更多功能,因此他们只能查询所需的数据而忽略其余的数据,从而传输尺寸更小,带宽和延迟更短。 让我们从上面更改我们的代码,并在实际中看到它
const { ApolloServer, gql } = require("apollo-server"); const moment = require("moment"); const server = new ApolloServer({ resolvers: { Query: { getDateTime: () => ({ date: moment().format("MMM DD YYYY"), isoString: new Date().toISOString(), localString: new Date().toLocaleString(), }), }, }, typeDefs: gql` type dateTime { date: String! isoString: String! localString: String! } type Query { getDateTime: dateTime } `, }); server .listen(4000) .then(() => console.log( `Application worker ${process.pid} is running a server at http://localhost:4000` ) );We’ve added another field to the type dateTime, and this time we don’t want to query the other two fields. And it’s really dead simple, all we have to do is specify the fields we are interested when making a request like below
我们在类型dateTime中添加了另一个字段,这次我们不想查询其他两个字段。 这真的非常简单,我们要做的就是在发出如下请求时指定我们感兴趣的字段
For a small application this doesn’t add much. But For a large application, you always want the most optimized solutions. The idea to query only the required fields itself is very powerful and hence it’s always been a pattern in the traditional REST architecture as well to make routes for retrieving some specific data. This works without an issue for a small application and even theoretically but as the app size grow larger (consider Facebook), connecting wires become more and more complex and you’ll eventually run into a situation where you have to re design the entire system again using something like GraphQL or maybe end up building another GraphQL.
对于小型应用程序,这并不会增加太多。 但是对于大型应用程序,您始终需要最优化的解决方案。 仅查询必需字段的想法本身非常强大,因此,它一直是传统REST体系结构中的一种模式,并且为获取某些特定数据提供了路由。 对于小型应用程序,甚至从理论上讲,这都没有问题,但是随着应用程序大小的增加(考虑Facebook),连接线变得越来越复杂,最终您将不得不重新设计整个系统使用GraphQL之类的东西,或者最终构建另一个GraphQL。
And there’s still more to cool stuffs GraphQL ships with (Like Subscriptions) but that can be saved for another articles someday because i wanted to talk on if GraphQL is better than the traditional REST APIs.
GraphQL附带(还有“订阅”之类)还有很多更酷的东西,但是有一天可以保存下来,因为我想谈一谈GraphQL是否比传统的REST API更好。
I’ll agree on GraphQL being a better version of rest and it’s a really powerful alternative to REST but it’s not going to replace APIs today or anytime soon. And there are a couple of reasons for the same.The major ones being
我同意GraphQL是rest的更好版本,它是REST的真正强大替代品,但它不会在今天或不久的将来替代API。 造成这种情况的原因有两个。
For a small application A REST API can do pretty much everything a GraphQL API would.
对于小型应用程序,REST API几乎可以完成GraphQL API的所有工作。
Since GraphQL bring more power to the clients by allowing them to only query the fields they need. But this powerful features trades off server side performance for the same, if the client request for a lot of nested fields which requires multiple resources like reading from file system or database. And there are millions of millions of such requests with your servers not being able to scale up really fast, you’ll eventually run out of resources.
由于GraphQL通过允许客户端仅查询所需字段来为客户端带来更多功能。 但是,如果客户端请求大量嵌套字段,而这需要多个资源(例如从文件系统或数据库读取),则此强大功能会牺牲服务器端的性能。 而且有数亿个这样的请求,而您的服务器却无法真正Swift地扩展,最终将耗尽资源。
The above reasons are why in corporate world, GraphQL APIs are used in conjunction with REST API.
以上原因是在企业界将GraphQL API与REST API结合使用的原因。
On a personal level GraphQL is my first preference when building APIs and I really haven’t built anything which doesn’t include the same for a while now. Simply because it adds a better Full Stack DX.
就个人而言,在构建API时,我首选GraphQL,而且我确实有一段时间没有构建任何不包含相同内容的东西。 仅仅是因为它增加了更好的Full Stack DX。
You made it to the very bottom! Thank you for reading.
您做到了最底下! 感谢您的阅读。
Did you know that we have three publications and a YouTube channel? Find links to everything at plainenglish.io!
您知道我们有三个出版物和一个YouTube频道吗? 在plainenglish.io上找到所有内容的链接!
翻译自: https://medium.com/javascript-in-plain-english/loving-graphql-more-than-rest-4e213c568635