user27711371
user27711371

Reputation: 11

Removing attribute values from Dynamodb getItem response

I have create an direct connection from API gateway to DynamoDB using the AwsIntegration. It works but the problem is that I get all the attribute values

{
  "Item": {
    "properties": {
      "M": {
        "requireLogin": {
          "BOOL": false
        },

like M and BOOL. I want to have the direct values such as {"properties": {"requireLogin": false}} returned. The payload is pretty long and have different different types like S, L, etc. so the solution needs to be generic I have tried an bunch of thing using VTL in the responseTemplates, different flags but nothing seems to work. My CDK code looks like this:

    const dynamoIntegration = new AwsIntegration({
      service: 'dynamodb',
      action: 'GetItem',
      options: {
        credentialsRole: apiGatewayRole,
        integrationResponses: [
          {
            statusCode: '200',
          },
          ...errorResponses,
        ],
        requestTemplates: {
          'application/json': JSON.stringify({
            TableName: DELIVERY_TABLE,
            Key: {
              [partitionKey]: {
                S: "$input.params('pagePath')",
              },
            },
          }),
        },
      },
    });
    
    deliveryApi.root.addMethod('GET', dynamoIntegration, {
      apiKeyRequired: !isLocalStack,
      requestParameters: {
        'method.request.querystring.pagePath': true,
      },
      methodResponses: [
        {
          statusCode: '200',
          responseModels: {
            'application/json': deliveryApi.addModel('ResponseModel', {
              contentType: 'application/json',
              modelName: 'ResponseModel',
              schema: {},
            }),
          },
        },
      ],
    });

I have a solution where it goes through a lambda and does unmarshall but I would like to avoid this overhead :)

I'm expecting a response without any of the attribute values like this:

{"properties": {"requireLogin": false}}

Upvotes: 1

Views: 67

Answers (1)

Leeroy Hannigan
Leeroy Hannigan

Reputation: 19883

You have to use the integration response mapping and unmarshall manually. For example:

#set($inputRoot = $input.path('$'))
{
    "comments": [
        #foreach($elem in $inputRoot.Items) {
            "commentId": "$elem.commentId.S",
            "userName": "$elem.userName.S",
            "message": "$elem.message.S"
        }#if($foreach.hasNext),#end
    #end
    ]
}

https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-integration-settings-integration-response.html

Alternatively, unmarshall using the DynamoDB client on your client side.

Upvotes: 1

Related Questions