amazon-web-services - 如何直接从请求映射器返回?

标签 amazon-web-services graphql aws-appsync vtl

考虑以下 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/

相关文章:

ruby-on-rails - 使用 aws-sdk 流式上传大文件

javascript - 声明式与编程式 GraphQL

amazon-s3 - 如何使用 AWS AppSync 将文件上传到 AWS S3

amazon-web-services - aws cdk Fn.import_value 返回 token 忽略bucketname 的cloudformation 输出并显示 token

amazon-web-services - 使云端控制台文件夹中的所有文件无效

python - 如何以编程方式将 lambda 监听器规则注册到 ALB?

graphql - 如何通过 postman 发送graphql查询?

javascript - CraftCMS Gatsby 项目抛出错误 "GraphQL Error Expected type [String], found {eq: $slug}."

amazon-web-services - 如何使用 AppSync Resolvers 和 Aurora 将可选字段插入为空?

aws-appsync - 运行事务 - AppSync Aurora 无服务器解析器 RDS