GraphQL - Apollo客户端

我们已经使用Apollo Server在服务器端构建graphql规范.可以快速轻松地构建生产就绪的GraphQL服务器.现在让我们了解客户端.

Apollo Client是使用GraphQL构建客户端应用程序的最佳方式.客户端旨在帮助开发人员快速构建一个使用GraphQL获取数据的UI,并且可以与任何JavaScript前端一起使用.

Apollo Client支持以下平台 :

Sr.No.平台&框架
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步和第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
}

Step 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 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

这将安装典型反应应用程序所需的一切. npx实用程序和create-react-app工具创建名为 hello-world-client 的项目.安装完成后,在VSCode中打开项目.

步骤2 : 启动hello-world-client

将终端中的当前文件夹路径更改为 hello-world-client .键入npm start以启动项目.这将在端口3000运行开发服务器,并将自动打开浏览器并加载索引页.

这在下面给出的屏幕截图中显示 :

Creating Ract Project.jpg

Step 3 : 安装Apollo客户端库

要安装Apollo客户端,请打开一个新终端并进入当前项目文件夹路径.键入以下命令 :

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查询方法返回一个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()
});

在上一章中,我们讨论了如何对HTTP请求使用fetch API.以下代码显示了如何使用 gql 函数. loadStudentsAsync 函数使用graphql客户端查询服务器.

async function loadStudentsAsync() {
   const query = gql`
   {
      students{
         id
         firstName
         lastName
         college{
            name
         }
      }
   }`
   const {data} = await client.query({query}) ;
   return data.students;
}

您只需要将 index.js 保留在 src 文件夹中index.html在公共文件夹中;可以删除自动生成的所有其他文件.

目录结构在下面和下面给出;

hello-world-client /
   -->node_modules
   -->public
         index.html
   -->src
         index.js
   -->package.json

以下是反应应用中的 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>
      )
   }
}

一旦我们点击loadStudents按钮,反应应用程序将从GraphQL服务器加载学生,如下所示 :

浏览器输出反应应用程序