如何在 API 网关映射模板中允许可选键
How to allow Optional Key in API Gateway mapping template
我有一个扫描 DynamoDB table 的 API 网关。我想在我的请求正文中传递 LastEvaluatedKey
;如果我通过了 LastEvaluatedKey
,那么一切正常,我得到了预期数据的响应 - 所以我已经完成了一半。
但是,当然,我第一次向 API 发送请求 LastEvaluatedKey
将不存在,因此映射模板中的 ExclusiveStartKey
需要 [=13] =] 必须是可选的。我已经尝试了几种不同的方法来使它成为可选的,但到目前为止没有任何效果。这是我拥有的:
#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')"
}
}
}
正如我所说,当我 do 在我的请求正文中传递 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
我也尝试过将 Name
和 Date
包装在 if #if
内,但完全没有成功。我从其他答案中获得了灵感,例如:this and this,但没有运气。
在我的示例中 'cursor' 是 LastEvaluatedKey:
#set($hasCursor = $input.params('cursor') != "")
{
"TableName": "my-table"
#if($hasCursor) "ExclusiveStartKey":$util.base64Decode("$input.params('cursor')")
#end
}
它只是检查 'cursor' 是否作为查询参数传递(如 /my/api?cursor=myencodedlastevaluatedkey),如果是,则只将 ExclusiveStartKey 添加到请求中。
我有一个扫描 DynamoDB table 的 API 网关。我想在我的请求正文中传递 LastEvaluatedKey
;如果我通过了 LastEvaluatedKey
,那么一切正常,我得到了预期数据的响应 - 所以我已经完成了一半。
但是,当然,我第一次向 API 发送请求 LastEvaluatedKey
将不存在,因此映射模板中的 ExclusiveStartKey
需要 [=13] =] 必须是可选的。我已经尝试了几种不同的方法来使它成为可选的,但到目前为止没有任何效果。这是我拥有的:
#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')"
}
}
}
正如我所说,当我 do 在我的请求正文中传递 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
我也尝试过将 Name
和 Date
包装在 if #if
内,但完全没有成功。我从其他答案中获得了灵感,例如:this and this,但没有运气。
在我的示例中 'cursor' 是 LastEvaluatedKey:
#set($hasCursor = $input.params('cursor') != "")
{
"TableName": "my-table"
#if($hasCursor) "ExclusiveStartKey":$util.base64Decode("$input.params('cursor')")
#end
}
它只是检查 'cursor' 是否作为查询参数传递(如 /my/api?cursor=myencodedlastevaluatedkey),如果是,则只将 ExclusiveStartKey 添加到请求中。