当前位置: 首页 > 工具软件 > GraphQL > 使用案例 >

graphql_GraphQL简介

欧阳何平
2023-12-01

graphql

什么是GraphQL (What is GraphQL)

GraphQL is the new frontier in APIs (Application Programming Interfaces) design, and in how we build and consume them.

GraphQL是API( 应用程序编程接口 )设计以及我们如何构建和使用它们的新领域。

It’s a query language, and a set of server-side runtimes (implemented in various backend languages) for executing queries. It’s not tied to a specific technology, but you can implement it in any language.

它是一种查询语言,还有一组用于执行查询的服务器端运行时(以各种后端语言实现)。 它与特定技术无关,但是您可以使用任何语言来实现它。

It is a methodology that directly competes with REST (REpresentational State Transfer) APIs, much like REST competed with SOAP at first.

它是一种直接与REST ( 代表性状态转移 )API 竞争的方法,就像REST首先与SOAP竞争一样。

And as we’ll see, it’s very different from REST. It creates a whole new dimension for API design.

正如我们将看到的,它与REST有很大的不同。 它为API设计创建了一个全新的维度。

GraphQL was developed at Facebook, like many of the technologies that are shaking the JavaScript world lately, like React and React Native, and it was publicly launched in 2015 - although Facebook used it internally for a few years before.

GraphQL是在Facebook上开发的 ,就像最近撼动JavaScript世界的许多技术一样,例如React和React Native,它于2015年公开发布 -尽管Facebook在内部使用了几年。

Many big companies are adopting GraphQL beside Facebook, including GitHub, Pinterest, Twitter, Sky, The New York Times, Shopify, Yelp and thousands many other.

许多大公司都在Facebook旁边采用GraphQL,包括GitHub,Pinterest,Twitter,Sky,《纽约时报》,Shopify,Yelp等数千种。

I’ve first been in touch with GraphQL when GitHub decided to implement the v4 of their API using that technology, and I joined their beta program. That’s when I discovered it’s a game changer in many aspects.

当GitHub决定使用该技术实现其API的v4时,我第一次与GraphQL联系,我加入了他们的beta程序。 从那时起,我发现它在许多方面都改变了游戏规则。

这个怎么运作 (How it works)

GraphQL exposes a single endpoint from your server.

GraphQL从您的服务器公开一个端点

You send a query to that endpoint by using a special Query Language syntax. That query is just a string.

可以使用特殊的查询语言语法将查询发送到该端点 。 该查询只是一个字符串

The server responds to a query by providing a JSON object.

服务器通过提供JSON对象来响应查询。

Let’s see a first example of such a query. This query gets the name of a person with id=1:

让我们看看这种查询的第一个例子。 此查询获取id=1的人的名字:

GET /graphql?query={ person(id: "1") { name } }

or:

要么:

{
  person(id: "1") {
    name
  }
}

We’ll get this JSON response back:

我们将返回此JSON响应:

{
  "name": "Tony"
}

Let’s add a bit more complexity: we get the name of the person, and the city where the person lives, by extracting it from the address object. We don’t care about other details of the address, and the server does not return them back to us because we didn’t ask for them:

让我们增加一点复杂性:通过从address对象中提取人的名字,以及人的居住城市。 我们不在乎地址的其他详细信息,并且服务器不会将它们退还给我们,因为我们没有要求它们:

GET /graphql?query={ person(id: "1") { name, address { city } } }

or

要么

{
  person(id: "1") {
    name
    address {
      city
    }
  }
}

This is what we get back:

这就是我们得到的:

{
  "name": "Tony",
  "address": {
    "city": "York"
  }
}

As you can see the data we get is basically the same structure of the request we sent, filled with values that were fetched.

如您所见,我们获取的数据基本上与我们发送的请求的结构相同,其中填充了所获取的值。

GraphQL查询 (GraphQL Queries)

In this section you’ll learn how is a GraphQL query composed.

在本节中,您将学习如何构成GraphQL查询。

The concepts I’ll introduce are

我将介绍的概念是

  • fields and arguments

    字段和参数
  • aliases

    别名
  • fragments

    碎片

字段和参数 (Fields and arguments)

Take this simple GraphQL query:

进行以下简单的GraphQL查询:

{
  person(id: "1") {
    name
  }
}

In this query you see 2 fields, person and name, and 1 argument.

在此查询中,您看到2个字段personname ,以及1个参数

The field person returns an Object which has another field in it, a String.

现场person返回其中包含另一个字段StringObject

The argument allows us to specify which person we want to reference. We pass an id, but we could as well pass a name argument, if the API we talk to has the option to find a person by name.

该参数允许我们指定要引用的人。 我们传递一个id ,但是我们也可以传递一个name参数,如果与我们交谈的API可以选择按名称查找人。

