0

I am trying to enhance data I am pushing through an APIGateway Websocket with information about the connection and user.

The integration is pushing the data into Kinesis for context. I would like to do the following where I can merge the JSON objects together at the top level.

#set($payload = $input.json('$'))
#set($data = "{""apiId"": ""$context.apiId"", ""region"": ""${AWS::Region}"", stage"": ""$context.stage"", ""connectionId"": ""$context.connectionId""}")
{
    "Data": "$util.base64Encode({merge data and payload - prefer $data})",
    "PartitionKey": "$context.connectionId",
    "StreamName": "${EventStream}"
}

The documentation on the available language is awful, there is no reference to an underlying language to look this up. AWS does not link to this from API-gateway but can be found api-gateway-mapping-template, which suggests there is a possible way of doing this with the use of foreach statements:

#set($allParams = $input.params())
{
  "params" : {
    #foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
    "$type" : {
      #foreach($paramName in $params.keySet())
      "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
      #if($foreach.hasNext),#end
      #end
    }
    #if($foreach.hasNext),#end
    #end
  }
}

However, my attempt fails serialisation and I can't find any context about the issue in cloudwatch.

#set($payload = $input.json('$'))
#set($data = "{""apiId"": ""$context.apiId"", ""region"": ""${AWS::Region}"", stage"": ""$context.stage"", ""connectionId"": ""$context.connectionId""}")
{
    "Data": "$util.base64Encode(
        {
            #foreach($key in $data.keySet())
            #set($value $data.get($key))
            ""$key"": ""$value"",
            #end
            #foreach($key in $data.keySet())
            #set($value $data.get($key))
            ""$key"": ""$value""
            #if($foreach.hasNext),#end
            #end
        }
    )",
    "PartitionKey": "$context.connectionId",
    "StreamName": "${EventStream}"
}

the template section does link to websocket-api-selection-expressions but this seems more confusing that helpful.

Is this possible in the template? Or should I simple nest the payload into my data object?

hi im Bacon
  • 374
  • 1
  • 12

0 Answers0