After AWS AppSync is aware of the DynamoDB table, we can link it to individual queries and mutations by defining Resolvers. In this part we will create addPost resolver of Mutation type, allowing us to create posts in the AppSyncTutorial-Post table.
{
"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 }
}
}
A Type is specified on all the keys and attribute values. For example, you set the author field to { “S” : “${context.arguments.author}” }. The S part indicates to AWS AppSync and DynamoDB that the value will be a string value, and the value is taken from the author argument passed by the user.
$utils.toJson($context.result)
Because the shape of the data in the AppSyncTutorial-Post table exactly matches the shape of the Post type in GraphQL, the response mapping template just passes the results straight through.
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
}
}
}