총 2달을 삽질하고 쓰는 정리글.. 좋아요 눌러주시면 감사드리겠습니다
이전 글에서는 Flutter앱에서 간단한 GraphQL 문을 보내서 통신하는 과정을 담았습니다.
이 GraphQL을 접해보시지 않은 분들은 굉장히 생소할 텐데요..
SQL문과는 상당히 다릅니다.
그치만 조금만 공부하면 직관적이라는 것을 금방 깨달으실 수 있습니다.
따라서 오늘은 콘솔에서 직접,
AppSync를 통한 DynamoDB 쿼리 구성 맛보기를 할 것입니다.
쿼리를 만들 줄 몰라도, 버튼클릭으로 쿼리를 만들 수 있습니다.
이걸 해보면서 플러터 코드를 그대로 사용하게 되니까, 잘 사용해보세요.
쿼리를 만들어주고, 이걸 복붙해서 플러터에서 사용하면 됩니다.
AppSync로 이동해줍니다.
직접 웹페이지 이동으로 이동하셔도 되고, 개발중인 프로젝트 터미널에
amplify console api
를 입력하신 뒤, GraphQL 을 선택하시면 AppSync로 이동하게 됩니다.
왼쪽 메뉴에서 Query를 선택하면 다음과 같은 화면이 나옵니다.
이전 시간에서 잠깐 봤듯이, 여기서 버튼클릭만으로도 쿼리를 구성할 수 있고, 구성한 쿼리를 마음껏 테스트할 수 있습니다.
예시로 하나의 쿼리를 작성해보겠습니다.
저는 생성을 할 거기 때문에, +를 눌러 Mutation을 추가해주고
Mutation을 설정하고 플레이 버튼을 눌러 실행까지 완료한 화면입니다.
createTodo mutation에서,
input은 description : Sample des, name : Sample name
으로 설정해주었고, 아래 createdAt 부터 updatedAt은 다 체크해주었는데요!
input은 말그대로 입력할 데이터이고, 그 아래에 있는 createdAt부터는 실행 결과로 받아올 데이터입니다.
그렇기 때문에 로그에 해당 값들이 출력됨을 알 수 있습니다.
이렇게 AppSync를 이용해서 이러한 데이터를 DynamoDB에 생성했습니다.
이제 저희가 생성한 데이터를 탐색해보겠습니다.
검색문은 Query를 사용하기에, Query로 변경해주고
getTodo는 id값을 기반으로 찾아야 되는 것이기에 패스하고,
저는 listTodos를 이용해서, name == 'Sample name' 인 데이터를 찾아보겠습니다. 저희가 방금 넣은 데이터죠.
그대로 실행해보면
로그를 주목해주세요.
필터를 이용해서 name == 'Sample name'인 데이터를 찾았고, 그 데이터의 description은 Sample des네요.
저희가 방금 넣은 데이터가 맞죠?
이렇게 AppSync를 이용해서 DynamoDB에 데이터를 넣고, 검색하는 과정까지 거쳐봤습니다!
자 이제, 방금 list를 얻어내는 과정을 Flutter 앱을 통해 구현해봅시다.
저희가 버튼으로 만든 쿼리 있죠? 그 쿼리를 활용하면 됩니다.
아래 함수를 정의합니다.
Future<String> GetTodosByName(String input_name) async {
try {
String graphQLDocument = '''query ListTodos {
listTodos(filter: {name: {eq: "$input_name"}}) {
items {
createdAt
description
id
name
updatedAt
}
}
}''';
var operation = Amplify.API.query(
request: GraphQLRequest<String>(
document: graphQLDocument,
));
var response = await operation.response;
var data = response.data;
print('Query result: ' + data);
} on ApiException catch (e) {
print('Query failed: $e');
}
return 'Success';
}
입력으로 받은 name 변수를, 필터 변수로 사용해서 쿼리를 날리는 방식입니다.
전부 끝났습니다. 이제 이 함수도 한번 테스트해봅시다.
전체 소스코드
import 'package:flutter/material.dart';
// 추가
import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:amplify_api/amplify_api.dart';
import 'amplifyconfiguration.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isConfigured = false;
@override
void initState() {
super.initState();
_configureAmplify();
}
void _configureAmplify() async {
// Add the following line to add API plugin to your app
Amplify.addPlugin(AmplifyAPI());
try {
await Amplify.configure(amplifyconfig);
setState(() {
isConfigured = true;
});
} on AmplifyAlreadyConfiguredException {
print("Tried to reconfigure Amplify; this can occur when your app restarts on Android.");
}
}
Widget build(BuildContext context) {
return MaterialApp(
title: 'title',
home: Scaffold(
body: Center(
child: isConfigured ? createWidget() : Text('Loading'),
),
)
);
}
}
class createWidget extends StatefulWidget {
const createWidget({Key? key}) : super(key: key);
@override
_createWidgetState createState() => _createWidgetState();
}
class _createWidgetState extends State<createWidget> {
Future<String> CreateTodo() async {
try {
String graphQLDocument =
'''mutation CreateTodo(\$name: String!, \$description: String) {
createTodo(input: {name: \$name, description: \$description}) {
id
name
description
}
}''';
var variables = {
"name": "my first todo",
"description": "todo description",
};
var request = GraphQLRequest<String>(document: graphQLDocument, variables: variables);
var operation = Amplify.API.mutate(request: request);
var response = await operation.response;
var data = response.data;
print('Mutation result: ' + data);
} on ApiException catch (e) {
print('Mutation failed: $e');
}
return 'SUCCESS';
}
Future<String> GetTodosByName(String input_name) async {
try {
String graphQLDocument = '''query ListTodos {
listTodos(filter: {name: {eq: "$input_name"}}) {
items {
createdAt
description
id
name
updatedAt
}
}
}''';
var operation = Amplify.API.query(
request: GraphQLRequest<String>(
document: graphQLDocument,
));
var response = await operation.response;
var data = response.data;
print('Query result: ' + data);
} on ApiException catch (e) {
print('Query failed: $e');
}
return 'Success';
}
@override
Widget build(BuildContext context) {
return FutureBuilder(builder: (context, snap) {
if(!snap.hasData) {
return Text('POSTING...');
} else {
return Text('FETCHED');
}
},
future: GetTodosByName("Sample name"),);
}
}
실행해보면 순식간에 앱 화면에 FETCHED가 출력될 것이고
콘솔에는 쿼리로 날린 결과 데이터가 출력됨을 확인할 수 있습니다.
오늘은 여기까지 하겠습니다!
참고하면 좋은 자료
https://techblog.geekyants.com/aws-amplify-for-flutter-part-5-graphql-api
AWS Amplify For Flutter Part 5: GraphQL API
In this fifth exploration of the series, we shall see how to integrate GraphQL in your project for further data exploration
techblog.geekyants.com
'[클라이언트] > [Flutter]' 카테고리의 다른 글
[Flutter] Amplify GraphQL 클라우드 기반 앱 만들기 [4] (0) | 2022.02.14 |
---|---|
Flutter와 Amplify GraphQL (0) | 2022.02.14 |
[Flutter] Amplify GraphQL 클라우드 기반 앱 만들기 [2] (0) | 2022.02.11 |
[Flutter] Amplify GraphQL 클라우드 기반 앱 만들기 [1] (0) | 2022.02.10 |
setState 원리 (0) | 2021.10.29 |