开始使用 AWS
构建 React 应用程序
使用 AWS Amplify 创建简单的 Web 应用程序
模块 4:添加 GraphQL API 和数据库
在此模块中,您将使用 Amplify CLI 和库配置和添加 GraphQL API 到您的应用程序中。
简介
现在,您已使用身份验证创建并配置应用程序,接下来添加 API。
在此模块中,您将使用 Amplify CLI 和库添加 API 到您的应用程序中。您将创建的 API 是 GraphQL API,它利用 Amazon DynamoDB(NoSQL 数据库)支持的 AWS AppSync(托管 GraphQL 服务)。(有关 GraphQL 的介绍,请访问此页面。)
我们将构建的应用程序是备注应用程序,用户可使用它创建、删除和列出备注。本示例将让您了解如何构建很多常见类型的 CRUD+L(创建、读取、更新、删除和列出)应用程序。
您将学到的内容
- 创建和部署 GraphQL API
- 编写前端代码以与 API 互动
重要概念
API – 提供编程接口,以允许多个软件中介之间的通信和互动。
GraphQL – 基于应用程序类型化表示的查询语言和服务器端 API 实施。此 API 表示使用基于 GraphQL 类型系统的架构声明。(要了解有关 GraphQL 的更多信息,请访问此页面。)
完成时间
15 分钟
使用的服务
实施
-
创建 GraphQL API 和数据库
a.通过从您的应用程序目录根中运行以下命令添加 GraphQL API 到您的应用程序中:
amplify add api ? Please select from one of the below mentioned services: GraphQL ? Provide API name: notesapp ? Choose the default authorization type for the API: API Key ? Enter a description for the API key: demo ? After how many days from now the API key should expire: 7 (or your preferred expiration) ? Do you want to configure advanced settings for the GraphQL API: No, I am done. ? Do you have an annotated GraphQL schema? No ? Do you want a guided schema creation? Yes ? What best describes your project: Single object with fields ? Do you want to edit the schema now? Yes
b.在您的文本编辑器中打开 GraphQL 架构:amplify/backend/api/myapi/schema.graphql。
使用下面的架构更新文件:
type Note @model { id: ID! name: String! description: String }
c.保存文件。然后返回命令行,并按 enter 键完成 API 配置步骤。
-
部署 API
现在,API 已在本地配置完成,接下来对其进行部署。要执行此操作,运行 Amplify push 命令:
amplify push --y
将完成 3 项操作:
- 创建 AppSync API
- 创建 DynamoDB 表
- 在位于 src/graphql 的文件夹中创建本地 GraphQL 操作,您可以使用该文件夹查询 API
要随时在您的账户中查看 GraphQL API,运行以下命令:
amplify console api > Choose GraphQL
要随时在您的账户中查看 Amplify 应用程序,请运行以下命令:
amplify console
-
编写前端代码以与 API 互动
现在,后端已部署完成,我们来编写一些代码来使用户创建、列出和删除备注。
使用以下代码更新 src/App.js:
import React, { useState, useEffect } from 'react'; import './App.css'; import { API } from 'aws-amplify'; import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'; import { listNotes } from './graphql/queries'; import { createNote as createNoteMutation, deleteNote as deleteNoteMutation } from './graphql/mutations'; const initialFormState = { name: '', description: '' } function App() { const [notes, setNotes] = useState([]); const [formData, setFormData] = useState(initialFormState); useEffect(() => { fetchNotes(); }, []); async function fetchNotes() { const apiData = await API.graphql({ query: listNotes }); setNotes(apiData.data.listNotes.items); } async function createNote() { if (!formData.name || !formData.description) return; await API.graphql({ query: createNoteMutation, variables: { input: formData } }); setNotes([ ...notes, formData ]); setFormData(initialFormState); } async function deleteNote({ id }) { const newNotesArray = notes.filter(note => note.id !== id); setNotes(newNotesArray); await API.graphql({ query: deleteNoteMutation, variables: { input: { id } }}); } return ( <div className="App"> <h1>My Notes App</h1> <input onChange={e => setFormData({ ...formData, 'name': e.target.value})} placeholder="Note name" value={formData.name} /> <input onChange={e => setFormData({ ...formData, 'description': e.target.value})} placeholder="Note description" value={formData.description} /> <button onClick={createNote}>Create Note</button> <div style={{marginBottom: 30}}> { notes.map(note => ( <div key={note.id || note.name}> <h2>{note.name}</h2> <p>{note.description}</p> <button onClick={() => deleteNote(note)}>Delete note</button> </div> )) } </div> <AmplifySignOut /> </div> ); } export default withAuthenticator(App);
我们的应用程序有 3 个主要函数:
- fetchNotes - 此函数使用 API 类将查询发送到 GraphQL API 并检索备注列表。
- createNote - 此函数也使用 API 类将变化发送到 GraphQL API 中,主要的差别在于,在此函数中,我们传递 GraphQL 变化所需的变量,从而使我们能够使用表格数据创建新备注。
- deleteNote - 与 createNote 一样,此函数将 GraphQL 变化与一些变量一起发送,但不是创建备注,而是删除备注。
-
运行应用程序
要测试应用程序,请运行 start 命令:
npm start