1
votes

I am trying to write a resolver for AppSync that derives the value for a Boolean field based on the existence of a record in DynamoDB.

I currently have the following request mapping template:

{
    "version": "2017-02-28",
    "operation": "GetItem",
    "key": {
        "field1": $util.dynamodb.toDynamoDBJson($ctx.args.field1),
        "field2": $util.dynamodb.toDynamoDBJson($ctx.args.field2)
    }
}

And the following response mapping template:

#if($util.isNull($ctx.result))
    #set($exists = false)
#else
    #set($exists = true)
#end

$util.toJson({
    "field1": $ctx.args.field1,
    "field2": $ctx.args.field2,
    "exists": $exists
})

This works correctly if the record exists but if it does not then AppSync simply returns "null" for the entire API call and does not seem to evaluate the response mapping template at all. Is there any way I can instruct it not to do this?

Another option would be to perform a query and look at the length of the response but I have no idea how to check length in these templates.

1

1 Answers

5
votes

This is an expected behavior for the 2017 version of the Request template. If you would like the $ctx.result to be evaluated, switch to the 2018 version as below:

{
  "version": "2018-05-29",
  "operation": "GetItem",
  "key": {
    "id": $util.dynamodb.toDynamoDBJson($ctx.args.id),
  },
}

Refer to this change log for additional details.