SEOUL
Amplify를 통해 클라우드 기반
모바일 앱 개발하기
박태성 / Javascript Dev, 아이디어샘
Speaker
박태성
TaeSeong Park
@geoseong in AWSKRUG
#gudi organizer
@geoseong in react-native-seoul
co-organizer
geoseong in Github
Open Source Challenger
목차
What is Amplify?
Overview from init to deploy
Amplify 프로젝트 시작
API: API(AppSync) 추가하기
Auth: 회원관리(Cognito) 추가하기
Storage: 저장소(S3) 추가하기
Mock & Test: 로컬 디버깅 하기
Analytics: 분석 서비스(Pinpoint) 추가하기
New Amplify Feature: Amplify DataStore
DEMO
What is Amplify?
• 모바일 및 웹 어플리케이션을 위한 개발
플랫폼
• Open Source
• 제공 기능
Analytics PubSub
API Push Notifications
Authentication Storage
Interactions XR(AR/VR)
Predictions DataStore NEW
Overview from init to deploy
$	amplify	configure AWS IAM User 추가
$	amplify	init Amplify 프로젝트 생성
$	amplify	add	<category-name> 기능 추가
$	amplify	<category-name>	update 기능 업데이트
$	amplify	<category-name>	remove 기능 삭제
$	amplify	status Amplify 프로젝트 상태 보기
$	amplify	pull Amplify 백엔드 최신상태 받아오기
$	amplify	mock 오프라인 로컬 테스트
$	amplify	push Amplify로 생성된 리소스 온라인 배포
$	amplify	delete Amplify로 생성된 모든 리소스 삭제
$	amplify	console	<category-name> AWS 웹 콘솔로 이동
$ amplify	env	<subcommand> 환경 변경하기
Overview from init to deploy
Amplify 프로젝트 시작
$	npm install	-g	@aws-amplify/cli
$	npm install	-g	expo-cli
$	expo	init
(App/Slug	name:	JustApp)
$	cd	JustApp
$	npm install	aws-amplify
$	npm install	aws-amplify-react-native
Amplify 프로젝트 시작
$	amplify	init
Screenshot of Nader Dabit’s “Building Serverless
Web Applications with AWS Amplify - AWS Online
Tech Talks“ on YouTube
Amplify 프로젝트 시작
Amplify 프로젝트 시작
import Amplify from 'aws-amplify';
import config from './aws-exports’;
Amplify.configure(config);
App.js
API(AppSync) 추가하기
AWS AppSync
- 관리형 GraphQL 서버리스 서비스
- 실시간 조회기능(subscription)
- 오프라인 프로그래밍 모델 및 온/오프라인 데이터 동기화 지원
API(AppSync) 추가하기
projectname
API name
API(AppSync) 추가하기
amplify/backend/api/{프로젝트명}/schema.graphql
type Blog @model {
id:	ID!
name:	String!
posts:	[Post]	@connection(name:	"BlogPosts")
}
type Post @model @auth(rules:	[{	allow: owner,	queries:	null }])	{
id:	ID!
title:	String!
blog:	Blog @connection(name:	"BlogPosts")
comments:	[Comment]	@connection(name:	"PostComments)
}
type Comment @model {
id:	ID!
content:	String
post:	Post @connection(name:	"PostComments")
}
projectname
API(AppSync) 추가하기
GraphQL Transform
- 지시어(directive) 사용
- @model, @auth, @function, @connection, …
- GraphQL SDL(Schema Definition Language)을 사용하여 데이터 모델 정의 후 AWS CloudFormation
스택으로 변환 시켜줌
@model
• CRUD & List
• Configure DynamoDB
Table
• Subscription
• Resolvers
@connection
• Data간 모델 관계 설정 및
관련 resolver 생성
@auth
• 인증 규칙 정의
API(AppSync) 추가하기
import Amplify,	{	API,	graphqlOperation }	from 'aws-amplify';
import * as queries from './graphql/queries';
import * as mutations from './graphql/mutations';
import * as subscriptions from './graphql/subscriptions';
//	Simple	query
const allTodos =	await API.graphql(
graphqlOperation(queries.listTodos)
);
//	Query	using	a	parameter
const oneTodo =	await API.graphql(
graphqlOperation(queries.getTodo,	{	id: 'some	id’ })
);
//	Mutation
const todoDetails =	{
name: 'Todo 1’,
description: 'Learn	AWS	AppSync'
};
const newTodo =	await API.graphql(
graphqlOperation(mutations.createTodo,	{input:todoDetails})
);
//	Subscribe	to	creation	of	Todo
const subscription =	API.graphql(
graphqlOperation(subscriptions.onCreateTodo)
).subscribe({
next: (todoData)	=> console.log(todoData)
});
//	Stop	receiving	data	updates	from	the	
subscription
subscription.unsubscribe();
export const getTodo =	`query	GetTodo($id:	ID!)	{
getTodo(id:	$id)	{
id
clientId
name
description
city
}
}
API(AppSync) 추가하기
Subscription 구현 시 주의
import App from './App';
import {AppRegistry}	from 'react-native';
import {name as appName}	from './app.json';
AppRegistry.registerComponent(appName,	()	=> App);
global.Buffer =	global.Buffer ||	require('buffer').Buffer
GitHub Issue
https://github.com/aws-amplify/amplify-js/issues/4667
API(AppSync) 추가하기
$	amplify	push
($ amplify	push	api)
Auth: 회원관리(Cognito) 추가하기
Amazon Cognito
- 회원 통합관리 서비스
- 소셜 로그인 가능 (Facebook, Google, Apple, SAML, OpenID Connect)
- Amplify Framework에서 React, React-Native, Angular, Ionic 전용 회원
관리 컴포넌트 지원
Auth: 회원관리(Cognito) 추가하기
App.js
$ amplify	add	auth
CLI
import {	withAuthenticator }	from 'aws-amplify-react-native';
const App =	props => {
...
}
export default withAuthenticator(App,	{	includeGreetings: true });
Auth: 회원관리(Cognito) 추가하기
Auth: 회원관리(Cognito) 추가하기
HOC를 감싸는 게 싫다면…
import {	Auth }	from 'aws-amplify';
const signUpRes =	await Auth.signUp({
username: name,
password: pw,
attributes: {
nickname: nickname,
phone_number: `+82${tel}`,
email: email,
'custom:team': team,},
})
const confirmSignUpRes =	await Auth.confirmSignUp(name,	
confirmCode,	{
forceAliasCreation: true,
})
const user =	await Auth.signIn(username,	userPw)
const sessionObj =	await Auth.currentSession()
const signOuttedObj =	await Auth.signOut()
Auth: 회원관리(Cognito) 추가하기
$	amplify	push
($ amplify	push	auth)
Storage: 저장소(S3) 추가하기
Amazon S3
- 내구성 99.9999999999%의 저장소
- 정적 페이지 호스팅 가능
Storage: 저장소(S3) 추가하기
$ amplify	add	storage
? Please select from one of the below mentioned services: Content (Images, audio,
video, etc.)
? Please provide a friendly name for your resource that will be used to label this category
in the project: awskrugGallery
? Please provide bucket name: awskrug-gallery
? Who should have access: Auth users only
? What kind of access do you want for Authenticated users? (Press <space> to select,
<a> to toggle all, <i> to invert selection)create/update, read, delete
? Do you want to add a Lambda Trigger for your S3 Bucket? No
Successfully added resource awskrugGallery locally
Bucket name(Unique)
Resource name
Storage: 저장소(S3) 추가하기
import {	Storage }	from 'aws-amplify’;
const fileData =	await Storage.get('test.txt')
const result =	await Storage.remove('test.txt')
const fileList =	await Storage.list('photos/')
const uploadToStorage =	async pathToImageFile => {
try {
const response =	await fetch(pathToImageFile)
const blob =	await response.blob()
Storage.put('yourKeyHere.jpeg',	blob,	{
contentType: 'image/jpeg’,
progressCallback(progress)	{
console.log(`${progress.loaded}/${progress.total}`);
},
})
}	catch	(err)	{
console.log(err)
}
}
Storage: 저장소(S3) 추가하기
저장소 권한
Public
- 모든 유저에게 모든 권한 부여되어 있음
- public/ 경로에 보관
Protected
- 모든 유저에게 읽기전용
- 생성자에게만 모든 권한 부여
- protected/{user_identity_id}/ 경로에 보관
Private
- 모든 유저 볼 수 없음
- 개별 사용자만 액세스 가능
- private/{user_identity_id}/ 경로에 보관
//	Public	level:
const publicResult =	await Storage.put('test.txt',	'Hello’)
.catch(err => console.log(err));
//	Protected	level:
const protectedResult =	await Storage.put(
'test.txt’,
'Protected	Content',	{
level: 'protected’,
contentType:	'text/plain’,
})
.catch(err => console.log(err));
//	Private	level:
const privateResult =	await Storage.put(
'test.txt’,	
'Private	Content',	{
level: 'private’,
contentType:	'text/plain’,
}).catch(err => console.log(err));
Storage: 저장소(S3) 추가하기
$	amplify	push
($ amplify	push	storage)
Mock & Test: 로컬 디버깅 하기
$	amplify	mock
($ amplify	mock	api,	amplify	mock	storage)
Mock	Storage	endpoint	is	running	at	http://localhost:20005
GraphQL schema	compiled	successfully.
Edit	your	schema	at	/.../.graphql or	place	.graphql files	in	a	directory	at	/.../schema
Creating	table	PostTable locally
Creating	table	NoteTable locally
Running	GraphQL codegen
✔ Generated	GraphQL operations	successfully	and	saved	at	src/graphql
✔ Code	generated	successfully	and	saved	in	file	src/API.ts
AppSync	Mock	endpoint	is	running	at	http://{my	network	ip address}:20002
Mock & Test: 로컬 디버깅 하기
aws-exports.js
aws-exports.js (mocking mode)
const awsmobile =	{
...
"aws_appsync_graphqlEndpoint":	"https://cd767mzgajba3j3zurptndxhom.appsync-api.ap-northeast-2.amazonaws.com/graphql",...
};
const awsmobile =	{
...
"aws_appsync_graphqlEndpoint":	"http://192.168.123.164:20002/graphql",
"aws_appsync_apiKey": "da2-fakeApiId123456",
”aws_appsync_dangerously_connect_to_http_endpoint_for_testing": true,
"aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing": true
};
$	amplify	mock
Mock & Test: 로컬 디버깅 하기
Analytics: 분석 서비스(Pinpoint) 추가하기
Amazon Pinpoint
- 클라이언트로부터 이벤트 기록
- 세션 데이터 자동 기록
- 인증 데이터(로그인/로그아웃/인증실패) 자동 기록
- Email, SMS, Voice, Push Notification
Analytics: 분석 서비스(Pinpoint) 추가하기
$	amplify	add	analytics
CLI
import {	Analytics }	from 'aws-amplify';
Analytics.record({
name: ‘Test	Event	1’,	
//	Attribute	values	must	be	strings
attributes: {	username: 'geoseong' }
});
js
Analytics: 분석 서비스(Pinpoint) 추가하기
Analytics: 분석 서비스(Pinpoint) 추가하기
$	amplify	push
($ amplify	push	analytics)
• Multi Platform on-device persistent storage engine
• AWS 연결없이 오프라인 용도로만으로 사용 가능
• GraphQL을 이용한 모바일/웹 앱과 클라우드 사이의 자동 동기화
New Amplify Feature: Amplify DataStore
New Amplify Feature: Amplify DataStore
offline
New Amplify Feature: Amplify DataStore
DataStore Storage Adapter
- Mobile
- SQLite
- Web
- IndexedDB
New Amplify Feature: Amplify DataStore
$	npx amplify-app@latest
"scripts":	{
…
"amplify-modelgen":
"node	amplify/scripts/amplify-modelgen.js",
"amplify-push":	"node	amplify/scripts/amplify-push.js"
},
package.json
New Amplify Feature: Amplify DataStore
amplify/backend/api/{프로젝트명}/schema.graphql
enum PostStatus {
ACTIVE
INACTIVE
}
type Post @model {
id:	ID!
title:	String!
rating:	Int!
status:	PostStatus!
}
$ npm run amplify-modelgen
New Amplify Feature: Amplify DataStore
$	npm i @aws-amplify/core	@aws-amplify/datastore
CLI
New Amplify Feature: Amplify DataStore
import {	DataStore,	Predicates }	from '@aws-amplify/datastore';
import {	Todo }	from '../models';
//	Load	todos from	DataStore
let dataStoreItems =	await DataStore.query(Todo);
//	Create	todo in	DataStore
const newTodo =	await DataStore.save(
new Todo({
task: task.task
})
);
//	Update	DataStore
const original =	await DataStore.query(Todo,	todoId);
await DataStore.save(
Todo.copyOf(original,	updated => {
updated.task =	todoText;
})
);
//	Remove	from	DataStore
const todelete =	await
DataStore.query(Todo,	deleteTodo.id);
DataStore.delete(todelete);
//	Subscription: do	not	use	await
DataStore.observe(Todo).subscribe(task =>
{
if (task.opType ===	'INSERT')	{
//	do	sth...
}
});
New Amplify Feature: Amplify DataStore
Query with Predicates
• Strings:	eq |	ne |	le |	lt |	ge |	gt |	contains |	notContains |	beginsWith |	between
• Numbers:	eq |	ne |	le |	lt |	ge |	gt |	between
• Lists:	contains |	notContains
//	AND	statement:	multiple	condition
const posts =	await DataStore.query(Post,	c =>
c.rating("gt",	4).status("eq",PostStatus.ACTIVE));
//	OR	statement
const posts =	await DataStore.query(Post,	c => c.or(
c => c.rating("gt",	4).status("eq",	PostStatus.ACTIVE)
));
New Amplify Feature: Amplify DataStore
Sync with Cloud
import Amplify from 'aws-amplify';
import config from './aws-exports’;
Amplify.configure(config);
App.js
$ amplify init
CLI
New Amplify Feature: Amplify DataStore
$	amplify	push
Sync with Cloud
Amplify React-Native Project Finished!
$	amplify	console
$	amplify	console api
그 외 가능한 기능들
• 기능별 개별 Framework설치 가능
@aws-amplify/storage, @aws-amplify/api, @aws-amplify/auth, …
• Cognito, S3, DynamoDB Lambda trigger
• Create Lambda function
• Multiple Serverless Environments
• Utilities
• Service Worker
• LRU cache
• I18n
• Hub
Hub.dispatch(‘channel’, obj); Hub.listen(‘channel’, () => {}); Hub.remove(‘channel’, () => {});
• Logger
DEMO
https://github.com/geoseong
/study-amplify-with-react-native
Amplify 사용 후기
• 혼자 백엔드 & 프론트엔드 개발을 빠르게 할 때 매우 유용
• 그러나 아직은 소규모의 앱에서만 사용하는 것이 좋을 듯
• Amplify의 발전 가능성이 매우 높다. 오픈소스니까.
• Thanks to Nader Dabit (@dabit3)
• https://github.com/dabit3/awesome-aws-amplify
Reference
• Building React Native Apps with AWS Amplify
• https://aws-amplify.github.io/docs/js/tutorials/building-react-native-apps/
• Building Serverless Web Applications with React & AWS Amplify
• Author: Nader Dabit (twitter @dabit3)
• https://egghead.io/courses/building-serverless-web-applications-with-
react-aws-amplify
Join AWSKRUG Slack!
http://slack.awskr.org/
Q&A
감사합니다

Amplify를 통해 클라우드 기반 모바일 앱 개발하기 - 박태성(IDEASAM) :: AWS Community Day 2020

  • 1.
    SEOUL Amplify를 통해 클라우드기반 모바일 앱 개발하기 박태성 / Javascript Dev, 아이디어샘
  • 2.
    Speaker 박태성 TaeSeong Park @geoseong inAWSKRUG #gudi organizer @geoseong in react-native-seoul co-organizer geoseong in Github Open Source Challenger
  • 3.
    목차 What is Amplify? Overviewfrom init to deploy Amplify 프로젝트 시작 API: API(AppSync) 추가하기 Auth: 회원관리(Cognito) 추가하기 Storage: 저장소(S3) 추가하기 Mock & Test: 로컬 디버깅 하기 Analytics: 분석 서비스(Pinpoint) 추가하기 New Amplify Feature: Amplify DataStore DEMO
  • 4.
    What is Amplify? •모바일 및 웹 어플리케이션을 위한 개발 플랫폼 • Open Source • 제공 기능 Analytics PubSub API Push Notifications Authentication Storage Interactions XR(AR/VR) Predictions DataStore NEW
  • 5.
    Overview from initto deploy $ amplify configure AWS IAM User 추가 $ amplify init Amplify 프로젝트 생성 $ amplify add <category-name> 기능 추가 $ amplify <category-name> update 기능 업데이트 $ amplify <category-name> remove 기능 삭제 $ amplify status Amplify 프로젝트 상태 보기 $ amplify pull Amplify 백엔드 최신상태 받아오기 $ amplify mock 오프라인 로컬 테스트 $ amplify push Amplify로 생성된 리소스 온라인 배포 $ amplify delete Amplify로 생성된 모든 리소스 삭제 $ amplify console <category-name> AWS 웹 콘솔로 이동 $ amplify env <subcommand> 환경 변경하기
  • 6.
  • 7.
    Amplify 프로젝트 시작 $ npminstall -g @aws-amplify/cli $ npm install -g expo-cli $ expo init (App/Slug name: JustApp) $ cd JustApp $ npm install aws-amplify $ npm install aws-amplify-react-native
  • 8.
    Amplify 프로젝트 시작 $ amplify init Screenshotof Nader Dabit’s “Building Serverless Web Applications with AWS Amplify - AWS Online Tech Talks“ on YouTube
  • 9.
  • 10.
    Amplify 프로젝트 시작 importAmplify from 'aws-amplify'; import config from './aws-exports’; Amplify.configure(config); App.js
  • 11.
    API(AppSync) 추가하기 AWS AppSync -관리형 GraphQL 서버리스 서비스 - 실시간 조회기능(subscription) - 오프라인 프로그래밍 모델 및 온/오프라인 데이터 동기화 지원
  • 12.
  • 13.
    API(AppSync) 추가하기 amplify/backend/api/{프로젝트명}/schema.graphql type Blog@model { id: ID! name: String! posts: [Post] @connection(name: "BlogPosts") } type Post @model @auth(rules: [{ allow: owner, queries: null }]) { id: ID! title: String! blog: Blog @connection(name: "BlogPosts") comments: [Comment] @connection(name: "PostComments) } type Comment @model { id: ID! content: String post: Post @connection(name: "PostComments") } projectname
  • 14.
    API(AppSync) 추가하기 GraphQL Transform -지시어(directive) 사용 - @model, @auth, @function, @connection, … - GraphQL SDL(Schema Definition Language)을 사용하여 데이터 모델 정의 후 AWS CloudFormation 스택으로 변환 시켜줌 @model • CRUD & List • Configure DynamoDB Table • Subscription • Resolvers @connection • Data간 모델 관계 설정 및 관련 resolver 생성 @auth • 인증 규칙 정의
  • 15.
    API(AppSync) 추가하기 import Amplify, { API, graphqlOperation} from 'aws-amplify'; import * as queries from './graphql/queries'; import * as mutations from './graphql/mutations'; import * as subscriptions from './graphql/subscriptions'; // Simple query const allTodos = await API.graphql( graphqlOperation(queries.listTodos) ); // Query using a parameter const oneTodo = await API.graphql( graphqlOperation(queries.getTodo, { id: 'some id’ }) ); // Mutation const todoDetails = { name: 'Todo 1’, description: 'Learn AWS AppSync' }; const newTodo = await API.graphql( graphqlOperation(mutations.createTodo, {input:todoDetails}) ); // Subscribe to creation of Todo const subscription = API.graphql( graphqlOperation(subscriptions.onCreateTodo) ).subscribe({ next: (todoData) => console.log(todoData) }); // Stop receiving data updates from the subscription subscription.unsubscribe(); export const getTodo = `query GetTodo($id: ID!) { getTodo(id: $id) { id clientId name description city } }
  • 16.
    API(AppSync) 추가하기 Subscription 구현시 주의 import App from './App'; import {AppRegistry} from 'react-native'; import {name as appName} from './app.json'; AppRegistry.registerComponent(appName, () => App); global.Buffer = global.Buffer || require('buffer').Buffer GitHub Issue https://github.com/aws-amplify/amplify-js/issues/4667
  • 17.
  • 18.
    Auth: 회원관리(Cognito) 추가하기 AmazonCognito - 회원 통합관리 서비스 - 소셜 로그인 가능 (Facebook, Google, Apple, SAML, OpenID Connect) - Amplify Framework에서 React, React-Native, Angular, Ionic 전용 회원 관리 컴포넌트 지원
  • 19.
    Auth: 회원관리(Cognito) 추가하기 App.js $amplify add auth CLI import { withAuthenticator } from 'aws-amplify-react-native'; const App = props => { ... } export default withAuthenticator(App, { includeGreetings: true });
  • 20.
  • 21.
    Auth: 회원관리(Cognito) 추가하기 HOC를감싸는 게 싫다면… import { Auth } from 'aws-amplify'; const signUpRes = await Auth.signUp({ username: name, password: pw, attributes: { nickname: nickname, phone_number: `+82${tel}`, email: email, 'custom:team': team,}, }) const confirmSignUpRes = await Auth.confirmSignUp(name, confirmCode, { forceAliasCreation: true, }) const user = await Auth.signIn(username, userPw) const sessionObj = await Auth.currentSession() const signOuttedObj = await Auth.signOut()
  • 22.
  • 23.
    Storage: 저장소(S3) 추가하기 AmazonS3 - 내구성 99.9999999999%의 저장소 - 정적 페이지 호스팅 가능
  • 24.
    Storage: 저장소(S3) 추가하기 $amplify add storage ? Please select from one of the below mentioned services: Content (Images, audio, video, etc.) ? Please provide a friendly name for your resource that will be used to label this category in the project: awskrugGallery ? Please provide bucket name: awskrug-gallery ? Who should have access: Auth users only ? What kind of access do you want for Authenticated users? (Press <space> to select, <a> to toggle all, <i> to invert selection)create/update, read, delete ? Do you want to add a Lambda Trigger for your S3 Bucket? No Successfully added resource awskrugGallery locally Bucket name(Unique) Resource name
  • 25.
    Storage: 저장소(S3) 추가하기 import{ Storage } from 'aws-amplify’; const fileData = await Storage.get('test.txt') const result = await Storage.remove('test.txt') const fileList = await Storage.list('photos/') const uploadToStorage = async pathToImageFile => { try { const response = await fetch(pathToImageFile) const blob = await response.blob() Storage.put('yourKeyHere.jpeg', blob, { contentType: 'image/jpeg’, progressCallback(progress) { console.log(`${progress.loaded}/${progress.total}`); }, }) } catch (err) { console.log(err) } }
  • 26.
    Storage: 저장소(S3) 추가하기 저장소권한 Public - 모든 유저에게 모든 권한 부여되어 있음 - public/ 경로에 보관 Protected - 모든 유저에게 읽기전용 - 생성자에게만 모든 권한 부여 - protected/{user_identity_id}/ 경로에 보관 Private - 모든 유저 볼 수 없음 - 개별 사용자만 액세스 가능 - private/{user_identity_id}/ 경로에 보관 // Public level: const publicResult = await Storage.put('test.txt', 'Hello’) .catch(err => console.log(err)); // Protected level: const protectedResult = await Storage.put( 'test.txt’, 'Protected Content', { level: 'protected’, contentType: 'text/plain’, }) .catch(err => console.log(err)); // Private level: const privateResult = await Storage.put( 'test.txt’, 'Private Content', { level: 'private’, contentType: 'text/plain’, }).catch(err => console.log(err));
  • 27.
  • 28.
    Mock & Test:로컬 디버깅 하기 $ amplify mock ($ amplify mock api, amplify mock storage) Mock Storage endpoint is running at http://localhost:20005 GraphQL schema compiled successfully. Edit your schema at /.../.graphql or place .graphql files in a directory at /.../schema Creating table PostTable locally Creating table NoteTable locally Running GraphQL codegen ✔ Generated GraphQL operations successfully and saved at src/graphql ✔ Code generated successfully and saved in file src/API.ts AppSync Mock endpoint is running at http://{my network ip address}:20002
  • 29.
    Mock & Test:로컬 디버깅 하기 aws-exports.js aws-exports.js (mocking mode) const awsmobile = { ... "aws_appsync_graphqlEndpoint": "https://cd767mzgajba3j3zurptndxhom.appsync-api.ap-northeast-2.amazonaws.com/graphql",... }; const awsmobile = { ... "aws_appsync_graphqlEndpoint": "http://192.168.123.164:20002/graphql", "aws_appsync_apiKey": "da2-fakeApiId123456", ”aws_appsync_dangerously_connect_to_http_endpoint_for_testing": true, "aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing": true }; $ amplify mock
  • 30.
    Mock & Test:로컬 디버깅 하기
  • 31.
    Analytics: 분석 서비스(Pinpoint)추가하기 Amazon Pinpoint - 클라이언트로부터 이벤트 기록 - 세션 데이터 자동 기록 - 인증 데이터(로그인/로그아웃/인증실패) 자동 기록 - Email, SMS, Voice, Push Notification
  • 32.
    Analytics: 분석 서비스(Pinpoint)추가하기 $ amplify add analytics CLI import { Analytics } from 'aws-amplify'; Analytics.record({ name: ‘Test Event 1’, // Attribute values must be strings attributes: { username: 'geoseong' } }); js
  • 33.
  • 34.
    Analytics: 분석 서비스(Pinpoint)추가하기 $ amplify push ($ amplify push analytics)
  • 35.
    • Multi Platformon-device persistent storage engine • AWS 연결없이 오프라인 용도로만으로 사용 가능 • GraphQL을 이용한 모바일/웹 앱과 클라우드 사이의 자동 동기화 New Amplify Feature: Amplify DataStore
  • 36.
    New Amplify Feature:Amplify DataStore offline
  • 37.
    New Amplify Feature:Amplify DataStore DataStore Storage Adapter - Mobile - SQLite - Web - IndexedDB
  • 38.
    New Amplify Feature:Amplify DataStore $ npx amplify-app@latest "scripts": { … "amplify-modelgen": "node amplify/scripts/amplify-modelgen.js", "amplify-push": "node amplify/scripts/amplify-push.js" }, package.json
  • 39.
    New Amplify Feature:Amplify DataStore amplify/backend/api/{프로젝트명}/schema.graphql enum PostStatus { ACTIVE INACTIVE } type Post @model { id: ID! title: String! rating: Int! status: PostStatus! } $ npm run amplify-modelgen
  • 40.
    New Amplify Feature:Amplify DataStore $ npm i @aws-amplify/core @aws-amplify/datastore CLI
  • 41.
    New Amplify Feature:Amplify DataStore import { DataStore, Predicates } from '@aws-amplify/datastore'; import { Todo } from '../models'; // Load todos from DataStore let dataStoreItems = await DataStore.query(Todo); // Create todo in DataStore const newTodo = await DataStore.save( new Todo({ task: task.task }) ); // Update DataStore const original = await DataStore.query(Todo, todoId); await DataStore.save( Todo.copyOf(original, updated => { updated.task = todoText; }) ); // Remove from DataStore const todelete = await DataStore.query(Todo, deleteTodo.id); DataStore.delete(todelete); // Subscription: do not use await DataStore.observe(Todo).subscribe(task => { if (task.opType === 'INSERT') { // do sth... } });
  • 42.
    New Amplify Feature:Amplify DataStore Query with Predicates • Strings: eq | ne | le | lt | ge | gt | contains | notContains | beginsWith | between • Numbers: eq | ne | le | lt | ge | gt | between • Lists: contains | notContains // AND statement: multiple condition const posts = await DataStore.query(Post, c => c.rating("gt", 4).status("eq",PostStatus.ACTIVE)); // OR statement const posts = await DataStore.query(Post, c => c.or( c => c.rating("gt", 4).status("eq", PostStatus.ACTIVE) ));
  • 43.
    New Amplify Feature:Amplify DataStore Sync with Cloud import Amplify from 'aws-amplify'; import config from './aws-exports’; Amplify.configure(config); App.js $ amplify init CLI
  • 44.
    New Amplify Feature:Amplify DataStore $ amplify push Sync with Cloud
  • 45.
    Amplify React-Native ProjectFinished! $ amplify console $ amplify console api
  • 46.
    그 외 가능한기능들 • 기능별 개별 Framework설치 가능 @aws-amplify/storage, @aws-amplify/api, @aws-amplify/auth, … • Cognito, S3, DynamoDB Lambda trigger • Create Lambda function • Multiple Serverless Environments • Utilities • Service Worker • LRU cache • I18n • Hub Hub.dispatch(‘channel’, obj); Hub.listen(‘channel’, () => {}); Hub.remove(‘channel’, () => {}); • Logger
  • 47.
  • 48.
    Amplify 사용 후기 •혼자 백엔드 & 프론트엔드 개발을 빠르게 할 때 매우 유용 • 그러나 아직은 소규모의 앱에서만 사용하는 것이 좋을 듯 • Amplify의 발전 가능성이 매우 높다. 오픈소스니까. • Thanks to Nader Dabit (@dabit3) • https://github.com/dabit3/awesome-aws-amplify
  • 49.
    Reference • Building ReactNative Apps with AWS Amplify • https://aws-amplify.github.io/docs/js/tutorials/building-react-native-apps/ • Building Serverless Web Applications with React & AWS Amplify • Author: Nader Dabit (twitter @dabit3) • https://egghead.io/courses/building-serverless-web-applications-with- react-aws-amplify
  • 50.
  • 51.
  • 52.