Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return directly from the request mapper?

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 ?

like image 961
Quentin Hayot Avatar asked Oct 09 '18 16:10

Quentin Hayot


1 Answers

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
         }
     }
}
like image 70
Matej Balantič Avatar answered Nov 06 '22 19:11

Matej Balantič