【问题标题】:How to allow Optional Key in API Gateway mapping template如何在 API Gateway 映射模板中允许可选键
【发布时间】:2020-04-03 01:14:32
【问题描述】:

我有一个扫描 DynamoDB 表的 API 网关。我想在我的请求正文中传递LastEvaluatedKey;如果我通过LastEvaluatedKey,那么一切正常,我会得到预期数据的响应 - 所以我已经完成了一半。

但是,当然,我第一次向 API 发送请求时LastEvaluatedKey 将不存在,因此映射模板中需要LastEvaluatedKeyExclusiveStartKey 必须是可选的。我已经尝试了几种不同的方法来让它成为可选的,但到目前为止没有任何效果。这是我所拥有的:

#set($hasName = $input.json('$.Name'))
{
    "TableName": "MyTable",
    #if($hasName && $hasName.length() != 0)
    "ExclusiveStartKey": {
        "Name": {
            "S": $input.json('$.Name')
        },
        "Date": {
            "S": $input.json('$.Date')
        }
    },#end
    "FilterExpression": "begins_with(#dt, :tdt)",
    "ExpressionAttributeNames": {
        "#dt": "Date"
    },
    "ExpressionAttributeValues": {
        ":tdt": {
            "S": "$input.params('date')"
        }
    }
}

正如我所说,当我 确实 在我的请求正文中传递 LastEvaluatedKey 时,上述方法有效,但当我没有时,我收到错误:

{
    "__type": "com.amazon.coral.validate#ValidationException",
    "message": "The provided starting key is invalid: One or more parameter values were invalid: An AttributeValue may not contain an empty string"
}

...仍然是LastEvaluatedKey

我也尝试将NameDate 包裹在#if 内,但完全没有运气。我从其他答案中获得了灵感,例如:thisthis,但没有运气。

【问题讨论】:

    标签: json amazon-web-services amazon-dynamodb aws-api-gateway mime-types


    【解决方案1】:

    在我的示例中,“光标”是 LastEvaluatedKey:

    #set($hasCursor = $input.params('cursor') != "")
    {
        "TableName": "my-table"
        #if($hasCursor) "ExclusiveStartKey":$util.base64Decode("$input.params('cursor')")
        #end
    }
    
    

    它只检查“光标”是否作为查询参数传递(如 /my/api?cursor=myencodedlastevaluatedkey),如果是,则仅将 ExclusiveStartKey 添加到请求中。

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 2018-06-28
      • 2016-12-03
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 2019-06-06
      相关资源
      最近更新 更多