考虑以下 GraphQL 模板:
type Foo {
id: ID!
bars: Bars
}
type Bar {
id: ID!
name: String!
}
type Bars {
items: [Bar]!
nextToken: String
}
bars
的映射模板Foo 类型中的字段如下所示:#set($ids = [])
#foreach($id in $context.source.bars)
#set($map = {})
$util.qr($map.put("id", $util.dynamodb.toString($id)))
$util.qr($ids.add($map))
#end
{
"version" : "2018-05-29",
"operation" : "BatchGetItem",
"tables" : {
"barsTable" : {
"keys": $util.toJson($ids),
"consistentRead": true
}
}
}
这很好用。但是如果
bars
字段包含和空数组[]
,模板显然会崩溃并出现以下错误:"errors": [
{
"path": [
"getFoo",
"bars"
],
"data": null,
"errorType": "MappingTemplate",
"errorInfo": null,
"locations": [
{
"line": 59,
"column": 7,
"sourceName": null
}
],
"message": "RequestItem keys '$[tables][barsTable]' can't be empty"
}
]
所以我的问题是:
当
$context.source.bars
时,如何防止查询被执行并只返回一个空数组到响应模板是空的 ?
最佳答案
我花了几个小时才弄清楚这个。就像调用 #return(data)
一样简单来自请求映射器。
在你的情况下:
#if ($context.source.bars.size() <= 0)
#return([])
#end
#set($ids = [])
#foreach($id in $context.source.bars)
#set($map = {})
$util.qr($map.put("id", $util.dynamodb.toString($id)))
$util.qr($ids.add($map))
#end
{
"version" : "2018-05-29",
"operation" : "BatchGetItem",
"tables" : {
"barsTable" : {
"keys": $util.toJson($ids),
"consistentRead": true
}
}
}
关于amazon-web-services - 如何直接从请求映射器返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52725737/