AWS Amplify에 웹 애플리케이션 배포
시작 안내서
모듈 2: 프런트엔드 구축 및 API 연결
이 모듈에서는 API를 Amplify 프로젝트에 연결하는 방법을 배워봅니다.
소개
이 모듈에서는 웹 애플리케이션용 프런트엔드를 구축하고, GraphQL API를 사용하여 API(애플리케이션 프로그래밍 인터페이스)에 연결합니다. GraphQL는 API용 쿼리 언어로, 애플리케이션에서 데이터를 검색 및 업데이트하도록 지원합니다.
배우게 될 내용
- 기본 React 프런트엔드 애플리케이션 생성
- 애플리케이션에서 GraphQL API 호출
- 애플리케이션의 프런트엔드에서 API 호출
소요 시간
10분
모듈 선행 조건
- 관리자 수준의 액세스 권한이 있는 AWS 계정**
- 권장 브라우저: 최신 버전의 Chrome 또는 Firefox
[**]생성된 지 24시간이 지나지 않은 계정은 이 자습서를 완료하는 데 필요한 서비스에 액세스할 권한이 아직 없을 수 있습니다.
구현
Amplify 라이브러리 설치
Amplify React 라이브러리 @aws-amplify/ui-react를 설치해야 합니다(React UI 구성요소 포함).
다음 명령을 실행하여 이를 설치합니다.
npm install @aws-amplify/ui-react
이제 애플리케이션에 대한 프런트엔드를 생성해야 합니다. src/App.js 파일을 열고 파일의 전체 내용을 다음 코드로 바꿉니다.
import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';
import Amplify from 'aws-amplify';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
function App() {
return (
<div>
<h1>Notes App</h1>
<AmplifySignOut />
</div>
);
}
export default withAuthenticator(App);
애플리케이션 테스트
이제 앱을 실행하고 테스트할 수 있습니다.
npm start
http://localhost:3000의 개발 서버가 시작되며 브라우저에서 페이지가 열립니다. 서비스를 사용하기에 앞서 가입 메시지가 표시됩니다. 이 데이터는 프로젝트의 Congnito 데이터베이스에 저장되며, 사용자만 액세스할 수 있습니다. 로그인하면 아직 아무것도 추가하지 않았으므로 해당 앱은 Notes App과 로그인 버튼이 있는 이 헤딩만을 보여줍니다. 다음으로 API를 앱에 추가합니다. 서버를 다시 중단시키기 위해 ctrl + c를 사용할 수 있습니다.

