graphql是什么
by Sacha Greif
由Sacha Greif
If you’re like me, you probably go through three stages when hearing about a new technology:
如果您像我一样,则在听说一项新技术时可能会经历三个阶段:
One more JavaScript library?! Just use jQuery already!
还有一个JavaScript库? 就已经使用jQuery了!
Hmm, maybe I should check out this new library I keep hearing about…
嗯,也许我应该去看看我一直在听说的这个新图书馆……
Help! I need to learn this new library right now or I’ll be completely obsolete!
救命! 我现在需要学习这个新的库或我会完全过时!
The trick to maintaining your sanity in these fast-moving times is to learn new stuff right between stages two and three, once your interest is piqued but while you’re still ahead of the curve.
在这些瞬息万变的时代保持理智的诀窍是,一旦激发了您的兴趣,但仍处于领先地位,就可以在第二和第三阶段之间学习新知识。
Which is why now is the perfect time to learn what exactly this GraphQL thing you keep hearing about really is.
这就是为什么现在是学习您一直在听说的GraphQL到底是什么的绝佳时机。
In a nutshell, GraphQL is a syntax that describes how to ask for data, and is generally used to load data from a server to a client. GraphQL has three main characteristics:
简而言之,GraphQL是描述如何请求数据的语法,通常用于将数据从服务器加载到客户端。 GraphQL具有三个主要特征:
So how did GraphQL get started? What does it look like in practice? And how do you start using it? Read on to find out!
那么GraphQL是如何开始的呢? 在实践中看起来像什么? 您如何开始使用它? 请仔细阅读,找出答案!
GraphQL got its start at big old Facebook, but even much simpler apps can often bump into the limitations of traditional REST APIs.
GraphQL始于大型的旧Facebook,但即使简单得多的应用程序也常常会遇到传统REST API的局限性。
For example, imagine you need to display a list of posts
, and under each post a list of likes
, including user names and avatars. Easy enough, you tweak your posts
API to include a likes
array containing user objects:
例如,假设您需要显示一个posts
列表,在每个帖子下显示一个likes
列表,包括用户名和头像。 很简单,您可以调整posts
API以包含一个包含用户对象的likes
数组:
But now, it’s time to work on your mobile app, and it turns out loading all that extra data is slowing things down. So you now need two endpoints, one with the likes
and one without them.
但是现在是时候在您的移动应用程序上工作了,事实证明,加载所有这些额外的数据使速度变慢了。 因此,您现在需要两个端点,一个包含likes
,一个没有likes
。
Now add one more factor to the mix: it turns out that while posts
are stored in a MySQL database, likes
on the other hand live in a Redis store! What do you do now?!
事实证明,虽然:现在一个因素加进来posts
都存储在MySQL数据库中, likes
在Redis的店铺,另一方面住! 你现在做什么?!
Extrapolate this scenario to however many data sources and API clients Facebook has to manage, and you can imagine why good old REST APIs were starting to show their limits.
将这种情况推论到Facebook必须管理的许多数据源和API客户端,您可以想象为什么好的老式REST API开始显示其局限性。
The solution Facebook came up with is conceptually very simple: instead of having multiple “dumb” endpoints, have a single “smart” endpoint that can take in complex queries, and then massage the data output into whatever shape the client requires.
Facebook提出的解决方案在概念上非常简单:与其拥有多个“哑”端点,不如拥有一个可以处理复杂查询的“智能”端点,然后将数据输出调整为客户端所需的任何形状。
Practically speaking, the GraphQL layer lives between the client and one or more data sources, receiving client requests and fetching the necessary data according to your instructions. Confused? It’s metaphor time!
实际上,GraphQL层位于客户端和一个或多个数据源之间,用于接收客户端请求并根据您的指令获取必要的数据。 困惑? 现在是隐喻的时间!
The old REST model is like ordering pizza, then getting groceries delivered, then calling your dry cleaner to get your clothes. Three shops, three phone calls.
旧的REST模式就像订购比萨饼,然后运送食品杂货,然后打电话给干洗店买衣服。 三个商店,三个电话。
GraphQL on the other hand is like having a personal assistant: once you’ve given them the addresses to all three places, you can simply ask for what you want (“get me my dry cleaning, a large pizza, and two dozen eggs”) and wait for them to return.
另一方面,GraphQL就像有个私人助理:将所有三个地方的地址给他们后,您只需索要什么(“给我干洗,一个大比萨饼和两个鸡蛋)” ),然后等待他们返回。
In other words, GraphQL establishes a standard language for talking to this magical personal assistant.
换句话说,GraphQL建立了一种与这位神奇的私人助理交谈的标准语言。
In practice, a GraphQL API is organized around three main building blocks: the schema, queries, and resolvers.
实际上,GraphQL API围绕三个主要构建块进行组织: 模式 , 查询和解析器 。
The request you make to your GraphQL personal assistant is the query, and it looks something like this:
您对GraphQL个人助理的请求是query ,它看起来像这样:
query { stuff}
We’re declaring a new query using the query
keyword, then asking for a field named stuff
. The great thing about GraphQL queries is that they support nested fields, so we can go one level deeper:
我们要使用query
关键字声明一个新查询,然后要求一个名为stuff
的字段。 GraphQL查询的妙处在于它们支持嵌套字段,因此我们可以更深入一点:
query { stuff { eggs shirt pizza }}
As you can see, the client making the query doesn’t need to care which “shop” the data is coming from. Just ask for what you need, and let the GraphQL server take care of the rest.
如您所见,进行查询的客户端不需要关心数据来自哪个“商店”。 只需询问您需要什么,然后让GraphQL服务器处理其余的工作即可。
It’s worth noting that query fields can also point to arrays. For example, here’s a common pattern when querying for a list of posts:
值得注意的是,查询字段也可以指向array 。 例如,这是查询帖子列表时的一种常见模式:
query { posts { # this is an array title body author { # we can go deeper! name avatarUrl profileUrl } }}
Query fields also support arguments. If I want to display a specific post, I can add an id
argument to the post
field:
查询字段还支持参数 。 如果要显示特定的帖子,可以在post
字段中添加id
参数:
query { post(id: "123foo"){ title body author{ name avatarUrl profileUrl } }}
Finally, if I want to make that id
argument dynamic, I can define a variable and then reuse it inside the query (note that we’re also naming the query here):
最后,如果我想使该id
参数动态化,我可以定义一个变量 ,然后在查询中重用它(请注意,我们也在这里命名查询):
query getMyPost($id: String) { post(id: $id){ title body author{ name avatarUrl profileUrl } }}
A good way to put all this in practice is to use GitHub’s GraphQL API Explorer. For example, give the following query a try:
将所有这些付诸实践的好方法是使用GitHub的GraphQL API Explorer 。 例如,尝试以下查询:
query { repository(owner: "graphql", name: "graphql-js"){ name description }}
Notice that as you try typing a new field name below description
, the IDE will automatically offer possible field names directly auto-completed from the GraphQL API itself. Neat!
请注意,当您尝试在description
下方输入新的字段名称时,IDE会自动提供直接从GraphQL API本身自动完成的可能的字段名称。 整齐!
You can learn more about GraphQL queries in the excellent Anatomy of a GraphQL Query article.
您可以在《 GraphQL查询》的出色解剖中了解有关GraphQL查询的更多信息。
Even the best personal assistant in the world can’t go and get your dry cleaning unless you give them an address.
除非您给他们提供地址,否则即使是世界上最好的私人助理也无法去干洗。
Similarly, your GraphQL server won’t know what to do with an incoming query unless you tell it using a resolver.
同样,您的GraphQL服务器将不知道如何处理传入的查询,除非您使用resolver告诉它。
A resolver tells GraphQL how and where to fetch the data corresponding to a given field. For example, here’s what a resolver for the post
field above could look like (using Apollo’s GraphQL-Tools schema generator):
解析器告诉GraphQL如何以及在何处获取与给定字段相对应的数据。 例如,这是上面post
字段的解析器的外观(使用Apollo的GraphQL-Tools模式生成器):
Query: { post(root, args) { return Posts.find({ id: args.id }); }}
We’re putting the resolver on Query
because we want to query for post
directly at the root level. But you can also have resolvers for sub-fields, such as a post
's author
field:
我们将解析器放在Query
因为我们想直接在根级别查询post
。 但是您也可以为子字段(例如post
的author
字段)提供解析程序:
Query: { post(root, args) { return Posts.find({ id: args.id }); }},Post: { author(post) { return Users.find({ id: post.authorId}) }}
And note that your resolvers are not limited to returning database documents. For example, maybe you want to add a commentsCount
to your Post
type:
请注意,您的解析器不仅限于返回数据库文档。 例如,也许您想在您的Post
类型中添加一个commentsCount
:
Post: { author(post) { return Users.find({ id: post.authorId}) }, commentsCount(post) { return Comments.find({ postId: post.id}).count() }}
The key concept to understand here is that with GraphQL, your API schema and your database schemas are decoupled. In other words, there might not be any author
and commentsCount
fields in our database, but we can “simulate” them through the power of resolvers.
在这里要理解的关键概念是,使用GraphQL, API模式和数据库模式是分离的 。 换句话说,我们的数据库中可能没有任何author
和commentsCount
字段,但是我们可以通过解析器的功能来“模拟”它们。
As you’ve seen you can write any code you want inside a resolver. Which is why you can also make them modify the contents of your database, in which case they’re known as mutation resolvers.
如您所见,您可以在解析器中编写所需的任何代码。 这就是为什么您还可以让他们修改数据库内容的原因,在这种情况下,它们被称为突变解析器。
All this good stuff is made possible by GraphQL’s typed schema system. My goal today is to give you a quick overview more than an exhaustive introduction, so I won’t go into details here.
GraphQL的类型化模式系统使所有这些好东西成为可能。 我今天的目标是为您提供快速的概述,而不是详尽的介绍,因此在此不再赘述。
That being said, I encourage you to check out the GraphQL documentation if you’d like to learn more.
话虽如此,如果您想了解更多信息,我鼓励您查看GraphQL文档 。
Let’s take a break to answer a few common questions.
让我们休息一下,回答一些常见问题。
You there, in the back. Yes, you. I can see you want to ask something. Go ahead, don’t be shy!
你在那里,在后面。 是的,就是你。 我可以看到你想问些问题。 来吧,别害羞!
Not much, really, GraphQL doesn’t have anything to do with graph databases like Neo4j. The “graph” part comes from the idea of crawling across your API graph by using fields and subfields; while “QL” stands for “query language”.
实际上,GraphQL与Neo4j之类的图形数据库没有任何关系。 “图”部分来自通过使用字段和子字段在API图上进行爬网的想法; 而“ QL”代表“查询语言”。
If you haven’t yet bumped into the REST pain points that GraphQL is meant to address, then I would say that’s a good thing!
如果您还没有碰到GraphQL打算解决的REST痛点,那么我会说这是一件好事!
Using GraphQL over REST probably won’t affect your app’s overall user experience that much, so switching to it isn’t a matter of life or death by any means. That being said, I’d definitely recommend trying out GraphQL on a small side project if you ever get the chance.
在REST上使用GraphQL可能不会对您的应用程序的整体用户体验产生太大影响,因此,切换到它绝不是生死攸关的问题。 话虽如此,如果您有机会的话,我绝对建议您在一个小型项目中尝试GraphQL。
Yes you can! Since GraphQL is just a specification, you can use it with any library on any platform, either with a client (for example, Apollo has GraphQL clients for the web, iOS, Angular, etc.) or by making your own calls to a GraphQL server.
是的你可以! 由于GraphQL只是一个规范,您可以将其与任何平台上的任何库一起使用,或者与客户端(例如, Apollo拥有用于Web,iOS,Angular等的GraphQL客户端),或者通过对GraphQL进行自己的调用服务器。
Again, GraphQL is a specification, meaning you can use GraphQL implementations without running a single line of code written by Facebook.
同样,GraphQL是一个规范,这意味着您可以使用GraphQL实现,而无需运行Facebook编写的一行代码。
And while having Facebook’s support is definitely a nice plus for the GraphQL ecosystem, at this point I believe the community is big enough for GraphQL to thrive even if Facebook were to stop using it.
尽管获得Facebook的支持绝对是GraphQL生态系统的一个不错的优势,但在这一点上,我认为,即使Facebook停止使用它,社区也足够使GraphQL蓬勃发展。
Since you write your own resolvers, it’s up to you to address any security concerns at that level.
由于您编写了自己的解析器,因此您有责任在该级别解决所有安全问题。
For example, if you let the client specify a limit
parameter to control the number of documents it receives, you’ll probably want to cap that number to avoid denial-of-service-style attacks where clients requests millions of documents over and over.
例如,如果让客户端指定一个limit
参数来控制其接收的文档数量,则可能需要限制该数量,以避免客户端反复请求数百万个文档的拒绝服务式攻击。
Generally speaking, you’ll need at least two components to run a GraphQL-powered app:
一般来说,您至少需要两个组件才能运行由GraphQL驱动的应用程序:
A GraphQL server that serves your API.
提供您的API的GraphQL服务器 。
A GraphQL client that connects to your endpoint.
连接到端点的GraphQL客户端 。
Read on to learn more about the various options available.
继续阅读以了解更多有关各种可用选项的信息。
Now that you have a fair idea of how GraphQL works, let’s talk about some of the main players in the space.
现在您对GraphQL的工作原理有了一个清晰的认识,让我们来谈谈该领域的一些主要参与者。
The first brick you’ll need is a GraphQL server. GraphQL itself is just a specification after all, so this leaves the door open to a few competing implementations.
您需要的第一个模块是GraphQL服务器。 毕竟GraphQL本身只是一个规范,因此这为一些相互竞争的实现打开了大门。
This is the original reference implementation of GraphQL. You can use it together with express-graphql to create your API server.
这是GraphQL的原始参考实现。 您可以将其与express-graphql一起使用来创建您的API服务器 。
The Apollo team also has their own all-in-one GraphQL server implementation. It’s not as widespread as the original yet, but is very well documented and supported and quickly gaining ground.
Apollo团队还拥有自己的多合一GraphQL服务器实现。 它不像原始版本那样广泛,但是有充分的文档记录和支持,并且很快获得了发展。
GraphQL.org has a list of GraphQL implementations for various other platforms (PHP, Ruby, etc.).
GraphQL.org 列出了其他各种平台 (PHP,Ruby等) 的GraphQL实现 。
Although you can technically query your GraphQL API directly without the need for a dedicated client library, it can definitely make your life easier.
尽管您可以从技术上直接查询GraphQL API而不需要专用的客户端库,但是它绝对可以使您的生活更轻松 。
Relay is Facebook’s own GraphQL toolkit. I haven’t used it myself, but from what I’ve heard it’s mainly tailored to Facebook’s own needs, and might be a bit over-engineered for most usages.
Relay是Facebook自己的GraphQL工具包。 我还没有亲自使用过它,但是据我所知,它主要是针对Facebook自身的需求量身定制的,对于大多数用途而言可能有些过分设计。
The new entrant in this space is Apollo, and it’s quickly taken over. The typical Apollo client stack is composed of two bricks:
这个领域的新进入者是Apollo ,并且很快被接管。 典型的Apollo客户端堆栈由两块砖组成:
Apollo-client, which lets you run GraphQL queries in the browser and store their data (and also has its own devtools extension).
Apollo-client ,它使您可以在浏览器中运行GraphQL查询并存储其数据(还具有自己的devtools扩展名 )。
A connector for your front-end framework of choice (React-Apollo, Angular-Apollo, etc.).
您选择的前端框架( React-Apollo , Angular-Apollo等)的连接器。
Note that by default, Apollo-client stores its data using Redux, which is great since Redux is itself a pretty established state management library with a rich ecosystem.
请注意,默认情况下,Apollo客户端使用Redux来存储其数据,这非常好,因为Redux本身是一个非常完善的具有丰富生态系统的状态管理库。
Even though GraphQL is fairly new, there are already some promising open-source apps making use of it.
即使GraphQL相当新,但已经有一些有前途的开源应用程序在使用它。
First, a disclaimer: I’m the lead maintainer of VulcanJS. I created VulcanJS to let people take advantage of the power of the React/GraphQL stack without having to write so much boilerplate. You can think of it as “Rails for the modern web ecosystem”, in that it lets you build CRUD apps (such as an Instagram clone) in a matter of hours.
首先,免责声明:我是VulcanJS的首席维护者。 我创建了VulcanJS,以使人们无需编写太多样板即可利用React / GraphQL堆栈的功能。 您可以将其视为“现代网络生态系统的轨道”,因为它使您可以在几个小时内构建CRUD应用程序(例如Instagram克隆 )。
Gatsby is a React static site generator, which is now powered by GraphQL as of version 1.0. While that might seem like an odd combination at first, it’s actually quite powerful. During its build process, Gatsby can fetch data from multiple GraphQL APIs, and then use them to create a fully static client-only React app.
Gatsby是一个React静态站点生成器,现在由GraphQL 1.0版本开始支持 。 虽然乍一看似乎很奇怪,但实际上功能非常强大。 在构建过程中,Gatsby可以从多个GraphQL API中获取数据,然后使用它们来创建完全静态的纯客户端专用React应用。
GraphiQL is a very handy in-browser IDE for querying GraphQL endpoints.
GraphiQL是一个非常方便的浏览器内置IDE,用于查询GraphQL端点。
Due to the nested nature of GraphQL queries, a single query can easily trigger dozens of database calls. To avoid taking a performance hit, you can use a batching and caching library such as DataLoader, developed by Facebook.
由于GraphQL查询的嵌套性质,单个查询可以轻松触发数十个数据库调用。 为了避免性能下降,可以使用Facebook开发的批处理和缓存库,例如DataLoader。
Create GraphQL Server is a command line utility that makes it easy to quickly scaffold a GraphQL server powered by a Node server and a Mongo database.
Create GraphQL Server是一个命令行实用程序,可让您轻松快速搭建由Node服务器和Mongo数据库驱动的GraphQL服务器。
Similar to Create GraphQL Server, GraphQL-up lets you quickly bootstrap a new GraphQL back-end powered by GraphCool’s service.
与创建GraphQL服务器类似,通过GraphQL-up,您可以快速引导由GraphCool服务提供支持的新GraphQL后端。
Finally, there are also a number of “GraphQL-backend-as-a-service” companies that take care of the whole server side of things for you, and might be a nice way to dip your toes in the GraphQL ecosystem.
最后,也有许多“ GraphQL后端即服务”公司为您照顾整个服务器端,并且可能是在GraphQL生态系统中扎根的好方法。
A flexible backend platform combining GraphQL and AWS Lambda, with a free developer plan.
结合了GraphQL和AWS Lambda的灵活后端平台以及免费的开发人员计划。
Another GraphQL backend as a service, which also has a free plan. It offers a lot of the same features as Graphcool.
另一个GraphQL后端即服务,也有免费计划。 它提供了许多与Graphcool相同的功能。
There are already quite a few places where you can brush up on GraphQL.
已经有很多地方可以使用GraphQL。
The official GraphQL site has some great documentation to get you started.
GraphQL官方网站上有一些不错的文档,可以帮助您入门。
LearnGraphQL is an interactive course put together by the folks at Kadira.
LearnGraphQL是一个互动的过程中通过在人放在一起Kadira 。
A good follow-up to LearnGraphQL, LearnApollo is a free course made by Graphcool.
作为LearnGraphQL的良好后续,LearnApollo是Graphcool提供的免费课程。
The Apollo blog has tons of detailed, well-written posts about Apollo and GraphQL in general.
一般而言,Apollo博客上有大量详尽,写得很好的有关Apollo和GraphQL的帖子。
A newsletter about all things GraphQL curated by the Graphcool team.
有关Graphcool团队策划的GraphQL一切的新闻通讯。
Another great newsletter, which also covers React and Meteor in addition to GraphQL.
另一个重要新闻通讯,除了GraphQL之外,还涵盖了React和Meteor。
A tutorial series teaching you how to build an Intercom clone using GraphQL.
一个教程系列,教您如何使用GraphQL构建对讲机克隆。
A pretty exhaustive list of GraphQL links and resources.
GraphQL链接和资源的详尽列表。
So how do you put your newly acquired GraphQL knowledge in practice? Here are a few recipes you can try:
那么,如何将新获得的GraphQL知识付诸实践呢? 您可以尝试以下一些食谱:
If you’re already familiar with Next.js and React, this example will let you set up your GraphQL endpoint using Graphcool, and then query it using Apollo.
如果您已经熟悉Next.js和React,则此示例将使您可以使用Graphcool设置GraphQL端点,然后使用Apollo查询它。
The Vulcan tutorial will take you through setting up a simple GraphQL data layer, both on the server and client. Since Vulcan is an all-in-one platform, it’s a nice way to get started without any setup. If you need help, don’t hesitate to drop by our Slack channel!
Vulcan教程将引导您在服务器和客户端上设置一个简单的GraphQL数据层。 由于Vulcan是一个多平台平台,因此这是无需任何设置即可入门的好方法。 如果您需要帮助,请随时访问我们的Slack频道 !
The Chroma blog has a six-part tutorial on building a React/GraphQL app following a component-driven development approach.
Chroma博客有一个由六部分组成的教程 ,内容涉及按照组件驱动的开发方法构建React / GraphQL应用程序。
GraphQL might seem complex at first because it’s a technology that reaches across many areas of modern development. But if you take the time to understand the underlying concepts, I think you’ll find out that a lot of it just makes sense.
GraphQL乍看起来可能很复杂,因为它是一项涉及现代开发许多领域的技术。 但是,如果您花时间来理解基本概念,那么我想您会发现其中的许多内容都是有道理的。
So whether you end up actually using it or not, I believe it’s worth taking the time to familiarize yourself with GraphQL. More and more companies and frameworks are adopting it, and it might very well end up becoming one of the key building blocks of the web over the next few years.
因此,不管您最终是否实际使用它,我都认为值得花时间熟悉GraphQL。 越来越多的公司和框架正在采用它,并且在接下来的几年中,它很可能最终成为Web的关键构建块之一。
Agree? Disagree? Questions? Just let me know here in the comments. And if you’ve enjoyed this article, please consider ?ing and sharing it!
同意? 不同意? 有什么问题吗 请在评论中让我知道。 如果您喜欢这篇文章,请考虑阅读并分享!
翻译自: https://www.freecodecamp.org/news/so-whats-this-graphql-thing-i-keep-hearing-about-baf4d36c20cf/
graphql是什么