在 Amplify API 上轻松构建后端

本次介绍使用Amplify-CLI构建GraphQL后端API。
步骤可参考官方指南。

GraphQL是一种与AWS AppSync相结合的应用程序开发工具。

GraphQL是由Facebook和社区开发的一种查询语言。它是为了解决传统REST中的以下三个主要问题而开发的。
根据GraphQL官方网站的资料,还记录了其他的优势。

    1. 在中文中重新解释以上句子:

過多地获取数据(返回了客户端不需要的数据,导致资源的浪费)
需要对多个URL进行访问(即使只要实现一个操作,也需要访问多个终端节点)
前端和后端之间的规范不一致(即使在规范文件中记录了协议,但经常出现无法及时适应规范变更的不一致)

AppSync是一种使用GraphQL的AWS托管服务。
本次我们将介绍如何使用Amplify构建AppSync的API。

预先准备

安装 Amplify CLI

npm install -g @aws-amplify/cli
amplify configure

放大器的初始设置

amplify init

因为amplify-cli将以交互式的方式询问配置信息,所以我会回答它。
与以前的文章相同,因此不再赘述说明。

创建API

amplify add api

因为它是交互式的,所以回答它的问题。

? Please select from one of the below mentioned services GraphQL
? Provide API name: AmplifyFunction
? Choose an authorization type for the API Amazon Cognito User Pool
Using service: Cognito, provided by: awscloudformation

 The current configured provider is Amazon Cognito.

 Do you want to use the default authentication and security configuration? Defau
lt configuration
 Warning: you will not be able to edit these selections.
 How do you want users to be able to sign in when using your Cognito User Pool?
Email
 Warning: you will not be able to edit these selections.
 What attributes are required for signing up? (Press <space> to select, <a> to t
oggle all, <i> to invert selection)Email
Successfully added auth resource
? 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 (e.g., “Todo” with
 ID, name, description)
? Do you want to edit the schema now? Yes

编辑器将在这里启动。
由于已经自动生成了名为schema.graphql的文件,因此需要根据需要更改模式定义。

以下是添加了title字段的模式示例

type Todo @model {
  id: ID!
  name: String!
  description: String
  title: String
}

在类型(type)中添加@model指令将创建表格。
在模式定义中,还提供了其他各种指令(@key、@auth、@connection等)。
请参考此处以获取更多详细信息。

当schema.graphql的模式定义完成后,保存并返回终端。
你应该会看到”请按回车键继续”的提示,然后请按下回车键。

最后,执行以下命令进行部署。

amplify push

将显示新创建的身份验证和 API 资源。


| Category | Resource name           | Operation | Provider plugin   |
| -------- | ----------------------- | --------- | ----------------- |
| Auth     | amplifyfunctiondxxxxxxx | Create    | awscloudformation |
| Api      | AmplifyFunction         | Create    | awscloudformation |

完成部署后,接下来我们将以互动方式回答一些问题(基本上都是”Yes”),然后执行部署。

? Do you want to generate code for your newly created GraphQL API Yes
? Choose the code generation language target typescript
? Enter the file name pattern of graphql queries, mutations and subscriptions sr
c/graphql/**/*.ts
? Do you want to generate/update all possible GraphQL operations - queries, muta
tions and subscriptions Yes
? Enter maximum statement depth [increase from default if your schema is deeply
nested] 2
? Enter the file name for the generated code src/API.ts

一旦成功部署完成,您可以通过访问AWS控制台来确认资源已经创建。

使用Amplify创建API时,会自动生成标准的CRUD操作所需的查询。虽然您可以根据需要定义自己的查询,但对于简单的应用程序来说,只使用这些自动生成的查询就足够了。

export const getTodo = `query GetTodo($id: ID!) {
  getTodo(id: $id) {
    id
    name
    description
    title
  }
}
`;
export const listTodos = `query ListTodos(
  $filter: ModelTodoFilterInput
  $limit: Int
  $nextToken: String
) {
  listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {
    items {
      id
      name
      description
      title
    }
    nextToken
  }
}
`;
export const createTodo = `mutation CreateTodo($input: CreateTodoInput!) {
  createTodo(input: $input) {
    id
    name
    description
    title
  }
}
`;

...などなど
export const onCreateTodo = `subscription OnCreateTodo {
  onCreateTodo {
    id
    name
    description
    title
  }
}
`;
...などなど

使用API

当部署完成后,将在src文件夹的根目录下生成一个名为”aws-exports.js”的文件。该文件记录了与后端连接的AppSync端点、区域、认证方式等信息。在将该应用程序集成并使用时,需要读取并使用该文件。

比如说,就像下面这样的感觉。

import awsmobile from './aws-exports';
Amplify.configure(awsmobile)

const App: React.FC = () => {
  return (
      ...snip...
  );
}

API调用的感觉如下:

查詢

(默认情况下,list最多只能获取10条记录,所以请根据需要适当更改limit的值。)

import { API, graphqlOperation } from 'aws-amplify'
import { listTodos } from './graphql/queries'


//Todoリスト取得する実装抜粋
const result = await API.graphql(graphqlOperation(listTodos, { limit: 1000 })) as GraphQLResult
const query = result.data as ListTodosQuery
if (query.listTodos) {
   const list = query.listTodos.items as Array<CreateTodoInput>
   return list
}

变异

import { API, graphqlOperation } from 'aws-amplify'
import { createTodo } from './graphql/mutations'

//Todo追加する実装抜粋
const input: CreateTodoInput = {
   name: 'hoge',
   description: 'fuga',
   title: 'piyo',
}
const newTodo = await API.graphql(graphqlOperation(createTodo, { input }))

訂閱

import { API, graphqlOperation } from "aws-amplify";
import { onUpdateTodo } from "../graphql/subscriptions";

//更新されたTodoをサブスクライブする実装抜粋
const subscription = API.graphql(graphqlOperation(onUpdateTodo)).subscribe({
        next: (response: any) => {
            const todo = response.value.data.onUpdateTodo as UpdateTodoInput
            //do something
        }
    })

总结

这次我尝试使用Amplify Add API快速构建后端。只需要非常简单的步骤,就能够很快地创建完成。虽然本次只介绍了简单的创建表格的情况,但是在Amplify中,schema.graphql提供了各种不同的类别,可以轻松地构建复杂的系统结构。如果有机会的话,我会再介绍给大家,但是这次就到这里了。

广告
将在 10 秒后关闭
bannerAds