몇 개의 CLI 명령과 코드 줄만으로 로그인 플로우가 있는 단일 페이지 애플리케이션을 만들었습니다. 이 애플리케이션은 단지 틀일 뿐이며 로그인은 아직 작동하지 않습니다. 계속해서 다음 섹션에서 프로그램에 기능을 추가하십시오.
Amplify에 GraphQL API 추가
이제 애플리케이션에 API를 추가할 것입니다. Amplify는 AWS AppSync 및 Amazon DynamoDB를 사용하여 GraphQL API를 구동합니다. AppSync는 관리형 GraphQL 서비스로 API를 관리하고, Amazon DynamoDB는 NoSQL 데이터베이스로 API가 사용할 데이터를 저장합니다.
API를 추가하려면 amplify add api를 실행하고, 질문에 다음 옵션을 선택합니다(> 기호로 시작하는 라인). 이 단계 동안 인증 공급자에 대한 질문을 할 것이며, 이는 향후 가이드에서 사용됩니다.
GraphQL 스키마는 객체와 그 필드를 나타냅니다. GraphQL 스키마를 정의해야 하며, Amplify는 필수 DynamoDB 표를 생성하고 GraphQL를 구성하여 사용자의 읽기, 쓰기, 그리고 삭제를 처리합니다. amplify/backend/api/amplifyapp/schema.graphql 파일을 열고 콘텐츠를 다음으로 교체합니다.
amplify add api
? Please select from one of the below mentioned services:
❯ GraphQL
REST
? Provide API name: amplifyapp
? Choose the default authorization type for the API
API key
❯ Amazon Cognito User Pool
IAM
OpenID Connect
? Do you want to configure advanced settings for the GraphQL API
? Do you want to use the default authentication and security configuration?
❯ Default configuration
Default configuration with Social Provider (Federation)
Manual configuration
I want to learn more.
? How do you want users to be able to sign in?
◯ Email
❯◉ Username
◯ Phone number
? Do you want to configure advanced settings?
❯ No, I am done.
Yes, I want to make some additional changes.
? Do you have an annotated GraphQL schema? No
? Choose a schema template:
❯ Single object with fields (e.g., “Todo” with ID, name, description)
One-to-many relationship (e.g., “Blogs” with “Posts” and “Comments”)
Objects with fine-grained access control (e.g., a project management app with owner-bas
ed authorization)
? Do you want to edit the schema now? Yes
GraphQL 스키마 생성
GraphQL 스키마는 객체와 그 필드를 나타냅니다. GraphQL 스키마를 정의해야 하며, Amplify는 필수 DynamoDB 표를 생성하고 GraphQL를 구성하여 사용자의 읽기, 쓰기, 그리고 삭제를 처리합니다. amplify/backend/api/amplifyapp/schema.graphql 파일을 열고 콘텐츠를 다음으로 교체합니다.
type Note @model @auth(rules: [{ allow: owner }]) {
id: ID!
text: String!
}
이 스키마는 ID와 텍스트가 필수 필드인 노트 유형을 정의합니다. 또한 Amplify GraphQL Transform 라이브러리의 일부인 지침을 포함합니다.
@model: @model로 주석을 다는 유형이며 DynamoDB에 저장되고, 이를 위해 CRUDL(생성, 읽기, 업데이트, 삭제, 나열) 동작이 자동으로 생성됩니다.
@auth: @auth로 주석을 단 유형으로 인증 규칙의 집합으로 보호됩니다. 여기서 소유자 권한 부여를 사용하여 노트의 소유자만 이에 액세스하고 수정할 수 있도록 합니다.
애플리케이션 배포
이제 amplify push를 실행하여 Amplify 웹 애플리케이션을 배포할 준비가 되었습니다. 이렇게 하면 애플리케이션이 AWS 계정에 업로드되고 Amplify는 배포 중인 변경 사항을 보여주며 배포 확인을 요청합니다.
✔ Successfully pulled backend environment dev from the cloud.
Current Environment: dev
┌──────────┬────────────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Auth │ amplifyapp6177aede │ Create │ awscloudformation │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Api │ amplifyapp │ 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
배포하려면 몇 분 정도 소요되며 사용자를 위해 생성된 리소스 목록이 표시됩니다. Amplify는 다음 작업을 수행했습니다.
- GraphQL 작업의 세 가지 유형(쿼리, 변형 및 구독) 모두를 사용하여 AWS AppSync가 지원한 GraphQL API를 생성했습니다.
- 노트를 생성, 검색 및 업데이트하는 데 필요한 GraphQL 작업을 사용하여 src/graphql/ 폴더 내부에 코드를 생성했습니다.
- 애플리케이션과 함께 생성된 모든 노트를 저장하기 위해 DynamoDB 표를 생성했습니다.
API 사용을 위해 프런트엔드 업데이트
방금 배포한 새 API를 사용하려면 src/App.js 파일의 콘텐츠를 다음 코드로 변경하여 업데이트합니다.
import { Component } from 'react';
import Amplify, { API, graphqlOperation } from 'aws-amplify';
import { createNote, deleteNote } from './graphql/mutations';
import { listNotes } from './graphql/queries';
import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
class AddNote extends Component {
constructor(props) {
super(props);
this.state = { text: '' };
}
handleChange = (event) => {
this.setState({ text: event.target.value });
}
handleClick = () => {
this.props.addNote(this.state);
this.setState({ text: '' });
}
render() {
return (
<div style={styles.form}>
<input
value={this.state.text}
onChange={this.handleChange}
placeholder="New Note"
style={styles.input}
/>
<button onClick={this.handleClick} style={styles.addButton}>Add Note</button>
</div>
);
}
}
class NotesList extends Component {
render() {
return (
<div>
{this.props.notes.map(note =>
<div key={note.id} style={styles.note}>
<p>{note.text}</p>
<button onClick={() => { this.props.deleteNote(note) }} style={styles.deleteButton}>x</button>
</div>
)}
</div>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = { notes: [] };
}
async componentDidMount() {
var result = await API.graphql(graphqlOperation(listNotes));
this.setState({ notes: result.data.listNotes.items });
}
deleteNote = async (note) => {
const id = {
id: note.id
};
await API.graphql(graphqlOperation(deleteNote, { input: id }));
this.setState({ notes: this.state.notes.filter(item => item.id !== note.id) });
}
addNote = async (note) => {
var result = await API.graphql(graphqlOperation(createNote, { input: note }));
this.state.notes.push(result.data.createNote);
this.setState({ notes: this.state.notes });
}
render() {
return (
<div style={styles.container}>
<h1>Notes App</h1>
<AddNote addNote={this.addNote} />
<NotesList notes={this.state.notes} deleteNote={this.deleteNote} />
<AmplifySignOut />
</div>
);
}
}
export default withAuthenticator(App);
const styles = {
container: { width: 480, margin: '0 auto', padding: 20 },
form: { display: 'flex', marginBottom: 15 },
input: { flexGrow: 2, border: 'none', backgroundColor: '#ddd', padding: 12, fontSize: 18 },
addButton: { backgroundColor: 'black', color: 'white', outline: 'none', padding: 12, fontSize: 18 },
note: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 22, marginBottom: 15 },
deleteButton: { fontSize: 18, fontWeight: 'bold' }
}
이제 사용자는 작동하는 애플리케이션을 보유하고 있습니다. 멀티 팩터 인증으로 로그인하면 애플리케이션이 이제 API와 통신하여 노트를 저장/업데이트/삭제할 수 있습니다. 로컬에서 테스트하려면 npm start를 다시 실행하여 확인합니다.
