如何直接从请求映射器返回?

Que*_*yot 8 vtl amazon-web-services graphql aws-appsync

考虑以下 GraphQL 模板:

type Foo {
  id: ID!
  bars: Bars
}

type Bar {
  id: ID!
  name: String!
}

type Bars {
  items: [Bar]!
  nextToken: String
}
Run Code Online (Sandbox Code Playgroud)

barsFoo 类型字段的映射模板如下所示:

#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
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

这很好用。但是如果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"
    }
  ]
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:
如何防止执行查询并在$context.source.bars为空时仅将空数组返回到响应模板?

Mat*_*tič 11

我花了几个小时才弄明白这个。它就像#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
         }
     }
}
Run Code Online (Sandbox Code Playgroud)