Search code examples
amazon-web-servicesaws-appsyncvtlapache-velocity

Create JSON Object with Velocity Template Language


I am working with the Apache Velocity Template Language (VTL) in AWS AppSync. In my request template I query an undefined amount of items with different elements. What I want to do in the response template is to transform the result into a JSON Object which I need later on for my BatchDeleteItem operation. This is how I solved it currently:

#set($deleteObject='{"Id" : { "S": "nodelete" },"Sk" : { "S": "nodelete" }}')
#set($replaceDeleteObject ="")
#set($separator="")

#foreach( $item in $ctx.result.items )
  #set($replaceDeleteObject = $replaceDeleteObject + $separator + '{"Id" : { "S": "' + $item.Id + '" },"Sk" : { "S": "' + $item.Sk + '" }}')
  #set($separator = ",")
  #set($deleteObject = $replaceDeleteObject)
#end

$util.qr($ctx.stash.put("deleteObject", $deleteObject))

Later on I can access my deleteObject and it works properly.

My question however is, if it is possible to directly create some kind of JSON Object in vtl in which I can append my values instead of creating this string in the form of a JSON Object?


Solution

  • You can follow this example from the AppSync Batch docs:

    #set($ids = [])
    #foreach($id in ${ctx.args.ids})
        #set($map = {})
        $util.qr($map.put("id", $util.dynamodb.toString($id)))
        $util.qr($ids.add($map))
    #end
    
    {
        "version" : "2018-05-29",
        "operation" : "BatchGetItem",
        "tables" : {
            "Posts": {
                "keys": $util.toJson($ids),
                "consistentRead": true
            }
        }
    }
    

    So for your case it should look like this:

    #set ($batchDeleteArray = [])
    #foreach( $item in $ctx.result.items )
      #set ($entry = {
        "Id": $util.dynamodb.toString($item.Id),
        "Sk": $util.dynamodb.toString($item.Sk)
      })
    
      $util.qr($batchDeleteArray.add($entry))
    #end
    
    {
        "version" : "2018-05-29",
        "operation" : "BatchDeleteItem",
        "tables" : {
            "TableName": {
              "keys": $util.toJson($batchDeleteArray)
            }
        }
    }