amazon-web-servicesamazon-dynamodbaws-api-gatewayvelocity

How can I modify a DynamoDB query using an API Gateway mapping template?


I am using an APIGW to proxy Dynamo requests. The aim is to intercept queries and add on some fixed filtering expressions. I am using a mapping template to do this but getting stuck with the template not allowing object keys that begin with ':' which I need for dynamo to set the attribute values

So for example this request

{
    "ExpressionAttributeValues": {
        ":pk": {
            "S": "pk"
        }
    },
    "KeyConditionExpression": "pk = :pk",
    "TableName": "mytable"
}

Should be transformed to this

{
    "ExpressionAttributeValues": {
        ":pk": {
            "S": "pk"
        },
        ":myproperty": {
            "S": "example"
        }
    },
    "FilterExpression": "contains(myproperty, :myproperty)",
    "KeyConditionExpression": "pk = :pk",
    "TableName": "mytable"
}

This is my current mapping template

## This section works to append to the Filter Expression
#set($filter = $input.path('$').FilterExpression)
#if($filter == "") #set($filter = "contains(myproperty, :myproperty)") #{else} #set($filter = $filter + " AND contains(myproperty, :myproperty)") #end
#set($input.path('$').FilterExpression = $filter)

## This section is handles the attribute values
#set($vals = $input.path('$').ExpressionAttributeValues)
#if($vals == "") #set($vals = {}) #end

## Offending line - it won't met me set this property with the leading colon
#set(${vals.:myproperty} = {'S': 'example'})
#set($input.path('$').ExpressionAttributeValues = $vals)

$input.json("$")

Is there a way I can get around this to add onto the existing ExpressionAttributeValues object in the request?


Solution

  • Solved! This did the trick $!{vals.put(":myproperty", {'S': 'example'})}

    Stumbled upon these docs which helped me understand the VTL stuff better https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-programming-guide.html