Consider the following GraphQL template:
type Foo {
id: ID!
bars: Bars
}
type Bar {
id: ID!
name: String!
}
type Bars {
items: [Bar]!
nextToken: String
}
The mapping template for the bars
field in the Foo type looks like this:
#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
}
}
}
This works well. But if the bars
field contains and empty array []
, the template will obviously crash with the following error:
"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"
}
]
So my question is:
How do I prevent the query to be executed and just return an empty array to the response template when $context.source.bars
is empty ?
It took me hours to figure out this one. It's as simple as calling the #return(data)
from the request mapper.
In your case:
#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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With