我整理了使用AWS Amplify将资源(API,Auth)构建和导入到前端(React)的步骤
首先
我听说使用 AWS Amplify 可以轻松创建无服务器的后端。我一直想尝试个人应用开发,但是由于后端构建的麻烦,一直没有下手。所以,我决定借此机会学习 Amplify。
下面是我构建 API 和认证资源,并将其实施到前端的总结。
AWS Amplify 是什么?
只需使用CLI键入命令即可在云端配置后端资源(如S3和API Gateway等AWS服务),从而轻松构建无服务器后端的服务。使用此服务可以使应用开发变得极为高效。
可以通过命令来创建的资源包括以下几种类型:
-
- Auth: Amazon Cognito(SignIn/SignUp機能を追加)
-
- Analytics: Amazon Pinpoint(ユーザのセッションやイベントを記録)
-
- Storage: Amazon S3
-
- Caching: Amazon Cloudfront
- API: API Gateway+Lambda(REST)やAppSync(GraphQL)
在黑带的资料中有更详细的内容。
引用CLI Amplify的介绍
只需点几下即可创建后端资源,需要使用Amplify CLI进行安装并与自己的AWS账户关联。具体安装步骤请参考官方文档,简单概括如下所示。
-
- Amplify CLIのインストール(Node.jsとnpmの事前導入が必要)
-
- Amplifyの設定でAWSリソースを作成するためのIAMユーザを新規作成
- アクセスキーIDとシークレットアクセスキーを入力してAmplify CLIとIAMユーザを紐付け
创建应用程式
使用Amplify构建后端资源如GraphQL和Auth,并在React应用程序中使用它们。请首先使用npx create-react-app <app名>命令创建项目。
后端建设
首先,在项目中导入amplify。输入以下命令后,会弹出与默认编辑器和使用的框架相关的问题,请回答这些问题。
amplify init
? Enter a name for the project chatapp
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using react
? Source Directory Path: src
? Distribution Directory Path: build
? Build Command: npm run-script build
? Start Command: npm run-script start
Using default provider awscloudformation
? Select the authentication method you want to use: (Use arrow keys)
? Select the authentication method you want to use: AWS profile
For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html
? Please choose the profile you want to use default
构建API(GraphQL)资源
通过以下命令逐步回答问题,将在amplify/backend的根目录下创建api文件夹。
amplify add api
? Please select from one of the below mentioned services: GraphQL
? Provide API name: chatapp
? Choose the default authorization type for the API API key
? Enter a description for the API key:
? After how many days from now the API key should expire (1-365): 365
? Do you want to configure advanced settings for the GraphQL API No, I am done.
? Do you have an annotated GraphQL schema? No
? Choose a schema template: Single object with fields (e.g., “Todo” with ID, name, description)
在 schema.graphql 中定义模式。
type Post @model {
id: ID!
postOwnerId: String!
postOwnerUsername: String!
postTitle: String!
postBody: String!
createdAt: String
comments: [Comment] @connection(name: "PostComments") #relationship
likes: [Like] @connection(name: "PostLikes")
}
type Comment @model {
id: ID!
commentOwnerId: String!
commentOwnerUsername: String!
post: Post @connection(name: "PostComments")
content: String!
createdAt: String!
}
type Like @model {
id: ID!
numberLikes: Int!
likeOwnerId: String!
likeOwnerUsername: String!
post: Post @connection(name: "PostLikes")
}
若在”type”上添加”model”指令,它将自动生成与数据源(DynamoDB)的连接以及解析器。此外,使用amplify codegen,还可以自动生成客户端源代码库,以便在src/graphql中访问。
当执行amplify push命令并回答以下问题时,将会部署AWS资源(AppSync)。
amplify push
| Category | Resource name | Operation | Provider plugin |
| -------- | ------------- | --------- | ----------------- |
| Api | chatapp | Create | awscloudformation |
? Are you sure you want to continue? Yes
? Do you want to generate code for your newly created GraphQL API Yes
? Choose the code generation language target javascript
? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
建立Auth资源
在执行 “amplify add auth” 后,您可以通过使用 “amplify push” 来构建AWS资源(Cognito)。
amplify add auth
Using service: Cognito, provided by: awscloudformation
The current configured provider is Amazon Cognito.
Do you want to use the default authentication and security configuration? Default configuration
Warning: you will not be able to edit these selections.
How do you want users to be able to sign in? Username
Do you want to configure advanced settings? No, I am done.
前端配置
我整理了如何在前端(React)中使用配置好的 AWS 资源的方法。
API(GraphQL)
我整理了如何使用创建的Query和Mutation的方法。
查询
通过运行npm install aws-amplify aws-amplify-react安装所需的库,并加载已创建的查询来执行API.graphql(graphqlOperation(listPosts))。在获取数据后,我们希望进行显示,所以进行了异步处理(async~await)。
import { listPosts } from '../graphql/queries';
import { API, graphqlOperation } from 'aws-amplify';
const getPosts = async () => {
const result = await API.graphql(graphqlOperation(listPosts));
};
突变 (tú
这也与查询类似,从graphql文件夹中读取并执行。
以下是deletePost的示例。为了指定要删除的post,它将postId作为参数。
const handleDeletePost = async (postId) => {
const input = {
id: postId,
};
await API.graphql(graphqlOperation(deletePost, { input }));
认证
我将导入withAuthentificator并将其包装在App中。
import './App.css';
import { DisplayPosts } from './components/DisplayPosts';
import { CreatePost } from './components/CreatePost';
import { withAuthenticator } from 'aws-amplify-react';
function App() {
return (
<div className="App">
<CreatePost />
<DisplayPosts />
</div>
);
}
export default withAuthenticator(App, { includeGreetings: true });
最后
我在考虑使用React Native+ Amplify构建一个专门针对胃部不适人群的服务。