Arguments are not limited to any particular field. We could have a friends field in person that lists the friends of that person, and it could have a limit argument, to specify how many we want the API to return:

参数不限于任何特定字段。 我们可以person一个friends字段,其中列出该person的朋友,并且可以有一个limit参数,以指定我们希望API返回多少:

{
  person(id: "1") {
    name
    friends(limit: 100)
  }
}

别名 (Aliases)

You can ask the API to return a field with a different name. For example here you request the name field, but you want it returned as fullname:

您可以要求API返回具有不同名称的字段。 例如,您在此处请求name字段,但希望它以fullname name返回:

{
  owner: person(id: "1") {
    fullname: name
  }
}

will return

将返回

{
  "data": {
    "owner": {
      "fullname": "Tony"
    }
  }
}

This feature, beside creating more ad-hoc naming for your client code, in case you need, is the only thing that can make the query work if you need to reference the same endpoint 2 times in the same query:

如果需要,此功能除了为您的客户端代码创建更多临时命名之外,如果您需要在同一查询中两次引用相同的端点 ,则该功能也是唯一可以使查询正常工作的功能:

{
  owner: person(id: "1") {
    fullname: name
  }
  first_employee: person(id: "2") {
    fullname: name
  }
}

碎片 (Fragments)

In the above query we replicated the person structure. Fragments allow us to specify the structure just once (a very useful thing when you have many similar fields):

在上面的查询中,我们复制了人员结构。 片段允许我们只指定一次结构(当您有许多相似字段时,这非常有用):

{
  owner: person(id: "1") {
    ...personFields
  }
  first_employee: person(id: "2") {
    ...personFields
  }
}

fragment personFields on person {
  fullname: name
}

GraphQL变量 (GraphQL Variables)

More complex GraphQL queries need to use variables, a way to dynamically specify a value that is used inside a query.

更复杂的GraphQL查询需要使用变量 ,这是一种动态指定在查询中使用的的方法。

In this case we added the person id as a string inside the query:

在这种情况下,我们将人员ID作为字符串添加到查询中:

{
  owner: person(id: "1") {
    fullname: name
  }
}

The id will most probably change dynamically in our program, so we need a way to pass it, and not with string interpolation.

id很可能会在我们的程序中动态更改,因此我们需要一种传递它的方法,而不是使用字符串插值

With variables, the same query can be written as this:

使用变量,可以这样编写相同的查询:

query GetOwner($id: String) {
  owner: person(id: $id) {
    fullname: name
  }
}

{
  "id": "1"
}

In this snippet we have assigned the GetOwner name to our query. Think of it as named functions, while previously you had an anonymous function. Named queries are useful when you have lots of queries in your application.

在此代码段中,我们已将GetOwner名称分配给我们的查询。 可以将其视为命名函数,而以前您拥有匿名函数。 当您的应用程序中有很多查询时,命名查询很有用。

The query definition with the variables looks like a function definition, and it works in an equivalent way.

具有变量的查询定义看起来像函数定义,并且以等效方式工作。

使变量为必需 (Making variables required)

Appending a ! to the type:

附加一个! 类型:

query GetOwner($id: String!)

instead of $id: String will make the $id variable required.

而不是$id: String将使$ id变量成为必需。

指定变量的默认值 (Specifying a default value for a variable)

You can specify a default value using this syntax:

您可以使用以下语法指定默认值:

query GetOwner($id: String = "1")

GraphQL指令 (GraphQL Directives)

Directives let you include or exclude a field if a variable is true or false.

指令允许您在变量为true或false时包含或排除字段。

query GetPerson($id: String) {
  person(id: $id) {
    fullname: name,
    address: @include(if: $getAddress) {
      city
      street
      country
    }
  }
}

{
  "id": "1",
  "getAddress": false
}

In this case if getAddress variable we pass is true, we also get the address field, otherwise not.

在这种情况下,如果我们传递的getAddress变量为true,那么我们还将获取地址字段,否则返回。

We have 2 directives available: include, which we have just seen (includes if true), and skip, which is the opposite (skips if true)

我们有2个可用的指令: include ,我们刚刚看过(如果为true则包含),而skip ,则相反(如果为true则跳过)

@include(如果:布尔值) (@include(if: Boolean))

query GetPerson($id: String) {
  person(id: $id) {
    fullname: name,
    address: @include(if: $getAddress) {
      city
      street
      country
    }
  }
}

{
  "id": "1",
  "getAddress": false
}

@skip(如果是布尔值) (@skip(if: Boolean))

query GetPerson($id: String) {
  person(id: $id) {
    fullname: name,
    address: @skip(if: $excludeAddress) {
      city
      street
      country
    }
  }
}

{
  "id": "1",
  "excludeAddress": false
}

翻译自: https://flaviocopes.com/graphql/

graphql

 类似资料: