使用BatchGetItem

时间:2019-05-17 12:18:36

标签: amazon-dynamodb aws-appsync aws-serverless

我正在使用具有文件夹结构的微服务。

Microservice => 
  resolvers -> 
    Media/Image/get-images/request.vtl
    Media/Image/get-images/response.vtl
  templates -> services.yaml

请求映射:

#set($imageIds=$ctx.source.imageIds)
#set($keys=[])
#foreach($imageId in $imageIds)
    #set($key={})
    $util.qr($key.put("id", $util.dynamodb.toString($imageId)))
    $util.qr($keys.add($key))
#end
{
  "version": "2018-05-29",
  "operation": "BatchGetItem",
  "tables" : {
        "MediaImages": {
            "keys": $util.toJson($keys)
        }
  }
}

响应映射:

#set($result=$ctx.result.data.MediaImages)
$util.toJson($result)

Service.yaml

Resources:
  MediaImagesTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: MediaImages
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
        - AttributeName: userId
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5

      GlobalSecondaryIndexes:
        - IndexName: UserImages
          KeySchema:
            - AttributeName: userId
              KeyType: HASH
            - AttributeName: id
              KeyType: RANGE
          Projection:
            ProjectionType: ALL
          ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 2

  ImageDetailsDataSource:
    Type: AWS::AppSync::DataSource
    Properties:
      Name: ImageDetailsDataSource
      Type: AMAZON_DYNAMODB
      ServiceRoleArn:
        Fn::ImportValue: !Sub "DynamoDB-Role"
      ApiId:
        Fn::ImportValue: !Sub "API-Id"
      DynamoDBConfig:
        TableName: !Ref MediaImagesTable
        AwsRegion: !Ref AWS::Region
        UseCallerCredentials: false

  GetImagesPipelineFunction:
    Type: AWS::AppSync::FunctionConfiguration
    Properties:
      ApiId:
        Fn::ImportValue: !Sub "API-Id"
      Name: GetImagesPipelineFunction
      FunctionVersion: "2018-05-29"
      Description: Function to get the images from dynamo db
      DataSourceName: !GetAtt ImageDetailsDataSource.Name
      RequestMappingTemplateS3Location: ../resolvers/get-images/request.vtl
      ResponseMappingTemplateS3Location: ../resolvers/get-images/response.vtl

我尝试过

#set($tableName=$util.dynamodb.getDataSourceTableName())
#set($imageIds=$ctx.source.imageIds)
#set($keys=[])
#foreach($imageId in $imageIds)
    #set($key={})
    $util.qr($key.put("id", $util.dynamodb.toString($imageId)))
    $util.qr($keys.add($key))
#end
{
  "version": "2018-05-29",
  "operation": "BatchGetItem",
  "tables" : {
        "$tableName": {
            "keys": $util.toJson($keys)
        }
  }
}

"error": {
  "message": "1 validation error detected: Value '{$tableName= . 
  [com.amazonaws.dynamodb.v20120810.WriteRequest@1528275d]}' at 
  'requestItems' failed to satisfy constraint: Map keys must satisfy 
  constraint: [Member must have length less than or equal to 255, Member 
  must have length greater than or equal to 3, Member must satisfy regular 
  expression pattern: [a-zA-Z0-9_.-]+] (Service: AmazonDynamoDBv2; Status 
  Code: 400; Error Code: ValidationException; Request ID: 
  464H3LIEPOSA2S8OI34RJ31QLNVV4KQNSO5AEMVJF66Q9ASUAAJG)",
  "type": "DynamoDB:AmazonDynamoDBException"
},

在我的AppSync请求映射模板中。我正在做BatchGetItem并对表名进行硬编码。我想将表名称动态地添加到我的请求和响应映射模板中。我尝试了“映射模板实用程序参考$util.dynamodb.getDataSourceTableName($dataSourceName)”,但没有用。

1 个答案:

答案 0 :(得分:1)

我这样做:

RequestMappingTemplate: !Sub
  - |
    #set($keys=[])
    #foreach($imageId in $imageIds)
        #set($key={})
        $util.qr($key.put("id", $util.dynamodb.toString($imageId)))
        $util.qr($keys.add($key))
    #end
    {
      "version": "2018-05-29",
      "operation": "BatchGetItem",
      "tables" : {
            "${TableName}": {
                "keys": $util.toJson($keys)
            }
      }
    }
  - { TableName: INSERT YOUR TABLE NAME OR SOME REF HERE }
ResponseMappingTemplate: !Sub
  - |
    #set($result=$ctx.result.data["${TableName}"])
    $util.toJson($result)
  - { TableName: INSERT YOUR TABLE NAME OR SOME REF HERE }

我使用!FindInMap [Environments, !Ref Environment, ProjectsTableName],但您也可以使用!Ref YourDynamoDBTable替换INSERT YOUR TABLE NAME OR SOME REF HERE