Home > Article > Web Front-end > Understanding GraphQL: Introduction to GraphQL
GraphQL is an exciting new API for ad hoc queries and operations. It is very flexible and offers many benefits. It is particularly suitable for exposing data organized in graph and tree forms. Facebook developed GraphQL in 2012 and open sourced it in 2015.
It has grown rapidly and become one of the hottest technologies. Many innovative companies have adopted and used GraphQL in production. In this tutorial you will learn:
GraphQL is at its best when your data is organized in a hierarchy or graph and the front end wants to access different subsets of that hierarchy or graph. Consider an application that exposes the NBA. You have teams, players, coaches, championships, and tons of information on each. Here are some sample queries:
I could ask hundreds of queries like this. Imagine having to design an API that exposes all of these queries to the front end and be able to easily extend the API with new query types when your users or product managers come up with new and exciting query content.
This is not a trivial matter. GraphQL was designed to solve this exact problem, and with a single API endpoint, it provides tremendous functionality, as you'll soon see.
Before we get into the specifics of GraphQL, let’s compare it to REST, which is currently the most popular type of web API.
REST follows a resource-oriented model. If our resources were players, coaches, and teams, we might have endpoints like this:
Typically, endpoints without ids only return a list of ids, while endpoints with ids return complete information about a resource. Of course, you could design the API in other ways (e.g. the /players endpoint might also return each player's name or all the information about each player).
In a dynamic environment, the problem with this approach is that you either under-fetch (e.g., you only get the id and need more information), or over-fetch (e.g., you are only interested in the name).
These are difficult questions. When not getting enough, if you get 100 ids, you need to make 100 separate API calls to get each player's information. When you overfetch, you waste a lot of backend time and network bandwidth preparing and transmitting large amounts of data that you don't need.
There are multiple ways to solve this problem via REST. You can design many custom endpoints, each returning exactly the data you need. This solution is not scalable. Keeping APIs consistent is difficult. It's hard to evolve it. It's difficult to document and use. It's difficult to maintain it when there's a lot of overlap between these custom endpoints.
Consider these additional endpoints:
Another approach is to keep a small number of common endpoints but provide a large number of query parameters. This solution avoids the problem of multiple endpoints, but it violates the principles of the REST model and is difficult to develop and maintain consistently.
You could say that GraphQL has taken this approach to its limit. It does not consider explicitly defined resources, but rather a subgraph of the entire domain.
GraphQL models domains using a type system consisting of types and properties. Every property has a type. The property type can be one of the basic types provided by GraphQL, such as ID, String, and Boolean, or it can be a user-defined type. The nodes of a graph are user-defined types, and the edges are attributes with user-defined types.
For example, if the "player" type has a "team" attribute of the "team" type, it means that there is an edge from each player node to the team node. All types are defined in a schema that describes the GraphQL domain object model.
This is a very simplified architecture for the NBA domain. The player has a name, the team he is most associated with (yes, I know players sometimes move from one team to another), and the number of championships the player has won.
Teams have names, rosters, and the number of championships the team has won.
type Player { id: ID name: String! team: Team! championshipCount: Integer! } type Team { id: ID name: String! players: [Player!]! championshipCount: Integer! }
There are also predefined entry points. They are query, change and subscribe. The frontend communicates with the backend through entry points and can be customized as needed.
This is a simple query that returns all players:
type Query { allPlayers: [Player!]! }
感叹号表示该值不能为空。对于 allPlayers
查询,它可以返回空列表,但不能返回 null。另外,这意味着列表中不能有空玩家(因为它包含 Player!)。
这是一个基于 Node-Express 的成熟 GraphQL 服务器。它有一个内存中的硬编码数据存储。通常,数据将位于数据库中或从其他服务获取。数据定义如下(如果您最喜欢的球队或球员未能入选,请提前致歉):
let data = { "allPlayers": { "1": { "id": "1", "name": "Stephen Curry", "championshipCount": 2, "teamId": "3" }, "2": { "id": "2", "name": "Michael Jordan", "championshipCount": 6, "teamId": "1" }, "3": { "id": "3", "name": "Scottie Pippen", "championshipCount": 6, "teamId": "1" }, "4": { "id": "4", "name": "Magic Johnson", "championshipCount": 5, "teamId": "2" }, "5": { "id": "5", "name": "Kobe Bryant", "championshipCount": 5, "teamId": "2" }, "6": { "id": "6", "name": "Kevin Durant", "championshipCount": 1, "teamId": "3" } }, "allTeams": { "1": { "id": "1", "name": "Chicago Bulls", "championshipCount": 6, "players": [] }, "2": { "id": "2", "name": "Los Angeles Lakers", "championshipCount": 16, "players": [] }, "3": { "id": "3", "name": "Golden State Warriors", "championshipCount": 5, "players": [] } } }
我使用的库是:
const express = require('express'); const graphqlHTTP = require('express-graphql'); const app = express(); const { buildSchema } = require('graphql'); const _ = require('lodash/core');
这是构建架构的代码。请注意,我向 allPlayers
根查询添加了几个变量。
schema = buildSchema(` type Player { id: ID name: String! championshipCount: Int! team: Team! } type Team { id: ID name: String! championshipCount: Int! players: [Player!]! } type Query { allPlayers(offset: Int = 0, limit: Int = -1): [Player!]! }`
关键部分来了:连接查询并实际提供数据。 rootValue
对象可能包含多个根。
这里,只有 allPlayers
。它从参数中提取偏移量和限制,对所有玩家数据进行切片,然后根据团队 ID 设置每个玩家的团队。这使得每个玩家都是一个嵌套对象。
rootValue = { allPlayers: (args) => { offset = args['offset'] limit = args['limit'] r = _.values(data["allPlayers"]).slice(offset) if (limit > -1) { r = r.slice(0, Math.min(limit, r.length)) } _.forEach(r, (x) => { data.allPlayers[x.id].team = data.allTeams[x.teamId] }) return r }, }
最后,这是 graphql
端点,传递架构和根值对象:
app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: rootValue, graphiql: true })); app.listen(3000); module.exports = app;
将 graphiql
设置为 true
使我们能够使用出色的浏览器内 GraphQL IDE 来测试服务器。我强烈推荐它来尝试不同的查询。
万事俱备。让我们导航到 http://localhost:3000/graphql 并享受一些乐趣。
我们可以从简单的开始,只包含玩家姓名列表:
query justNames { allPlayers { name } } Output: { "data": { "allPlayers": [ { "name": "Stephen Curry" }, { "name": "Michael Jordan" }, { "name": "Scottie Pippen" }, { "name": "Magic Johnson" }, { "name": "Kobe Bryant" }, { "name": "Kevin Durant" } ] } }
好吧。我们这里有一些超级巨星。毫无疑问。让我们尝试一些更奇特的东西:从偏移量 4 开始,有 2 名玩家。对于每个球员,返回他们的名字和他们赢得的冠军数量以及他们的球队名称和球队赢得的冠军数量。
query twoPlayers { allPlayers(offset: 4, limit: 2) { name championshipCount team { name championshipCount } } } Output: { "data": { "allPlayers": [ { "name": "Kobe Bryant", "championshipCount": 5, "team": { "name": "Los Angeles Lakers", "championshipCount": 16 } }, { "name": "Kevin Durant", "championshipCount": 1, "team": { "name": "Golden State Warriors", "championshipCount": 5 } } ] } }
所以科比·布莱恩特随湖人队赢得了 5 个总冠军,湖人队总共获得了 16 个总冠军。凯文·杜兰特在勇士队只赢得了一次总冠军,而勇士队总共赢得了五次总冠军。
魔术师约翰逊无疑是场上的魔术师。但如果没有他的朋友卡里姆·阿卜杜勒·贾巴尔,他不可能做到这一点。让我们将 Kareem 添加到我们的数据库中。我们可以定义 GraphQL 突变来执行从图表中添加、更新和删除数据等操作。
首先,让我们向架构添加突变类型。它看起来有点像函数签名:
type Mutation { createPlayer(name: String, championshipCount: Int, teamId: String): Player }
然后,我们需要实现它并将其添加到根值中。该实现只是获取查询提供的参数并将一个新对象添加到 data['allPlayers']
。它还确保正确设置团队。最后,它返回新的玩家。
createPlayer: (args) => { id = (_.values(data['allPlayers']).length + 1).toString() args['id'] = id args['team'] = data['allTeams'][args['teamId']] data['allPlayers'][id] = args return data['allPlayers'][id] },
要实际添加 Kareem,我们可以调用突变并查询返回的玩家:
mutation addKareem { createPlayer(name: "Kareem Abdul-Jabbar", championshipCount: 6, teamId: "2") { name championshipCount team { name } } } Output: { "data": { "createPlayer": { "name": "Kareem Abdul-Jabbar", "championshipCount": 6, "team": { "name": "Los Angeles Lakers" } } } }
这是一个关于突变的黑暗小秘密......它们实际上与查询完全相同。您可以在查询中修改数据,并且可能只从突变中返回数据。 GraphQL 不会查看您的代码。查询和突变都可以接受参数并返回数据。它更像是语法糖,可以使您的架构更具人类可读性。
订阅是 GraphQL 的另一个杀手级功能。通过订阅,客户端可以订阅每当服务器状态发生变化时就会触发的事件。订阅是后来引入的,不同的框架以不同的方式实现。
GraphQL 将验证针对架构的每个查询或突变。当输入数据具有复杂形状时,这是一个巨大的胜利。您不必编写烦人且脆弱的验证代码。 GraphQL 将为您处理好它。
您可以检查和查询当前架构本身。这为您提供了动态发现架构的元能力。下面是一个返回所有类型名称及其描述的查询:
query q { __schema { types { name description } }
GraphQL 是一项令人兴奋的新 API 技术,与 REST API 相比,它具有许多优势。它背后有一个充满活力的社区,更不用说Facebook了。我预测它将很快成为前端的主要内容。试一试。你会喜欢的。
The above is the detailed content of Understanding GraphQL: Introduction to GraphQL. For more information, please follow other related articles on the PHP Chinese website!