Aws appsync 어플 패키지명 연결 방법

본 강좌를 시작하기 전에 먼저 part 1 학습을 통해 Amplify를 하나의 프레임워크로 설정하는 방법과 사용자 정의 UI를 사용하여 전자 우편 인증을 하는 방법에 대해 토론했습니다.

GraphQL API 만들기

API 생성 및 데이터베이스 연결을 시작하려면 터미널 창에서 다음 명령을 실행합니다.

amplify add api


이 CLI는 두 가지 작업을 자동으로 수행합니다.우선, 데이터 원본, 조회, 돌연변이, 구독 기본 모델 구조를 포함하는 GraphQL API를 만듭니다.또한 이러한 작업을 실행하는 데 필요한 클라이언트 코드와 프로필을 다운로드해 달라는 요청을 보냅니다.위의 명령은 작성할 API 유형 중에서 선택하라는 메시지를 표시합니다.프로필 API 이름을 입력합니다.다음 예에서 우리는 설정 파일 이름을 기본값으로 보존합니다.

다음은 AWS AppSync API를 검증하는 두 가지 옵션입니다.실시간 응용 프로그램에서 서로 다른 사용자가 데이터베이스에 접근하여 요청합니다.Amazon Cognito 사용자 풀 옵션을 선택합니다.이것은 더욱 실용적인 방법이다.Amazon Cognito 사용자 풀을 인증 모듈로 구성했기 때문에 여기서 구성할 필요가 없습니다.

다음 두 문제의 경우 **GraphQL API에 대한 고급 설정 ** 및 **주석이 있는 GraphQL 모드가 있는지 **답은 N 또는 아니요입니다. Amplify는 나중에 변경할 수 있는 미리 정의된 모드를 제공합니다.
구조 템플릿을 선택하라는 메시지가 나타나면 필드가 있는 단일 객체를 선택합니다.

계속하기 전에 이 프로세스가 만든 GraphQL 모드를 편집합니다.React 로컬 프로젝트로 이동하여 루트 디렉터리에서 파일amplify/backed/api/[api\u NAME]/schema를 엽니다.그래픽 QL.
AppSync에서 만든 기본 모델은 다음과 같습니다.

type Todo @model { id: ID! name: String! description: String }

현재 CLI에서 프로세스를 완료할 때 다음과 같은 경고 메시지가 표시되어야 합니다.

The following types do not have '@auth' enabled. Consider using @auth with @model - Todo

인증 모듈을 사용했기 때문에 추가할 수 있습니다[email protected]모드에서graphql 파일.기본적으로 소유자 권한 부여를 사용하면 모든 로그인 사용자가 기록을 만들 수 있습니다.

type Todo @model @auth(rules: [{ allow: owner }]) { id: ID! name: String! description: String }

GraphQL 모델과 그 유형에 익숙하지 않은 경우 간략하게 설명합니다.
GraphQL 모드의 유형은 데이터베이스에 저장된 데이터입니다.각 유형에는 서로 다른 필드 세트가 있을 수 있습니다.유형을 JavaScript 배경에서 객체로 봅니다.예를 들어 위의 Todomodel 모드에서 유형은 세 개의 필드가 있는데 그것이 바로 id,name,description이다.게다가[email protected]명령은 Amazon DynamoDB에 유형을 저장하는 데 사용됩니다.이것은 아마존이 우리의 응용 프로그램 데이터를 저장할 때 사용하는 데이터베이스다.
느낌표!데이터를 저장할 때 이 필드가 필요하고 값이 있어야 한다는 것을 나타낸다.위의 모드에는 두 개의 필수 필드가 있습니다. Todo 형식의 id와name입니다.
이 파일을 저장합니다. 저희가 방금 한 모든 변경 사항을 로컬에 저장합니다.

AWS 클라우드에 API 게시

명령을 실행할 때, 우리가 사용하거나, 수정하거나, 사용한 자원에 대한 정보를 포함하는 표를 되돌려줍니다.분류 부분에서 이 자원들의 이름을 설명합니다.
위 표의 리소스 이름은 이전 섹션에서 선택한 API 이름입니다.


