- GraphQL 教程
- GraphQL - 首頁
- GraphQL - 簡介
- GraphQL - 環境搭建
- GraphQL - 架構
- GraphQL - 應用程式元件
- GraphQL - 示例
- GraphQL - 型別系統
- GraphQL - 模式
- GraphQL - 解析器
- GraphQL - 查詢
- GraphQL - 變異
- GraphQL - 驗證
- GraphQL - JQuery 整合
- GraphQL - React 整合
- GraphQL - Apollo 客戶端
- GraphQL - 客戶端身份驗證
- GraphQL - 快取
- GraphQL 有用資源
- GraphQL - 快速指南
- GraphQL - 有用資源
- GraphQL - 討論
GraphQL - Apollo 客戶端
我們已經使用 Apollo Server 在伺服器端構建了 graphql 規範。它可以快速輕鬆地構建生產就緒的 GraphQL 伺服器。現在讓我們瞭解客戶端。
Apollo Client 是使用 GraphQL 構建客戶端應用程式的最佳方式。該客戶端旨在幫助開發人員快速構建一個使用 GraphQL 獲取資料的 UI,並且可以與任何 JavaScript 前端一起使用。
Apollo Client 支援以下平臺:
| 序號 | 平臺和框架 |
|---|---|
| 1 | Javascript React、Angular、Vue、Meteor、Ember |
| 2 | WebComponents Polymer、lit-apollo |
| 3 | 原生移動 使用 Java 的原生 Android,使用 Swift 的原生 iOS |
快取是 Apollo Client 的主要功能之一。apollo-boost 是一個便捷的軟體包,它包含了許多其他依賴項。
圖示
讓我們看看如何使用 Apollo Client 透過以下步驟構建客戶端應用程式:
設定伺服器
我們必須按照以下步驟設定伺服器:
步驟 1 - 下載並安裝專案所需的依賴項
建立一個資料夾 apollo-server-app。從終端將您的目錄更改為 apollo-server-app。然後,按照環境設定章節中解釋的步驟 3 到 5 進行操作。
步驟 2 - 建立模式
在專案資料夾 apollo-server-app 中新增 schema.graphql 檔案,並新增以下程式碼:
type Query
{
students:[Student]
}
type Student {
id:ID!
firstName:String
lastName:String
college:College
}
type College {
id:ID!
name:String
location:String
rating:Float
}
步驟 3 - 新增解析器
在專案資料夾中建立一個檔案 resolvers.js,並新增以下程式碼:
const db = require('./db')
const Query = {
//resolver function for students returns list
students:() => db.students.list(),
}
const Student = {
college:(root) => {
return db.colleges.get(root.collegeId);
}
}
module.exports = {Query,Student}
步驟 4 - 執行應用程式
建立一個 server.js 檔案。參考環境設定章節中的步驟 8。在終端中執行命令 npm start。伺服器將在 9000 埠啟動並執行。在這裡,我們將使用 GraphiQL 作為客戶端來測試應用程式。
開啟瀏覽器並輸入 URL https://:9000/graphiql。在編輯器中鍵入以下查詢。
{
students{
id
firstName
college{
name
}
}
}
查詢的響應如下所示:
{
"data": {
"students": [
{
"id": "S1001",
"firstName": "Mohtashim",
"college": {
"name": "CUSAT"
}
},
{
"id": "S1002",
"firstName": "Kannan",
"college": {
"name": "AMU"
}
},
{
"id": "S1003",
"firstName": "Kiran",
"college": {
"name": "AMU"
}
}
]
}
}
設定客戶端
為客戶端開啟一個新的終端。在執行客戶端應用程式之前,應保持伺服器終端執行。React 應用程式將在 3000 埠執行,伺服器應用程式將在 9000 埠執行。
步驟 1 - 建立 React 應用程式
在客戶端終端中,鍵入以下命令:
npx create-react-app hello-world-client
這將安裝典型 React 應用程式所需的一切。npx 實用程式和 create-react-app 工具建立一個名為 hello-world-client 的專案。安裝完成後,在 VSCode 中開啟專案。
步驟 2 - 啟動 hello-world-client
將終端中的當前資料夾路徑更改為 hello-world-client。鍵入 npm start 啟動專案。這將在 3000 埠執行開發伺服器,並將自動開啟瀏覽器並載入索引頁面。
這在下面給出的螢幕截圖中顯示:
步驟 3 - 安裝 Apollo Client 庫
要安裝 Apollo Client,請開啟一個新的終端並位於當前專案資料夾路徑中。鍵入以下命令:
npm install apollo-boost graphql
這將下載客戶端的 graphql 庫以及 Apollo Boost 包。我們可以透過在 apollo-boost 依賴項中鍵入 npm view 來交叉檢查這一點。這將具有許多依賴項,如下所示:
{
'apollo-cache': '^1.1.15',
'apollo-cache-inmemory': '^1.2.8',
'apollo-client': '^2.4.0',
'apollo-link': '^1.0.6',
'apollo-link-error': '^1.0.3',
'apollo-link-http': '^1.3.1',
'apollo-link-state': '^0.4.0',
'graphql-tag': '^2.4.2'
}
我們可以清楚地看到已安裝 Apollo-Client 庫。
步驟 4 - 修改 index.js 檔案中的 App 元件
使用 Apollo Client,我們可以直接呼叫伺服器,而無需使用 fetch API。此外,查詢和變異不應嵌入用反引號編寫的字串中。這是因為 gql 函式直接解析查詢。這意味著程式設計師可以在使用 GraphiQL 工具編寫查詢時以相同的方式直接編寫查詢。gql 是一個標籤函式,它將用反引號編寫的模板字串解析為 graphql 查詢物件。Apollo Client 的 query 方法返回一個 Promise。
以下程式碼片段顯示瞭如何匯入 Apollo Client:
import {ApolloClient, HttpLink, InMemoryCache} from 'apollo-boost'
const endPointUrl = 'https://:9000/graphql'
const client = new ApolloClient({
link: new HttpLink({uri:endPointUrl}),
cache:new InMemoryCache()
});
在上一章中,我們討論瞭如何使用 fetch API 進行 HTTP 請求。以下程式碼顯示瞭如何使用 gql 函式。loadStudentsAsync 函式使用 graphql 客戶端查詢伺服器。
async function loadStudentsAsync() {
const query = gql`
{
students{
id
firstName
lastName
college{
name
}
}
}`
const {data} = await client.query({query}) ;
return data.students;
}
您只需要保留 src 資料夾中的 index.js 和 public 資料夾中的 index.html;所有其他自動生成的可以刪除。
目錄結構如下所示:
hello-world-client /
-->node_modules
-->public
index.html
-->src
index.js
-->package.json
以下是 React 應用程式中的 index.js:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
// apollo client
import {ApolloClient, HttpLink, InMemoryCache} from 'apollo-boost'
import gql from 'graphql-tag'
const endPointUrl = 'https://:9000/graphql'
const client = new ApolloClient({
link: new HttpLink({uri:endPointUrl}),
cache:new InMemoryCache()
});
async function loadStudentsAsync() {
const query = gql`
{
students{
id
firstName
lastName
college{
name
}
}
}
`
const {data} = await client.query({query}) ;
return data.students;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
students:[]
}
this.studentTemplate = [];
}
async loadStudents() {
const studentData = await loadStudentsAsync();
this.setState({
students: studentData
})
console.log("loadStudents")
}
render() {
return(
<div>
<input type = "button" value = "loadStudents" onClick = {this.loadStudents.bind(this)}/>
<div>
<br/>
<hr/>
<table border = "3">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>college Name</td>
</tr>
</thead>
<tbody>
{
this.state.students.map(s => {
return (
<tr key = {s.id}>
<td>
{s.firstName}
</td>
<td>
{s.lastName}
</td>
<td>
{s.college.name}
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
一旦我們單擊 loadStudents 按鈕,React 應用程式將從 GraphQL 伺服器載入學生,如下所示: