Dudedolf
Dudedolf

Reputation: 625

AWS AppSync Resolver Mapping Template Dynamic Key for DynamoDB

I am trying to create a dynamic key for a DynamoDB 'putItem' call. The current (non-dynamic) Resolver Mapping Template I have is

{
  "version" : "2017-02-28",
  "operation" : "PutItem",
  "key" : {
    "userId1" : { "S" : "${context.identity.sub}" },
    "userId2" : { "S" : "${context.stash.userId2}" },
  },
  "attributeValues" : {
   ...
  }
}

I am trying to make the key portion dynamic, one of the attempts I had, which does not work is:

{
  "version" : "2017-02-28",
  "operation" : "PutItem",
  #set($key={})
  #set($keyValue1={})
  #set($keyValue2={})
  $keyValue1.put("S", ${context.identity.sub})
  $keyValue2.put("S", ${context.stash.userId2})
  $util.qr($key.put("userId1", $keyValue1))
  $util.qr($key.put("userId2", $keyValue2))

  "key" : $util.toJson($key),
  "attributeValues" : {
    ...
  }
}

I cannot see much in the documentation for this type of thing. Any pointers would be appreciated.

Thank you

Upvotes: 2

Views: 1187

Answers (1)

Dudedolf
Dudedolf

Reputation: 625

I found a solution that I would like to share.

    "version" : "2017-02-28",
    "operation" : "PutItem",

    #set($key={})

    #set($key.userId1= $util.dynamodb.toString("${context.identity.sub}"))

    #if(!$ctx.prev.result.items.isEmpty()) ## My condition is based on result from previous template
      #set($key.userId2 = $util.dynamodb.toString("${ctx.prev.result.items[0].userId}"))
    #else
      #set($key.userId2 = $util.dynamodb.toString("${context.stash.anotherValue}"))
    #end

    "key" : $util.toJson($key), ## convert map/object to JSON and set the 'key' for use in the DynamoDB request

Hope this helps somebody in the future :)

Upvotes: 1

Related Questions