Amplify CLI 인터페이스에서 모드를 확인한 다음 최종 변경 사항을 클라우드에 게시하기 전에 컴파일하여 오류를 찾습니다.
다음 단계에서는 새로 만든 GraphQL API에 대한 코드를 생성할지 여부를 선택하라는 메시지가 표시됩니다.Y 키를 누릅니다. 그런 다음 코드 생성 언어로 JavaScript를 선택합니다.

Y키를 눌러 다음 질문으로 넘어가면 GraphQL과 관련된 모든 작업을 업데이트해야 합니다.또한 최대 문장 깊이를 기본값 2로 설정합니다.AWS 클라우드에 있는 리소스를 업데이트하는 데 시간이 좀 걸리고 완료되면 성공 메시지가 표시됩니다.

React Native 응용 프로그램에 입력 필드 추가

사용자 입력을 포착하기 위해 React hookuseState를 사용하여 두 개의 상태 변수를 사용합니다.첫 번째 상태 변수는 todo 항목의 이름 필드와 todos라는 그룹에 사용됩니다.이 배열은 GraphQL API에서 모든 todo 항목을 가져와 UI에 표시하는 데 사용됩니다.

const [name, setName] = useState(''); const [todos, setTodos] = useState([]);

다음은 React Native에서 Text Inputand와 Touchable Opacityfrom을 가져와서 입력 필드를 만들고 Homecomponent 아래의 StyleSheetreference 대상에 정의된 사용자 정의 스타일의 단추를 누르십시오.이것은 집의 전체 코드다.js:

