# [AWS] 使用 Amplify CLI 建立全端應用程式 ###### tags: `AWS` [TOC] --- :::warning Amplify 是給前端用的 CLI 工具 可以建立 RESTful API, Auth 和 GraphQL ::: ## 給前端用的 AWS 工具 - Amplify 建立 API, Auth 適合靜態的前端環境 (例如部落格) - AppSync 全託管的 WebQL 可以即時更新,彈性自動擴展或減縮 - AWS Device Farm --- ## Amplify 三階段 ### Develop - 使用 CLI 或 Admin UI 設定後端 - 支援網頁前端三大框架、IOS、Android、Flutter ### Deploy - 自動部署 ![](https://i.imgur.com/ae5jXBY.png) ### Deliver --- ## Amplify CLI 指令 :::warning $ amplify init $ amplify push $ amplify status $ amplify delete $ amplify add <category> ::: ## Amplify Client 端工具 `$ npm i aws-amplify` ```jsx //登入驗證 import { Auth } from 'aws-amplify' Auth.signIn('myusername', 'mypassword') Auth.currentAuthenticatedUser() Auth.signOut() ``` --- ## 結合其他服務來使用 Amplify ![](https://i.imgur.com/VAG3LyE.png) ### :star:建立新的 RESTful API :::info Lambda API Gateway ::: #### 初始化 ``` $ amplify add api # 選擇 REST 選項 ``` - 新增 Path : `/todo` (使用 Lambda) - 選擇語言:NodeJS - 可以結合 DynamoDB 來部署 #### 撰寫 API 程式 `amplify/backend/function/<FUNCTION_NAME>/src/app.js` ```javascript app.get('/items', function (req, res) { // new code goes here }) ``` #### 部署 部署新的 API (API Gateway) ``` $ amplify push ``` #### 前端互動 ```javascript import { API } from 'aws-amplify' API.get('/items') .then(data => console,log({ data })) .catch(err => console.log({ err })) ``` --- ### :star:建立登入驗證 :::info Cognito ::: `$ amplify add auth` ```jsx import { Auth } from 'aws-amplify' Auth.signUp('username', 'password', { attributes: { email: 'jane@doe.com' } }) Auth.signIn('myusername', 'mypassword') Auth.currentAuthenticatedUser() Auth.signOut() ``` --- ### :star:用 GraphQL 建立 API :::info AppSync DynamoDB ::: #### 初始化 ``` $ amplify add api # 選擇 GraphQL ``` #### 定義 Schema ```graphql type TODO @model { id:ID! name: String description: String completed: Boolean } ``` #### 部署 ``` $ amplify push ``` #### 前端互動 部署完成後,就可以在 Client 端進行互動 ```javascript import { API, GraphqlOperation } from 'aws-amplify' import { listTodos } from './src/graphql/queries' API.graphql(graphqlOperation(listTodos)) .then(data => console.log(data)) .catch(err => console.log({ err})) ``` --- ### :star:新增 Analytics Pinpoint - 彈性可擴展的行銷通訊服務 - 適用於訊息、行銷活動 - 追蹤使用者行為 - 發送簡訊、電子郵件時 -> 收集點擊、觀看的資訊 ``` $ amplify add analytics $ amplify push ``` Client 端 ```javascript import { Analytics } from '' Analytics.record({ name: 'albumVisit' }) Analytics.record({ name: 'albumvisit', attributes: { genre: 'nu-metal', artist: 'RATM' } }) ``` --- ## CI/CD 支援:git branch 來切分環境 ## 範例:建立 React App - 官方教程 https://aws.amazon.com/tw/getting-started/hands-on/build-react-app-amplify-graphql/ ## Reference AWS QuickStart - 前端入門系列 React 程式快速上雲 https://hktw-resources.awscloud.com/aws-quickstart-introduction-to-aws-amplify/aws-quickstart-introduction-to-aws-amplify-video