AWS 入門
建立 React 應用程式
使用 AWS Amplify 建立簡單的 Web 應用程式
單元 4:新增 GraphQL API 和資料庫
在本單元中,您將使用 Amplify CLI 和程式庫來設定 GraphQL API,並將其新增到您的應用程式。
簡介
現在,我們已經建立應用程式並設定了身份驗證,接下來我們要新增一個 API。
在本單元中,您將使用 Amplify CLI 和庫將 API 新增到您的應用程式中。您將建立的 API 是 GraphQL API,它利用了由 Amazon DynamoDB (NoSQL 資料庫) 支援的 AWS AppSync (受管的 GraphQL 服務)。(如需有關 GraphQL 的介紹,請參閱本頁。)
我們將要建立的應用程式是一個記事應用程式,使用者可以用它來建立、刪除和列出筆記。透過本範例,您將能夠很好地了解如何建立許多熱門的 CRUD+L 類型 (建立、讀取、更新、刪除和列出) 應用程式。
您將學到的內容
- 建立和部署 GraphQL API
- 編寫與 API 互動的前端程式碼
主要概念
API – 提供程式開發界面,允許多個軟體仲介之間的通訊和互動。
GraphQL – 以應用程式具類型表示為基礎的查詢語言和伺服器端 API 實作。此 API 表示通過以 GraphQL 類型系統為基礎的結構描述進行聲明。(如需了解有關 GraphQL 的更多資訊,請參閱本頁。)
完成時間
15 分鐘
使用的服務
實作
-
建立 GraphQL API 和資料庫
a.透過從應用程式的根目錄執行以下命令,將 GraphQL API 新增到您的應用程式:
amplify add api ? Please select from one of the below mentioned services: GraphQL ? Provide API name: notesapp ? Choose the default authorization type for the API: API Key ? Enter a description for the API key: demo ? After how many days from now the API key should expire: 7 (or your preferred expiration) ? Do you want to configure advanced settings for the GraphQL API: No, I am done. ? 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 ? Do you want to edit the schema now? Yes
b.在文字編輯器中開啟 GraphQL 結構描述:amplify/backend/api/myapi/schema.graphql。
使用以下結構描述更新檔案:
type Note @model { id: ID! name: String! description: String }
c.儲存檔案。然後返回命令列並按 Enter 鍵以完成 API 設定步驟。
-
部署 API
現在已經在本機對 API 進行了設定,是時候部署它了。為此,請執行 Amplify push 命令:
amplify push --y
這將完成 3 項操作:
- 建立 AppSync API
- 建立 DynamoDB 資料表
- 在 src/graphql 資料夾中建立可用於查詢 API 的本機 GraphQL 操作
要查看您帳戶中的 GraphQL API,請執行以下命令:
amplify console api > Choose GraphQL
要查看您帳戶中的 Amplify 應用程式,請執行以下命令:
amplify console
-
編寫與 API 互動的前端程式碼
現在後端已經部署完畢,讓我們編寫一些程式碼,以允許使用者建立、列出和刪除筆記。
使用以下程式碼更新 src/App.js:
import React, { useState, useEffect } from 'react'; import './App.css'; import { API } from 'aws-amplify'; import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'; import { listNotes } from './graphql/queries'; import { createNote as createNoteMutation, deleteNote as deleteNoteMutation } from './graphql/mutations'; const initialFormState = { name: '', description: '' } function App() { const [notes, setNotes] = useState([]); const [formData, setFormData] = useState(initialFormState); useEffect(() => { fetchNotes(); }, []); async function fetchNotes() { const apiData = await API.graphql({ query: listNotes }); setNotes(apiData.data.listNotes.items); } async function createNote() { if (!formData.name || !formData.description) return; await API.graphql({ query: createNoteMutation, variables: { input: formData } }); setNotes([ ...notes, formData ]); setFormData(initialFormState); } async function deleteNote({ id }) { const newNotesArray = notes.filter(note => note.id !== id); setNotes(newNotesArray); await API.graphql({ query: deleteNoteMutation, variables: { input: { id } }}); } return ( <div className="App"> <h1>My Notes App</h1> <input onChange={e => setFormData({ ...formData, 'name': e.target.value})} placeholder="Note name" value={formData.name} /> <input onChange={e => setFormData({ ...formData, 'description': e.target.value})} placeholder="Note description" value={formData.description} /> <button onClick={createNote}>Create Note</button> <div style={{marginBottom: 30}}> { notes.map(note => ( <div key={note.id || note.name}> <h2>{note.name}</h2> <p>{note.description}</p> <button onClick={() => deleteNote(note)}>Delete note</button> </div> )) } </div> <AmplifySignOut /> </div> ); } export default withAuthenticator(App);
我們的應用程式有 3 個主要函數:
- fetchNotes - 此函數使用 API 類將查詢傳送到 GraphQL API 並擷取筆記清單。
- createNote - 此函數也使用 API 類將變動傳送給 GraphQL API,主要區別在於,在此函數中,我們傳遞了 GraphQL 變動所需的變數,以便使用表單資料建立新的筆記。
- deleteNote - 與 createNote 一樣,此函數傳送 GraphQL 變動以及一些變數,但不是建立筆記,而是刪除筆記。
-
執行應用程式
要測試該應用程式,執行 start 命令:
npm start