import React, { useState } from 'react'; import { View, Text, TextInput, TouchableOpacity, StyleSheet, Button, ScrollView, Dimensions } from 'react-native'; import { Auth } from 'aws-amplify'; const { width } = Dimensions.get('window'); export default function Home({ updateAuthState }) { const [name, setName] = useState(''); const [todos, setTodos] = useState([]); async function signOut() { try { await Auth.signOut(); updateAuthState('loggedOut'); } catch (error) { console.log('Error signing out: ', error); } } const addTodo = () => {}; return ( <View style={styles.container}> <Button title="Sign Out" color="tomato" onPress={signOut} /> <ScrollView> <TextInput style={styles.input} value={name} onChangeText={text => setName(text)} placeholder="Add a Todo" /> <TouchableOpacity onPress={addTodo} style={styles.buttonContainer}> <Text style={styles.buttonText}>Add</Text> </TouchableOpacity> </ScrollView> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', marginTop: 20 }, input: { height: 50, borderBottomWidth: 2, borderBottomColor: 'tomato', marginVertical: 10, width: width * 0.8, fontSize: 16 }, buttonContainer: { backgroundColor: 'tomato', marginVertical: 10, padding: 10, borderRadius: 5, alignItems: 'center', width: width * 0.8 }, buttonText: { color: '#fff', fontSize: 24 } });

이 단계의 결과를 보기 위해 터미널 창에서 expostartcommand를 실행하고 있는지 확인하십시오.

GraphQL API를 사용하여 변이 추가

GraphQL의 돌연변이는 데이터 추가, 삭제 또는 수정 등의 작업에 관한 것입니다.현재, React 본체 응용 프로그램은 기본적이지만, 도구 체인으로서의 Amplify와 크로스플랫폼 프레임워크와의 통합을 익히는 데 목적을 두고 있습니다.
React 원본 응용 프로그램에 항목을 추가하고 검색하기 위해 GraphQL 백엔드와 통신하기 위해 업무 논리를 추가합니다.

/* eslint-disable */ // this is an auto generated file. This will be overwritten export const createTodo = /* GraphQL */ ` mutation CreateTodo( $input: CreateTodoInput! $condition: ModelTodoConditionInput ) { createTodo(input: $input, condition: $condition) { id name description createdAt updatedAt owner } } `; export const updateTodo = /* GraphQL */ ` mutation UpdateTodo( $input: UpdateTodoInput! $condition: ModelTodoConditionInput ) { updateTodo(input: $input, condition: $condition) { id name description createdAt updatedAt owner } } `; export const deleteTodo = /* GraphQL */ ` mutation DeleteTodo( $input: DeleteTodoInput! $condition: ModelTodoConditionInput ) { deleteTodo(input: $input, condition: $condition) { id name description createdAt updatedAt owner } } `;

이것은 확대를 통해 이루어진 것이다. 상술한 어떤 돌연변이를 사용하려면, 우리는 이 방법을 구성 요소 파일에 직접 가져올 수 있다.집에 있어요.js 파일,awsamplify 패키지에서 API와graphqlOperation을 가져옵니다.API는 AWS 리소스의 범주이며 가져온 두 번째 함수는 변이나 질의를 실행하는 방법입니다.또한 graphql/mutation에서 돌연변이createTodo를 가져옵니다.js 파일.

// ... import { Auth, API, graphqlOperation } from 'aws-amplify'; import { createTodo } from '../graphql/mutations';

이전 절에서 정의한addTodocustom 처리 프로그램 방법에 논리를 추가합니다.이것은 변이에서 결과를 얻고 todosarray를 업데이트하는 비동기 함수입니다.이것은 이름을 입력으로 하는데, 그 중에서 이름은 항목의 텍스트입니다.

const addTodo = async () => { const input = { name }; const result = await API.graphql(graphqlOperation(createTodo, { input })); const newTodo = result.data.createTodo; const updatedTodo = [newTodo, ...todos]; setTodos(updatedTodo); setName(''); };

다음 절을 계속하기 전에 데이터를 추가해 보십시오.

AWS AppSync에서 데이터 가져오기 쿼리 실행

데이터베이스에서 데이터를 얻기 위해서 우리는 조회를 실행해야 한다.Amplify는 돌연변이와 유사하게 생성된 GraphQL 모드에 따라 초기 질의를 작성합니다.
모든 사용 가능한 조회는 src/graphql/querys에서 찾을 수 있습니다.js.

/* eslint-disable */ // this is an auto generated file. This will be overwritten export const getTodo = /* GraphQL */ ` query GetTodo($id: ID!) { getTodo(id: $id) { id name description createdAt updatedAt owner } } `; export const listTodos = /* GraphQL */ ` query ListTodos( $filter: ModelTodoFilterInput $limit: Int $nextToken: String ) { listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) { items { id name description createdAt updatedAt owner } nextToken } } `;

GraphQL API에서 모든 데이터를 가져와 장치 화면에 표시하기 위해 위 파일의 질의를 사용합니다.ListToDosside Home 가져오기js 파일:

import { listTodos } from '../graphql/queries';

데이터베이스에서 데이터를 얻기 위해 useEffect 연결을 사용합니다.React 라이브러리에서 가져오려면 다음과 같이 하십시오.

import React, { useState, useEffect } from 'react';

fetchtodos라는 다른 처리 프로그램 방법을 정의합니다. listTodos를 실행하여 데이터를 가져옵니다.이것은 비동기적인 방법이 될 것입니다. 따라서try/catchblock을 사용하여 데이터를 가져올 때의 초기 오류를 포착합니다.주 어셈블리에 다음 코드 세그먼트를 추가합니다.

useEffect(() => { fetchTodos(); }, []); async function fetchTodos() { try { const todoData = await API.graphql(graphqlOperation(listTodos)); const todos = todoData.data.listTodos.items; console.log(todos); setTodos(todos); } catch (err) { console.log('Error fetching data'); } }

데이터베이스에서 반환되는 데이터 배열은 다음과 같습니다.

return ( <View style={styles.container}> <Button title="Sign Out" color="tomato" onPress={signOut} /> <ScrollView> <TextInput style={styles.input} value={name} onChangeText={text => setName(text)} placeholder="Add a Todo" /> <TouchableOpacity onPress={addTodo} style={styles.buttonContainer}> <Text style={styles.buttonText}>Add</Text> </TouchableOpacity> {todos.map((todo, index) => ( <View key={index} style={styles.itemContainer}> <Text style={styles.itemName}>{todo.name}</Text> </View> ))} </ScrollView> </View> );

또한 해당 스타일을 업데이트합니다.

const styles = StyleSheet.create({ // ... itemContainer: { marginTop: 20, borderBottomWidth: 1, borderBottomColor: '#ddd', paddingVertical: 10, flexDirection: 'row', justifyContent: 'space-between' }, itemName: { fontSize: 18 } });

다음 결과는 다음과 같습니다.

데이터를 검색할 때 로드 표시기 추가

현재, 프로그램이 리셋되거나 사용자가 로그인할 때, 데이터를 불러오는 데 시간이 걸리기 때문에, 목록 항목을 보일 때 약간의 지연이 있습니다.React Native의 Activity Indicator를 사용하여 로드 표시기를 추가합니다.

// modify the following import statement import { View, Text, TextInput, TouchableOpacity, StyleSheet, Button, ScrollView, Dimensions, ActivityIndicator } from 'react-native';

검색이 실행될 때 마운트 표시기가 언제 표시되는지 알기 위해서, 홈 컴포트에loading이라는 새로운 상태 변수를 추가합니다. 초기 값은booleanfalse입니다.데이터를 추출할 때 처음에 이 값은true이고 API에서 데이터를 추출할 때만 다시 false로 설정됩니다.

export default function Home({ updateAuthState }) { // ... const [loading, setLoading] = useState(false); // modify the fetchTodos method async function fetchTodos() { try { setLoading(true); const todoData = await API.graphql(graphqlOperation(listTodos)); const todos = todoData.data.listTodos.items; console.log(todos); setTodos(todos); setLoading(false); } catch (err) { setLoading(false); console.log('Error fetching data'); } } // then modify the JSX contents return ( {/* rest remains same */} <ScrollView> {/* rest remains same */} {loading && ( <View style={styles.loadingContainer}> <ActivityIndicator size="large" color="tomato" /> </View> )} {todos.map((todo, index) => ( <View key={index} style={styles.itemContainer}> <Text style={styles.itemName}>{todo.name}</Text> </View> ))} </ScrollView> ) } // also modify the styles const styles = StyleSheet.create({ // ... loadingContainer: { marginVertical: 10 } });

다음은 출력입니다.

항목 삭제 변이 실행 \

todosarray에서 항목을 삭제하려면 변이deletetetodoneeds가 실행됩니다.사용하래요[email protected]/아이콘을 목록의 각 항목에 벡터합니다.집에 있어요.js 구성 요소 파일, 가져오기 아이콘과 변이부터 시작합니다.

// ... import { Feather as Icon } from '@expo/vector-icons'; import { createTodo, deleteTodo } from '../graphql/mutations';

그리고removetodo라는 처리 프로그램 방법을 정의합니다. 이 방법은 todo 그룹에서 todo 항목을 삭제하고 filtermethod를 사용하여 그룹을 업데이트합니다.이번 변이의 입력은 todo 항목의 id가 될 것입니다.

const removeTodo = async id => { try { const input = { id }; const result = await API.graphql( graphqlOperation(deleteTodo, { input }) ); const deletedTodoId = result.data.deleteTodo.id; const updatedTodo = todos.filter(todo => todo.id !== deletedTodoId); setTodos(updatedTodo); } catch (err) { console.log(err); } };

현재 작업 목록 항목을 표시할 단추를 추가합니다.

{ todos.map((todo, index) => { return ( <View key={index} style={styles.itemContainer}> <Text style={styles.itemName}>{todo.name}</Text> <TouchableOpacity onPress={() => removeTodo(todo.id)}> <Icon name="trash-2" size={18} color="tomato" /> </TouchableOpacity> </View> ); }); }

이것은 이 단계 후에 당신이 얻을 출력입니다.

총결산

이 강좌를 마치면 AWS AppSync 및 Amplify를 사용하여 GraphQL API를 만드는 것이 얼마나 간단한지 확인할 수 있습니다.
Instamobile 플랫폼에서 우리는 개발자가 자신의 모바일 응용 프로그램을 더욱 빨리 개발할 수 있도록 다양한 백엔드 지원, 예를 들어 AWS Amplify나 Firebase를 구축하고 있습니다.
최초 2020년 10월 5일 발표//www.instamobile.io.

Toplist

최신 우편물

태그