【问题标题】:How to write a AWS AppSync response mapping template for an RDS data source如何为 RDS 数据源编写 AWS AppSync 响应映射模板
【发布时间】:2020-04-22 02:46:00
【问题描述】:

我一直在关注此guide,以通过 AppSync 模式查询 Aurora Serverless 数据库。现在我想同时运行几个查询,请求映射如下:

{
    "version": "2018-05-29",
        "statements": [
            "SELECT * FROM MyTable WHERE category='$ctx.args.category'",
            "SELECT COUNT(*) FROM MyTable WHERE category='$ctx.args.category'",
    ]
}

那么,如何处理响应映射中的多个选择?该页面有几个示例,但没有一个有两个选择:

$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])    ## For first item results
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0][0]) ## For first item of first query
$utils.toJson($utils.rds.toJsonObject($ctx.result)[1][0]) ## For first item of second query
$utils.toJson($utils.rds.toJsonObject($ctx.result)??????) ## ?? For first & second item results

我预测响应类型如下,但不严格,只要我能得到值。

type MyResponse {
    MyResponseItemList [MyResponseItem]
    Count Int
}

type MyResponseItem {
  Id: ID!
  Name: String
  ...
}

【问题讨论】:

  • 我可以在 GraphQL 中查看您的响应类型吗?
  • 您可以建议任何结构以产生所需的输出,即列表项和计数。但我已经编辑分享了我认为它会是什么样子。

标签: amazon-web-services amazon-rds aws-appsync vtl


【解决方案1】:

我遇到了同样的问题,并得到了如下工作。

我没有将 Count 作为直接 Int 类型结果,而是将其转换为另一种称为 PaginationResult 的类型。

type MyResponse {
    MyResponseItemList [MyResponseItem]
    Count PaginationResult
}

type PaginationResult {
   Count Int
}

type MyResponseItem {
...
}

响应速度模板

#set($resMap = {
    "MyResponseItemList": $utils.rds.toJsonObject($ctx.result)[0],
    "Count": $utils.rds.toJsonObject($ctx.result)[1][0]
})
$util.toJson($resMap)

【讨论】:

    【解决方案2】:

    FWIW,我刚刚开始使用两个 SELECT 进行 UNION ALL Appsync/RDS 请求解析器查询:

      {  
        "version": "2018-05-29",   
        "statements": ["SELECT patientIDa, patientIDb, distance FROM Distances WHERE patientIDa='$ctx.args.patientID' UNION ALL SELECT patientIDb, patientIDa, distance FROM Distances WHERE patientIDb='$ctx.args.patientID'"]  
    }
    

    不确定这是否会帮助 OP,但它可能会。

    ***注意:在我的情况下(可能是因为我在 Windows 上)整个 ["SELECT...] 语句需要在一行上(没有 cr/lf),否则 graphql 错误“非转义字符.. .”(使用 GraphiQL 进行测试)

    【讨论】:

    • 原来的帖子确实需要两个返回不同类型的 sql 查询。您的 UNIONed 查询都返回相同的类型。
    【解决方案3】:

    进行两次选择不适用于 AppSync。

    我建议您要么将两个 SQL 查询拆分为两个不同的 GraphQL 查询操作,要么将两个 SQL 查询合并为一个。

    【讨论】:

    • AWS 文档说 SQL 语句的限制是 2。给我看说明你说什么的文档。
    • @Ricardo 我添加了一个答案。在那里,我没有使用 Count 作为 int,而是使用另一种类型。请您查看我的回答好吗?
    猜你喜欢
    • 2019-07-19
    • 2020-01-28
    • 2022-11-10
    • 2019-01-05
    • 2022-01-23
    • 2021-12-08
    • 2020-02-17
    • 2018-07-31
    • 1970-01-01
    相关资源
    最近更新 更多