GraphQL Apollo Client 怎么用?怎么快速上手开发?

文章导读
Previous Quiz Next 我们已经使用 Apollo Server 在服务器端构建了 GraphQL 规范。它快速且简单地构建了生产就绪的 GraphQL server。现在让我们了解客户端部分。
📋 目录
  1. 示例说明
  2. 设置服务器
  3. 设置客户端
A A

GraphQL - Apollo Client



Previous
Quiz
Next

我们已经使用 Apollo Server 在服务器端构建了 GraphQL 规范。它快速且简单地构建了生产就绪的 GraphQL server。现在让我们了解客户端部分。

Apollo Client 是使用 GraphQL 构建客户端应用的最佳方式。该客户端旨在帮助开发者快速构建使用 GraphQL 获取数据的 UI,并且可以与任何 JavaScript 前端框架一起使用。

Apollo Client 支持以下平台 −

序号 平台 & 框架
1

Javascript

React、Angular、Vue、Meteor、Ember

2

WebComponents

Polymer、lit-apollo

3

Native Mobile

使用 Java 的原生 Android、使用 Swift 的原生 iOS

缓存是 Apollo Client 的主要特性之一。apollo-boost 是一个便利包,它引入了许多其他依赖。

示例说明

让我们通过以下步骤了解如何使用 Apollo Client 构建客户端应用 −

设置服务器

设置服务器需要遵循以下步骤 −

步骤 1 − 下载并安装项目所需的依赖

创建一个名为 apollo-server-app 的文件夹。从终端切换到 apollo-server-app 目录。然后,按照环境设置章节中解释的步骤 3 到 5 操作。

步骤 2 − 创建 Schema

在项目文件夹 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

在项目文件夹中创建一个 resolvers.js 文件,并添加以下代码 −

const db = require('./db')

const Query = {
   //students 的 resolver 函数,返回列表
   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 http://localhost: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 上运行开发服务器,并自动打开浏览器并加载 index 页面。

如下图所示 −

Creating Ract Project.jpg

步骤 3 − 安装 Apollo Client 库

要安装 Apollo Client,请打开一个新终端并进入当前项目文件夹路径。输入以下命令 −

npm install apollo-boost graphql

这将下载客户端的 graphql 库以及 Apollo Boost 包。我们可以通过输入 npm view apollo-boost dependencies 来交叉检查。这将显示许多依赖项,如下所示 −

{
   '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。此外,查询和 mutation 不应嵌入使用反引号记号创建的字符串中。这是因为 gql 函数直接解析查询。这意味着程序员可以直接以与在 GraphiQL 工具中编写查询相同的方式编写查询。gql 是一个标签函数,它将使用反引号记号编写的模板字符串解析为 graphql query 对象。Apollo Client 的 query 方法返回一个 promise。

以下代码片段展示了如何导入 Apollo Client −

import {ApolloClient, HttpLink, InMemoryCache} from 'apollo-boost'

const endPointUrl = 'http://localhost:9000/graphql'
const client = new ApolloClient({
   link: new HttpLink({uri:endPointUrl}),
   cache:new InMemoryCache()
});

在上一章中,我们讨论了如何使用 fetch API 进行 HTTP 请求。以下代码展示了如何使用 gql 函数。loadStudentsAsync 函数使用 graphql client 查询服务器。

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 = 'http://localhost: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 服务器加载学生,如下所示 −

Browser Output React Application