我试着做了Amplify的教程(Vue.js)
首先
由于不太理解Amplify是什么,所以我尝试做了一下教程。
有很多人介绍了各种教程,但是内容有点过时,所以我按照官方(?)的教程一步步尝试了一下。
(这只是我留下的记录,供自己做备忘。)
由于Amplify和Vue都是为初学者设计的,所以可能有一些地方内容还不能理解…(这只是抄写的结果)。(我想可能也有更详细解释的人,尽量包含一些命令输出的结果。)
目标教程
前提条件
环境
环境要素
Node.js v14.x or later
npm v6.14.4 or later
git v2.14.1 or later
在本地环境下使用Windows10和Windows Terminal。
❯ node -v
v16.13.1
❯ npm -v
8.1.2
❯ git --version
git version 2.39.0.windows.2
AWS账户
利用现有的东西。
安装 Amplify CLI
增强设置
amplify configure
指定使用区域和IAM用户。
Specify the AWS Region
? region: us-east-1
Specify the username of the new IAM user:
? user name: amplify-test
添加IAM用户
创建用户访问密钥,并记下”Access key ID”和”Secret access key”。
在终端上输入并输入配置文件名称。(由于不想使用默认配置,我进行了指定。)
Enter the access key of the newly created user:
? accessKeyId: ********************
? secretAccessKey: ****************************************
This would update/create the AWS Profile in your local machine
? Profile Name: amplify-test
建立全栈项目
创建Vue3应用程序
❯ npm init vue@3
Need to install the following packages:
create-vue@3
Ok to proceed? (y) y
Vue.js - The Progressive JavaScript Framework
√ Project name: ... myamplifyproject
√ Add TypeScript? ... No
√ Add JSX Support? ... No
√ Add Vue Router for Single Page Application development? ... No
√ Add Pinia for state management? ... No
√ Add Vitest for Unit Testing? ... No
√ Add an End-to-End Testing Solution? » No
√ Add ESLint for code quality? ... No
安装所需的模块。
cd myamplifyproject
npm install
应用程序的运行
npm run dev
从终端显示的本地URL处进行查看。
VITE v4.0.3 ready in 1166 ms
➜ Local: http://127.0.0.1:5173/
➜ Network: use --host to expose
➜ press h to show help
初始化新的后端
amplify init
❯ amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project todo <--- TODO と指定
The following configuration will be applied:
Project information
| Name: todo
| Environment: dev
| Default editor: Visual Studio Code
| App type: javascript
| Javascript framework: vue
| Source Directory Path: src
| Distribution Directory Path: dist
| Build Command: npm.cmd run-script build
| Start Command: npm.cmd run-script serve
? Initialize the project with the above configuration? Yes
Using default provider awscloudformation
? Select the authentication method you want to use: AWS profile <---認証はprofile
? Please choose the profile you want to use amplify-test <--- 先ほど作成したものを指定
使用 CloudFormation 创建。
Adding backend environment dev to AWS Amplify app: **********
Deployment completed.
Deployed root stack todo [ ======================================== ] 4/4
AuthRole AWS::IAM::Role CREATE_COMPLETE
DeploymentBucket AWS::S3::Bucket CREATE_COMPLETE
UnauthRole AWS::IAM::Role CREATE_COMPLETE
amplify-todo-dev-***** AWS::CloudFormation::Stack CREATE_COMPLETE
√ Help improve Amplify CLI by sharing non sensitive configurations on failures (y/N) <--- Nを指定
Deployment bucket fetched.
√ Initialized provider successfully.
√ Initialized your environment successfully.
Your project has been successfully initialized and connected to the cloud!
安装Amplify库
npm install aws-amplify @aws-amplify/ui-vue
前端设置
修改 src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import './assets/main.css'
import { Amplify } from 'aws-amplify'; //追加
import awsExports from './aws-exports'; //追加
Amplify.configure(awsExports); //追加
createApp(App).mount('#app')
修复Vue Vite配置
在index.html中添加内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
<!-- 追加 -->
<script>
window.global = window;
var exports = {};
</script>
<!-- 追加 -->
</body>
</html>
修改别名的内容
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [
{
find: './runtimeConfig',
replacement: './runtimeConfig.browser',
},
]
}
})
不使用TypeScript,所以不需要修改tsconfig.json。
3. 将API和数据库连接到应用程序上。
创建GraphQL API和数据库。
amplify add api
❯ amplify add api
? Select from one of the below mentioned services: (Use arrow keys)
> GraphQL
REST
? Provide API name: todo
? Choose the default authorization type for the API (Use arrow keys)
> API key
Amazon Cognito User Pool
IAM
OpenID Connect
Lambda
? Enter a description for the API key: » 7
? Here is the GraphQL API that we will create. Select a setting to edit or continue (Use arrow keys)
Name: todo
Authorization modes: API key (default, expiration time: 7 days from now)
Conflict detection (required for DataStore): Disabled
> Continue <--- ここはContinueで次へ進む
? Choose a schema template: (Use arrow keys)
> Single object with fields (e.g., “Todo” with ID, name, description)
One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
Blank Schema
在指定的编辑器中打开了模式文件。
√ Do you want to edit the schema now? (Y/n) · yes
Edit the file in your editor: C:\Users\***\myamplifyproject\amplify\backend\api\todo\schema.graphql
似乎是为了使模型的描述被Amplify系统识别而进行的描述。
input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } # FOR TESTING ONLY!
type Todo @model {
id: ID!
name: String!
description: String
}
GraphQL API 的部署
amplify push
√ GraphQL schema compiled successfully.
√ Successfully pulled backend environment dev from the cloud.
√ GraphQL schema compiled successfully.
(メッセージ一部割愛)
Current Environment: dev
┌──────────┬───────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼───────────────┼───────────┼───────────────────┤
│ Api │ todo │ Create │ awscloudformation │
└──────────┴───────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? Yes
√ GraphQL schema compiled successfully.
生成适用于GraphQL API的前端代码。
? Do you want to generate code for your newly created GraphQL API Yes
? Choose the code generation language target (Use arrow keys)
> javascript
typescript
flow
? 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) <--- Enterで進む
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscripti
ons (Y/n) Y
? Enter maximum statement depth [increase from default if your schema is deeply nested] (2) <--- Enterで進む
在CloudFormation上建立环境。
Deployment completed.
Deployed root stack todo [ ======================================== ] 2/2
amplify-todo-dev-**** AWS::CloudFormation::Stack UPDATE_COMPLETE
apitodo AWS::CloudFormation::Stack CREATE_COMPLETE
Deployed api todo [ ======================================== ] 6/6
GraphQLAPI AWS::AppSync::GraphQLApi CREATE_COMPLETE
GraphQLAPINONE********** AWS::AppSync::DataSource CREATE_COMPLETE
GraphQLAPIDefaultApiKey**** AWS::AppSync::ApiKey CREATE_COMPLETE
GraphQLAPITransformerSchema3C… AWS::AppSync::GraphQLSchema CREATE_COMPLETE
Todo AWS::CloudFormation::Stack CREATE_COMPLETE
CustomResourcesjson AWS::CloudFormation::Stack CREATE_COMPLETE
√ Generated GraphQL operations successfully and saved at src\graphql
确认amplify的状态
amplify status
Current Environment: dev
┌──────────┬───────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼───────────────┼───────────┼───────────────────┤
│ Api │ todo │ No Change │ awscloudformation │
└──────────┴───────────────┴───────────┴───────────────────┘
GraphQL endpoint: https://********.appsync-api.us-east-1.amazonaws.com/graphql
GraphQL API KEY: ************
GraphQL transformer version: 2
对API进行测试。
在控制台上确认。(虽然建议使用Amplify Studio,但暂时可以在AWS控制台上确认)
可以执行查询并确认。
amplify console
将前端与API连接
使用GraphQL的操作说明
改写App.vue文件。(教程中分为3个步骤,但下面是最终版。)
<template>
<div id="app">
<h1>Todo App</h1>
<input type="text" v-model="name" placeholder="Todo name" />
<input type="text" v-model="description" placeholder="Todo description" />
<button v-on:click="createTodo">Create Todo</button>
<div v-for="item in todos" :key="item.id">
<h3>{{ item.name }}</h3>
<p>{{ item.description }}</p>
</div>
</div>
</template>
<script>
import { API } from 'aws-amplify';
import { createTodo } from './graphql/mutations';
import { listTodos } from './graphql/queries';
import { onCreateTodo } from './graphql/subscriptions';
export default {
name: 'App',
async created() {
this.getTodos();
},
data() {
return {
name: '',
description: '',
todos: []
};
},
created() {
this.getTodos();
this.subscribe();
},
methods: {
async createTodo() {
const { name, description } = this;
if (!name || !description) return;
const todo = { name, description };
this.todos = [...this.todos, todo];
await API.graphql({
query: createTodo,
variables: { input: todo }
});
this.name = '';
this.description = '';
},
async getTodos() {
const todos = await API.graphql({
query: listTodos
});
this.todos = todos.data.listTodos.items;
},
subscribe() {
API.graphql({ query: onCreateTodo }).subscribe({
next: (eventData) => {
let todo = eventData.value.data.onCreateTodo;
if (this.todos.some((item) => item.name === todo.name)) return; // remove duplications
this.todos = [...this.todos, todo];
}
});
}
}
};
</script>
4. 增加身份验证
在Amplify上的身份验证
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 <--- Usernameを選択
Do you want to configure advanced settings? No, I am done. <--- No, I am done.を選択
√ Successfully added auth resource todo****** locally
执行部署操作。
amplify push
使用CloudFormation来创建Cognito。
┌──────────┬───────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼───────────────┼───────────┼───────────────────┤
│ Auth │ todo****** │ Create │ awscloudformation │
├──────────┼───────────────┼───────────┼───────────────────┤
│ Api │ todo │ No Change │ awscloudformation │
└──────────┴───────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? Yes
Deployment completed.
Deployed root stack todo [ ======================================== ] 3/3
amplify-todo-dev-**** AWS::CloudFormation::Stack UPDATE_COMPLETE
authtodo***** AWS::CloudFormation::Stack CREATE_COMPLETE
apitodo AWS::CloudFormation::Stack UPDATE_COMPLETE
Deployed auth todo***** [ ======================================== ] 10/10
UserPool AWS::Cognito::UserPool CREATE_COMPLETE
UserPoolClientWeb AWS::Cognito::UserPoolClient CREATE_COMPLETE
UserPoolClient AWS::Cognito::UserPoolClient CREATE_COMPLETE
UserPoolClientRole AWS::IAM::Role CREATE_COMPLETE
UserPoolClientLambda AWS::Lambda::Function CREATE_COMPLETE
UserPoolClientLambdaPolicy AWS::IAM::Policy CREATE_COMPLETE
UserPoolClientLogPolicy AWS::IAM::Policy CREATE_COMPLETE
UserPoolClientInputs Custom::LambdaCallout CREATE_COMPLETE
IdentityPool AWS::Cognito::IdentityPool CREATE_COMPLETE
IdentityPoolRoleMap AWS::Cognito::IdentityPoolRol… CREATE_COMPLETE
创建登录界面
在App.vue中添加身份验证内容。(请原谅布局可能不够合适的地方…)
<template>
<div id="app">
<authenticator>
<template v-slot="{ user, signOut }">
<h2>Hello {{ user.username }}!</h2>
<button @click="signOut">Sign Out</button>
<h2>Todo App</h2>
<input type="text" v-model="name" placeholder="Todo name" />
<input type="text" v-model="description" placeholder="Todo description" />
<button v-on:click="createTodo">Create Todo</button>
<div v-for="item in todos" :key="item.id">
<h3>{{ item.name }}</h3>
<p>{{ item.description }}</p>
</div>
</template>
</authenticator>
</div>
</template>
<script>
import { API } from 'aws-amplify';
import { createTodo } from './graphql/mutations';
import { listTodos } from './graphql/queries';
import { onCreateTodo } from './graphql/subscriptions';
import { Authenticator } from '@aws-amplify/ui-vue'; // 追加
import '@aws-amplify/ui-vue/styles.css'; // 追加
export default {
name: 'App',
async created() {
this.getTodos();
},
data() {
return {
name: '',
description: '',
todos: []
};
},
components: { // 追加
Authenticator
},
created() {
this.getTodos();
this.subscribe();
},
methods: {
async createTodo() {
const { name, description } = this;
if (!name || !description) return;
const todo = { name, description };
this.todos = [...this.todos, todo];
await API.graphql({
query: createTodo,
variables: { input: todo }
});
this.name = '';
this.description = '';
},
async getTodos() {
const todos = await API.graphql({
query: listTodos
});
this.todos = todos.data.listTodos.items;
},
subscribe() {
API.graphql({ query: onCreateTodo }).subscribe({
next: (eventData) => {
let todo = eventData.value.data.onCreateTodo;
if (this.todos.some((item) => item.name === todo.name)) return; // remove duplications
this.todos = [...this.todos, todo];
}
});
}
}
};
</script>
5. 部署和托管应用程序 hé
增加主机选项
amplify add hosting
? Select the plugin module to execute ... (Use arrow keys or type to filter)
❯ Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
Amazon CloudFront and S3
? Choose a type (Use arrow keys)
Continuous deployment (Git-based deployments)
> Manual deployment
Learn more
发布应用程序
amplify publish
❯ amplify publish
(略)
Current Environment: dev
┌──────────┬────────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼────────────────┼───────────┼───────────────────┤
│ Hosting │ amplifyhosting │ Create │ awscloudformation │
├──────────┼────────────────┼───────────┼───────────────────┤
│ Api │ todo │ No Change │ awscloudformation │
├──────────┼────────────────┼───────────┼───────────────────┤
│ Auth │ todo06ef4fc2 │ No Change │ awscloudformation │
└──────────┴────────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? Yes
Deployment completed.
Deployed root stack todo [ ======================================== ] 4/4
amplify-todo-dev-****** AWS::CloudFormation::Stack UPDATE_COMPLETE
apitodo AWS::CloudFormation::Stack UPDATE_COMPLETE
hostingamplifyhosting AWS::CloudFormation::Stack CREATE_COMPLETE
authtodo******** AWS::CloudFormation::Stack UPDATE_COMPLETE
Deployed hosting amplifyhosting [ ======================================== ] 1/1
AmplifyBranch AWS::Amplify::Branch CREATE_COMPLETE
(略)
Publish started for amplifyhosting
> myamplifyproject@0.0.0 build
> vite build
(略)
√ Zipping artifacts completed.
√ Deployment complete!
https://dev.***********.amplifyapp.com
更新方式
只要进行修正,就需要重新开始。
amplify publish
6. 环境清理
如果要删除创建的环境,请执行以下操作。
amplify delete