1
votes

I'm making a service that requests data through AWS API Gateway directly from DynamoDB.

I want to use mapping templates on Integration Response, to remove DynamoDB item types and give a user expected simple JSON.

From DynamoDB I get this

{
  "Count": 10,
  "Items": [
    {
      "acc_secret": {
        "S": "12345"
      },
      "acc_apikey": {
        "S": "abcde"
      },
      "login": {
        "S": "user"
      }
    }
  ]
}

And I want to get items format like this

[
  {
    "acc_secret": "12345",
    "acc_apikey": "abcde",
    "login": "user"
  },
  {
    "acc_secret": "12345",
    "acc_apikey": "abcde",
    "login": "user"
  }
]

I have a code to change the format, but for explicit values.

#set($inputRoot = $input.path('$'))
[
  #foreach($elem in $inputRoot.Items) {
    "param1": "$elem.param1.S",
    "param2": "$elem.param2.S",
    "param3": "$elem.param3.S"
    
  }#if ($foreach.hasNext),#end
  #end
]

but in my case I can have different types of keys, not only string, and a lot more items, I can't declare them all in a mapping template at once.

Help me please to dynamically transform item keys in cycle. Thanks.

1

1 Answers

1
votes

Instead of adding to the general complexity of you application by adding a mapping, you could instead use the DynamoDB Document Client:

const dynamoDB = new AWS.DynamoDB.DocumentClient(options);
dynamoDB.query(queryParams, function(err, data) {
   /*
     data = {
        Items: [
          {
            "acc_secret": "12345",
            "acc_apikey": "abcde",
            "login": "user"
          }
        ]
      }
    */
});

The DynamoDB Document Client:

  1. Returns the data in the format you want (without the attribute type).
  2. Converts data to the correct type (e.g. for numeric values, it will return them as numbers, unlike the standard API which would return them as string values).