graphql入門
by Leonardo Maldonado
萊昂納多·馬爾多納多(Leonardo Maldonado)
GraphQL入門指南 (A Beginner’s Guide to GraphQL)
One of the most commonly discussed terms today is the API. A lot of people don’t know exactly what an API is. Basically, API stands for Application Programming Interface. It is, as the name says, an interface with which people — developers, users, consumers — can interact with data.
API是當今最常用的術語之一。 很多人不確切知道什么是API。 API基本上代表應用程序編程接口。 顧名思義,它是人們(開發人員,用戶,消費者)可以與數據進行交互的接口。
You can think of an API as a bartender. You ask the bartender for a drink, and they give you what you wanted. Simple. So why is that a problem?
您可以將API視為調酒師。 您要求酒保喝一杯,他們會給您您想要的。 簡單。 那為什么會有問題呢?
Since the start of the modern web, building APIs has not been as hard as it sounds. But learning and understanding APIs was. Developers form the majority of the people that will use your API to build something or just consume data. So your API should be as clean and as intuitive as possible. A well-designed API is very easy to use and learn. It’s also intuitive, a good point to keep in mind when you’re starting to design your API.
自從現代網絡開始以來,構建API并不像聽起來那樣困難。 但是學習和理解API卻是。 開發人員構成將使用您的API來構建某些東西或僅使用數據的大多數人。 因此,您的API應該盡可能簡潔明了。 精心設計的API非常易于使用和學習。 它也很直觀,這是在開始設計API時要牢記的一個好點。
We’ve been using REST to build APIs for a long time. Along with that comes some problems. When building an API using REST design, you’ll face some problems like:
長期以來,我們一直在使用REST來構建API。 隨之而來的是一些問題。 使用REST設計構建API時,您會遇到一些問題,例如:
1) you’ll have a lot of endpoints
1)您將有很多端點
2) it’ll be much harder for developers to learn and understand your API
2)開發人員將很難學習和理解您的API
3) there is over- and under-fetching of information
3)信息獲取過多和不足
To solve these problems, Facebook created GraphQL. Today, I think GraphQL is the best way to build APIs. This article will tell you why you should start to learn it today.
為了解決這些問題,Facebook創建了GraphQL。 今天,我認為GraphQL是構建API的最佳方法。 本文將告訴您為什么今天應該開始學習它。
In this article, you’re going to learn how GraphQL works. I’m going to show you how to create a very well-designed, efficient, powerful API using GraphQL.
在本文中,您將學習GraphQL的工作方式。 我將向您展示如何使用GraphQL創建一個設計良好,高效,強大的API。
You’ve probably already heard about GraphQL, as a lot of people and companies are using it. Since GraphQL is open-source, its community has grown huge.
您可能已經聽說過GraphQL,因為許多人和公司正在使用它。 由于GraphQL是開源的,因此其社區已經變得龐大。
Now, it’s time for you start to learn in practice how GraphQL works and all about its magic.
現在,是時候開始在實踐中學習GraphQL的工作原理以及其神奇之處了。
什么是GraphQL? (What is GraphQL?)
GraphQL is an open-source query language developed by Facebook. It provides us with a more efficient way design, create, and consume our APIs. Basically, it’s the replacement for REST.
GraphQL是Facebook開發的一種開源查詢語言。 它為我們提供了一種更有效的方式來設計,創建和使用我們的API。 基本上,它是REST的替代品。
GraphQL has a lot of features, like:
GraphQL具有很多功能,例如:
You write the data that you want, and you get exactly the data that you want. No more over-fetching of information as we are used to with REST.
您寫入所需的數據,并且您將確切獲得所需的數據。 不再像過去使用REST那樣過度獲取信息 。
It gives us a single endpoint, no more version 2 or version 3 for the same API.
它為我們提供了一個終結點 ,對于同一API,不再有版本2或版本3。
GraphQL is strongly-typed, and with that you can validate a query within the GraphQL type system before execution. It helps us build more powerful APIs.
GraphQL是強類型的 ,使用它可以在執行之前在GraphQL類型系統內驗證查詢。 它可以幫助我們構建更強大的API。
This is a basic introduction to GraphQL — why it’s so powerful and why it’s gaining a lot of popularity these days. If you want to learn more about it, I recommend you to go the GraphQL website and check it out.
這是對GraphQL的基本介紹-為什么它如此強大,以及為什么它如今越來越受歡迎。 如果您想了解更多信息,建議您訪問GraphQL網站并進行檢查。
入門 (Getting started)
The main objective in this article is not to learn how to set up a GraphQL server, so we’re not getting deep into that for now. The objective is to learn how GraphQL works in practice, so we’re gonna use a zero-configuration GraphQL server called ?? Graphpack.
本文的主要目的不是學習如何設置GraphQL服務器,因此我們暫時不對此進行深入研究。 我們的目標是學習GraphQL如何在實踐中,所以我們要使用一種叫做??零配置GraphQL服務器Graphpack 。
To start our project, we’re going to create a new folder and you can name it whatever you want. I’m going to name it graphql-server
:
要開始我們的項目,我們將創建一個新文件夾,您可以根據需要命名它。 我將其命名為graphql-server
:
Open your terminal and type:
打開您的終端并輸入:
mkdir graphql-server
Now, you should have npm or yarn installed in your machine. If you don’t know what these are, npm and yarn are package managers for the JavaScript programming language. For Node.js, the default package manager is npm.
現在,您應該在機器中安裝了npm或yarn 。 如果您不知道這些是什么,則npm和yarn是JavaScript編程語言的包管理器。 對于Node.js,默認的軟件包管理器是npm 。
Inside your created folder type the following command:
在創建的文件夾中,鍵入以下命令:
npm init -y
Or if you use yarn:
或者,如果您使用紗線:
yarn init
npm will create a package.json
file for you, and all the dependencies that you installed and your commands will be there.
npm將為您創建一個package.json
文件,所有已安裝的依賴項和命令都將存在。
So now, we’re going to install the only dependency that we’re going to use.
因此,現在,我們將安裝將要使用的唯一依賴項 。
??Graphpack lets you create a GraphQL server with zero configuration. Since we’re just starting with GraphQL, this will help us a lot to go on and learn more without getting worried about a server configuration.
?? Graphpack可以讓你創建一個GraphQL 服務器零配置 。 由于我們只是從GraphQL開始,因此這將幫助我們繼續學習并了解更多信息,而不必擔心服務器配置。
In your terminal, inside your root folder, install it like this:
在終端的根文件夾中,按以下方式安裝:
npm install --save-dev graphpack
Or, if you use yarn, you should go like this:
或者,如果您使用毛線,則應如下所示:
yarn add --dev graphpack
After Graphpack is installed, go to our scripts in package.json
file, and put the following code there:
安裝Graphpack后,轉到package.json
文件中的腳本,并在其中放置以下代碼:
"scripts": {"dev": "graphpack","build": "graphpack build"
}
We’re going to create a folder called src
, and it’s going to be the only folder in our entire server.
我們將創建一個名為src
的文件夾,它將是整個服務器中唯一的文件夾。
Create a folder called src
, after that, inside our folder, we’re going to create three files only.
創建一個名為src
的文件夾,然后在我們的文件夾內,僅創建三個文件。
Inside our src
folder create a file called schema.graphql
. Inside this first file, put the following code:
在我們的src
文件夾中,創建一個名為schema.graphql
的文件。 在第一個文件中,放入以下代碼:
type Query {hello: String
}
In this schema.graphql
file is going to be our entire GraphQL schema. If you don’t know what it is, I’ll explain later — don't worry.
在這個schema.graphql
文件schema.graphql
成為我們的整個GraphQL模式。 如果您不知道它是什么,我待會兒解釋-不用擔心。
Now, inside our src
folder, create a second file. Call it resolvers.js
and, inside this second file, put the following code:
現在,在我們的src
文件夾中,創建另一個文件。 將其resolvers.js
并在第二個文件中放入以下代碼:
import { users } from "./db";const resolvers = {Query: {hello: () => "Hello World!"}
};export default resolvers;
This resolvers.js
file is going to be the way we provide the instructions for turning a GraphQL operation into data.
此resolvers.js
文件將成為我們提供的將GraphQL操作轉換為數據的說明的方式。
And finally, inside your src
folder, create a third file. Call this db.js
and, inside this third file, put the following code:
最后,在您的src
文件夾中,創建第三個文件。 調用此db.js
并在第三個文件中放入以下代碼:
export let users = [{ id: 1, name: "John Doe", email: "john@gmail.com", age: 22 },{ id: 2, name: "Jane Doe", email: "jane@gmail.com", age: 23 }
];
In this tutorial we’re not using a real-world database. So this db.js
file is going to simulate a database, just for learning purposes.
在本教程中,我們不使用真實數據庫。 因此,此db.js
文件將用于模擬數據庫,僅用于學習目的。
Now our src
folder should look like this:
現在,我們的src
文件夾應如下所示:
src|--db.js|--resolvers.js|--schema.graphql
Now, if you run the command npm run dev
or, if you’re using yarn, yarn dev
, you should see this output in your terminal:
現在,如果您運行命令npm run dev
或者如果您使用的是yarn, yarn dev
,那么您應該在終端中看到以下輸出:
You can now go to localhost:4000
. This means that we’re ready to go and start writing our first queries, mutations, and subscriptions in GraphQL.
您現在可以轉到localhost:4000
。 這意味著我們已經準備好開始在GraphQL中編寫我們的第一個查詢,變異和訂閱。
You see the GraphQL Playground, a powerful GraphQL IDE for better development workflows. If you want to learn more about GraphQL Playground, click here.
您會看到GraphQL Playground,這是一個功能強大的GraphQL IDE,可用于更好的開發工作流程。 如果您想了解有關GraphQL Playground的更多信息, 請單擊此處 。
架構圖 (Schema)
GraphQL has its own type of language that’s used to write schemas. This is a human-readable schema syntax called Schema Definition Language (SDL). The SDL will be the same, no matter what technology you’re using — you can use this with any language or framework that you want.
GraphQL有自己的語言類型,用于編寫模式。 這是一種人類可讀的架構語法,稱為架構定義語言(SDL)。 無論您使用哪種技術,SDL都是相同的-您可以將其與所需的任何語言或框架一起使用。
This schema language its very helpful because it’s simple to understand what types your API is going to have. You can understand it just by looking right it.
這種模式語言非常有用,因為它很容易理解您的API將要具有的類型。 您可以通過正確查看它來理解它。
種類 (Types)
Types are one of the most important features of GraphQL. Types are custom objects that represent how your API is going to look. For example, if you’re building a social media application, your API should have types such as Posts
, Users
, Likes
, Groups
.
類型是GraphQL的最重要功能之一。 類型是自定義對象,代表您的API外觀。 例如,如果您正在構建社交媒體應用程序,則您的API應該具有諸如Posts
, Users
, Likes
, Groups
類的類型。
Types have fields, and these fields return a specific type of data. For example, we’re going to create a User type, we should have some name
, email
, and age
fields. Type fields can be anything, and always return a type of data as Int, Float, String, Boolean, ID, a List of Object Types, or Custom Objects Types.
類型具有字段,并且這些字段返回特定類型的數據。 例如,我們要創建一個User類型,我們應該有一些name
, email
和age
字段。 類型字段可以是任何內容,并且總是返回數據類型,例如Int,Float,String,Boolean,ID,Object Types列表或Custom Objects Types 。
So now to write our first Type, go to your schema.graphql
file and replace the type Query that is already there with the following:
因此,現在要編寫我們的第一個Type,請轉到您的schema.graphql
文件,并用以下內容替換已經存在的Query類型:
type User {id: ID!name: String!email: String!age: Int
}
Each User
is going to have an ID
, so we gave it an ID
type. User
is also going to have a name
and email
, so we gave it a String
type, and an age
, which we gave an Int
type. Pretty simple, right?
每個User
都有一個ID
,因此我們給了它一個ID
類型。 User
還將具有name
和email
,因此我們給了它一個String
類型,一個age
,我們給了一個Int
類型。 很簡單,對吧?
But, what about those !
at the end of every line? The exclamation point means that the fields are non-nullable, which means that every field must return some data in each query. The only nullable field that we’re going to have in our User
type will be age
.
但是,那些!
在每一行的末尾? 感嘆號表示字段不可為空 ,這意味著每個字段必須在每個查詢中返回一些數據。 我們將在User
類型中唯一擁有的null字段將是age
。
In GraphQL, you will deal with three main concepts:
在GraphQL中,您將處理三個主要概念:
queries — the way you’re going to get data from the server.
查詢 -您將從服務器獲取數據的方式。
mutations — the way you’re going to modify data on the server and get updated data back (create, update, delete).
突變 -修改服務器上的數據并取回更新的數據(創建,更新,刪除)的方式。
subscriptions — the way you’re going to maintain a real-time connection with the server.
訂閱 -與服務器保持實時連接的方式。
I’m going to explain all of them to you. Let’s start with Queries.
我將向您解釋所有這些內容。 讓我們從查詢開始。
查詢 (Queries)
To explain this in a simple way, queries in GraphQL are how you’re going to get data. One of the most beautiful things about queries in GraphQL is that you are just going to get the exact data that you want. No more, no less. This has a huge positive impact in our API — no more over-fetching or under-fetching information as we had with REST APIs.
為了以一種簡單的方式說明這一點,GraphQL中的查詢是您如何獲取數據的方式。 GraphQL中關于查詢的最美麗的事情之一就是您將獲得所需的確切數據。 不多不少。 這對我們的API產生了巨大的積極影響-不再像我們使用REST API那樣過度獲取或不足獲取信息。
We’re going to create our first type Query in GraphQL. All our queries will end up inside this type. So to start, we’ll go to our schema.graphql
and write a new type called Query
:
我們將在GraphQL中創建第一個類型的查詢。 我們所有的查詢都將以這種類型結束。 首先,我們將轉到schema.graphql
并編寫一個名為Query
的新類型:
type Query {users: [User!]!
}
It’s very simple: the users
query will return to us an array of one or more Users
. It will not return null, because we put in the !
, which means it’s a non-nullable query. It should always return something.
很簡單: users
查詢將返回給我們一個包含一個或多個Users
的數組。 它不會返回null,因為我們輸入了!
,這意味著它是一個不可為空的查詢。 它應該總是返回一些東西。
But we could also return a specific user. For that we’re going to create a new query called user
. Inside our Query
type, put the following code:
但是我們也可以返回特定的用戶。 為此,我們將創建一個名為user
的新查詢。 在我們的Query
類型中,放入以下代碼:
user(id: ID!): User!
Now our Query
type should look like this:
現在,我們的Query
類型應如下所示:
type Query {users: [User!]!user(id: ID!): User!
}
As you see, with queries in GraphQL we can also pass arguments. In this case, to query for a specific user
, we’re going to pass its ID
.
如您所見,通過GraphQL中的查詢,我們還可以傳遞參數。 在這種情況下,要查詢特定user
,我們將傳遞其ID
。
But, you may be wondering: how does GraphQL know where get the data? That’s why we should have a resolvers.js
file. That file tells GraphQL how and where it's going to fetch the data.
但是,您可能想知道:GraphQL如何知道從何處獲取數據? 這就是為什么我們應該有一個resolvers.js
文件的原因。 該文件告訴GraphQL如何以及在何處獲取數據。
First, go to our resolvers.js
file and import the db.js
that we just created a few moments ago. Your resolvers.js
file should look like this:
首先,轉到我們的resolvers.js
文件,并導入我們剛才創建的db.js
您的resolvers.js
文件應如下所示:
import { users } from "./db";const resolvers = {Query: {hello: () => "Hello World!"}
};export default resolvers;
Now, we’re going to create our first Query. Go to your resolvers.js
file and replace the hello
function. Now your Query type should look like this:
現在,我們將創建第一個查詢。 轉到您的resolvers.js
文件,并替換hello
函數。 現在,您的查詢類型應如下所示:
import { users } from "./db";const resolvers = {Query: {user: (parent, { id }, context, info) => {return users.find(user => user.id === id);},users: (parent, args, context, info) => {return users;}}
};export default resolvers;
Now, to explain how is it going to work:
現在,解釋一下它是如何工作的:
Each query resolver has four arguments. In the user
function, we’re going to pass id
as an argument, and then return the specific user
that matches the passed id
. Pretty simple.
每個查詢解析器都有四個參數。 在user
函數中,我們將傳遞id
作為參數,然后返回與傳遞的id
匹配的特定user
。 很簡單
In the users
function, we’re just going to return the users
array that already exists. It’ll always return to us all of our users.
在users
函數中,我們將返回已經存在的users
數組。 它將始終返回給我們所有用戶。
Now, we’re going to test if our queries are working fine. Go to localhost:4000
and put in the following code:
現在,我們將測試查詢是否工作正常。 轉到localhost:4000
并輸入以下代碼:
query {users {idnameemailage}
}
It should return to you all of our users.
它應該返回給我們所有的用戶。
Or, if you want to return a specific user:
或者,如果您想返回特定用戶:
query {user(id: 1) {idnameemailage}
}
Now, we’re going to start learning about mutations, one of the most important features in GraphQL.
現在,我們將開始學習有關突變的知識 ,這是GraphQL中最重要的功能之一。
變異 (Mutations)
In GraphQL, mutations are the way you’re going to modify data on the server and get updated data back. You can think like the CUD (Create, Update, Delete) of REST.
在GraphQL中,變異是您將要修改服務器上的數據并取回更新的數據的方式。 您可以想到REST的CUD(創建,更新,刪除)。
We’re going to create our first type mutation in GraphQL, and all our mutations will end up inside this type. So, to start, go to our schema.graphql
and write a new type called mutation
:
我們將在GraphQL中創建我們的第一個類型突變,所有我們的突變都將最終存儲在該類型中。 因此,首先,轉到我們的schema.graphql
并編寫一個新的類型,稱為mutation
:
type Mutation {createUser(id: ID!, name: String!, email: String!, age: Int): User!updateUser(id: ID!, name: String, email: String, age: Int): User!deleteUser(id: ID!): User!
}
As you can see, we’re going to have three mutations:
如您所見,我們將進行三個突變:
createUser
: we should pass an ID
, name
, email
, and age
. It should return a new user to us.
createUser
:我們應該傳遞一個ID
, name
, email
和age
。 它應該將一個新用戶返回給我們。
updateUser
: we should pass an ID
, and a new name
, email
, or age
. It should return a new user to us.
updateUser
:我們應該傳遞一個ID
,以及一個新name
, email
或age
。 它應該將一個新用戶返回給我們。
deleteUser: we should pass an ID.
It should return a new user to us.
deleteUser :我們應該傳遞一個ID.
它應該將一個新用戶返回給我們。
Now, go to our resolvers.js
file and below the Query
object, create a new mutation
object like this:
現在,轉到我們的resolvers.js
文件,然后在Query
對象下面 ,創建一個新的mutation
對象,如下所示:
Mutation: {createUser: (parent, { id, name, email, age }, context, info) => {const newUser = { id, name, email, age };users.push(newUser);return newUser;},updateUser: (parent, { id, name, email, age }, context, info) => {let newUser = users.find(user => user.id === id);newUser.name = name;newUser.email = email;newUser.age = age;return newUser;},deleteUser: (parent, { id }, context, info) => {const userIndex = users.findIndex(user => user.id === id);if (userIndex === -1) throw new Error("User not found.");const deletedUsers = users.splice(userIndex, 1);return deletedUsers[0];}}
Now, our resolvers.js
file should look like this:
現在,我們的resolvers.js
文件應如下所示:
import { users } from "./db";const resolvers = {Query: {user: (parent, { id }, context, info) => {return users.find(user => user.id === id);},users: (parent, args, context, info) => {return users;}},Mutation: {createUser: (parent, { id, name, email, age }, context, info) => {const newUser = { id, name, email, age };users.push(newUser);return newUser;},updateUser: (parent, { id, name, email, age }, context, info) => {let newUser = users.find(user => user.id === id);newUser.name = name;newUser.email = email;newUser.age = age;return newUser;},deleteUser: (parent, { id }, context, info) => {const userIndex = users.findIndex(user => user.id === id);if (userIndex === -1) throw new Error("User not found.");const deletedUsers = users.splice(userIndex, 1);return deletedUsers[0];}}
};export default resolvers;
Now, we’re going to test if our mutations are working fine. Go to localhost:4000
and put in the following code:
現在,我們將測試我們的突變是否工作正常。 轉到localhost:4000
并輸入以下代碼:
mutation {createUser(id: 3, name: "Robert", email: "robert@gmail.com", age: 21) {idnameemailage}
}
It should return a new user to you. If you want to try making new mutations, I recommend you to try for yourself! Try to delete this same user that you created to see if it’s working fine.
它應該返回一個新用戶。 如果您想嘗試進行新的突變,建議您自己嘗試! 嘗試刪除與您創建的同一用戶,以查看其是否正常運行。
Finally, we’re going to start learning about subscriptions, and why they are so powerful.
最后,我們將開始學習訂閱 ,以及訂閱為何如此強大。
訂閱內容 (Subscriptions)
As I said before, subscriptions are the way you’re going to maintain a real-time connection with a server. That means that whenever an event occurs in the server and whenever that event is called, the server will send the corresponding data to the client.
如前所述,訂閱是您與服務器保持實時連接的方式。 這意味著,每當服務器中發生事件并調用該事件時,服務器便會將相應的數據發送到客戶端。
By working with subscriptions, you can keep your app updated to the latest changes between different users.
通過使用訂閱,您可以使您的應用程序更新為不同用戶之間的最新更改。
A basic subscription is like this:
基本訂閱是這樣的:
subscription {users {idnameemailage}
}
You will say it’s very similar to a query, and yes it is. But it works differently.
您會說它與查詢非常相似,是的。 但是它的工作方式不同。
When something is updated in the server, the server will run the GraphQL query specified in the subscription, and send a newly updated result to the client.
服務器中的某些內容更新后,服務器將運行訂閱中指定的GraphQL查詢,并將新更新的結果發送給客戶端。
We’re not going to work with subscriptions in this specific article, but if you want to read more about them click here.
在此特定文章中,我們將不使用訂閱,但是,如果您想了解有關訂閱的更多信息, 請單擊此處 。
結論 (Conclusion)
As you have seen, GraphQL is a new technology that is really powerful. It gives us real power to build better and well-designed APIs. That’s why I recommend you start to learn it now. For me, it will eventually replace REST.
如您所見,GraphQL是一項非常強大的新技術。 它為我們提供了構建更好的和精心設計的API的真正能力。 因此,我建議您立即開始學習。 對我來說,它將最終取代REST。
Thanks for reading the article.
感謝您閱讀本文。
Follow me on Twitter! Follow me on GitHub!
在推特上關注我! 在GitHub上關注我!
I’m looking for a remote opportunity, so if have any I’d love to hear about it, so please contact me at my Twitter!
我正在尋找機會,因此,如果有任何我想聽到的機會,請通過Twitter與我聯系!
翻譯自: https://www.freecodecamp.org/news/a-beginners-guide-to-graphql-86f849ce1bec/
graphql入門