Sau khi AWS AppSync nhận biết được bảng DynamoDB, chúng ta có thể truy vấn hoặc thay đổi nó bằng cách xác định các Resolver. Trong bước này chúng ta sẽ tạo resolver là addPost thuộc kiểu Mutation, cho phép chúng ta tạo bài đăng trong bảng AppSyncTutorial-Post.
{
"version" : "2017-02-28",
"operation" : "PutItem",
"key" : {
"id" : $util.dynamodb.toDynamoDBJson($context.arguments.id)
},
"attributeValues" : {
"author" : $util.dynamodb.toDynamoDBJson($context.arguments.author),
"title" : $util.dynamodb.toDynamoDBJson($context.arguments.title),
"content" : $util.dynamodb.toDynamoDBJson($context.arguments.content),
"url" : $util.dynamodb.toDynamoDBJson($context.arguments.url),
"ups" : { "N" : 1 },
"downs" : { "N" : 0 },
"version" : { "N" : 1 }
}
}
Một Type được chỉ định trên tất cả các khoá và giá trị của thuộc tính. Ví dụ bạn đặt thuộc tính author thành { “S” : “${context.arguments.author}” }. Trong đó “S” là định nghĩa kiểu giá trị của thuộc tính author là một String, và giá trị được lấy từ đối số author mà người dùng truyền vào.
$utils.toJson($context.result)
Vì shape của dữ liệu trong bảng AppSyncTutorial-Post khớp hoàn toàn với shape của Post trong GraphQL, nên mẫu ánh xạ phần hồi chỉ chuyển thẳng kết quả từ bảng qua GraphQL.
mutation addPost {
addPost(
id: 123
author: "AUTHORNAME"
title: "Our first post!"
content: "This is our first post."
url: "https://aws.amazon.com/appsync/"
) {
id
author
title
content
url
ups
downs
version
}
}
{
"data": {
"addPost": {
"id": "123",
"author": "AUTHORNAME",
"title": "Our first post!",
"content": "This is our first post.",
"url": "https://aws.amazon.com/appsync/",
"ups": 1,
"downs": 0,
"version": 1
}
}
}