构建全栈 React 应用程序

使用 AWS Amplify 创建简易 Android 应用程序

模块 4:添加 GraphQL API 和数据库

在本模块中,您将使用 Amplify CLI 和库来配置并添加 GraphQL API 到您的应用程序

概述

现在,我们已经创建并配置了带有身份验证的应用程序,让我们添加一个 API。

在本模块中,您将使用 Amplify CLI 和库为应用程序添加 API。您将创建的是一个 GraphQL API,它使用 AWS AppSync(一种托管的 GraphQL 服务),由 Amazon DynamoDB(一种 NoSQL 数据库)提供支持。(有关 GraphQL 的介绍,请参阅 GraphQL 网站。)

我们将构建的应用程序是一个笔记应用程序,它允许用户创建、删除和列出笔记。这个示例将让您很好地了解如何构建多种常见类型的 CRUD+L(创建、读取、更新、删除和列出)应用程序。

学习目标

在本模块中,您将:
  • 创建和部署 GraphQL API
  • 编写与 API 交互的前端代码

关键概念

API - 提供一个编程接口,允许多个软件中介之间进行通信和交互。

GraphQL - 一种查询语言和服务器端 API 的实现方式。它基于应用程序的类型化表示。通过定义一个符合 GraphQL 类型系统的模式 (Schema) 来描述 API。

 时长

15 分钟

 使用的服务

操作步骤

  • a. 在应用程序目录的根目录下运行以下命令,将 GraphQL API 添加到应用程序:

    amplify add api
    
    ? Select from one of the below mentioned services: GraphQL
    ? Here is the GraphQL API that we will create. Select a setting to edit or continue: Continue
    ? Choose a schema template: Single object with fields (e.g., "Todo" with ID, name, description)
    ? Do you want to edit the schema now? (Y/n) yes

    b. 在文本编辑器中打开 GraphQL 模式:/amplify/backend/api//schema.graphql。

    使用以下模式更新文件:

    type Note @model @auth(rules: [ { allow: public } ] ){
      id: ID!
      name: String!
      description: String
    }

    c. 保存文件。

  • 现在,API 已在本地配置完毕,是时候部署它了。为此,请运行 Amplify push 命令:

    amplify push --y

    这将完成以下三个操作:

    1. 创建 AWS AppSync API
    2. 创建 DynamoDB 表
    3. 在位于 src/graphql 的文件夹中创建本地 GraphQL 操作,您可以使用它来查询 API

    要随时查看您账户中的 GraphQL API,请运行以下命令,然后在左侧导航栏中选择 GraphQL API:

    amplify console api
    
    > Choose GraphQL
    

    要随时查看您账户中的 Amplify 应用程序,请运行以下命令:

    amplify console
    ? Which site do you want to open? AWS console
  • 现在,后端已部署完毕,接下来我们编写一些代码,让用户可以创建、列出和删除笔记。

    使用以下代码更新 src/App.js:

    import React, { useState, useEffect } from "react";
    import "./App.css";
    import "@aws-amplify/ui-react/styles.css";
    import { API } from "aws-amplify";
    import {
      Button,
      Flex,
      Heading,
      Text,
      TextField,
      View,
      withAuthenticator,
    } from "@aws-amplify/ui-react";
    import { listNotes } from "./graphql/queries";
    import {
      createNote as createNoteMutation,
      deleteNote as deleteNoteMutation,
    } from "./graphql/mutations";
    
    const App = ({ signOut }) => {
      const [notes, setNotes] = useState([]);
    
      useEffect(() => {
        fetchNotes();
      }, []);
    
      async function fetchNotes() {
        const apiData = await API.graphql({ query: listNotes });
        const notesFromAPI = apiData.data.listNotes.items;
        setNotes(notesFromAPI);
      }
    
      async function createNote(event) {
        event.preventDefault();
        const form = new FormData(event.target);
        const data = {
          name: form.get("name"),
          description: form.get("description"),
        };
        await API.graphql({
          query: createNoteMutation,
          variables: { input: data },
        });
        fetchNotes();
        event.target.reset();
      }
    
      async function deleteNote({ id }) {
        const newNotes = notes.filter((note) => note.id !== id);
        setNotes(newNotes);
        await API.graphql({
          query: deleteNoteMutation,
          variables: { input: { id } },
        });
      }
    
      return (
        <View className="App">
          <Heading level={1}>My Notes App</Heading>
          <View as="form" margin="3rem 0" onSubmit={createNote}>
            <Flex direction="row" justifyContent="center">
              <TextField
                name="name"
                placeholder="Note Name"
                label="Note Name"
                labelHidden
                variation="quiet"
                required
              />
              <TextField
                name="description"
                placeholder="Note Description"
                label="Note Description"
                labelHidden
                variation="quiet"
                required
              />
              <Button type="submit" variation="primary">
                Create Note
              </Button>
            </Flex>
          </View>
          <Heading level={2}>Current Notes</Heading>
          <View margin="3rem 0">
            {notes.map((note) => (
              <Flex
                key={note.id || note.name}
                direction="row"
                justifyContent="center"
                alignItems="center"
              >
                <Text as="strong" fontWeight={700}>
                  {note.name}
                </Text>
                <Text as="span">{note.description}</Text>
                <Button variation="link" onClick={() => deleteNote(note)}>
                  Delete note
                </Button>
              </Flex>
            ))}
          </View>
          <Button onClick={signOut}>Sign Out</Button>
        </View>
      );
    };
    
    export default withAuthenticator(App);

    我们的应用程序有三个主要功能:

    1. fetchNotes - 此函数使用 API 类向 GraphQL API 发送查询,并检索笔记列表。
    2. createNote - 此函数也使用 API 类向 GraphQL API 发送变更。主要区别在于,在此函数中,我们传递了 GraphQL 变更所需的变量,以便使用表单数据创建新的笔记。
    3. deleteNote - 与 createNote 类似,此函数发送 GraphQL 变更以及一些变量,但我们不是创建笔记,而是删除笔记。
  • 要测试应用程序,请运行 start 命令:

    npm start

总结

您现在已经创建了一个笔记应用程序。使用 AWS Amplify,您在应用程序中添加了 GraphQL API,并配置了创建、读取和删除功能。在下一个模块中,我们将为您的应用程序添加存储服务。