AWS AppSync (GraphQL) - 使用 HTTP 解析器时的 Where/filter 子句

AWS AppSync (GraphQL) - Where/filter clause when using HTTP resolver

是否可以在 AWS AppSync 中查询带有附加 where/filter 子句的 HTTP 解析器。

例如,http 解析器 returns 一个产品列表(所有行)。一些使用原因需要对结果进行过滤。

示例;其中价格 < 10 美元。

是的,可以从您的 HTTP 数据源中过滤数据。我能想到的一种方法是在响应模板中使用 if/else 条件来过滤您需要的数据。

假设您将价格作为查询定义中的输入,并且请求模板中的结果正文如下所示;

{
  "data" :
         [
           {"item" : "ItemA", "price" : 20},
           {"item" : "ItemB", "price" : 10},
           {"item" : "ItemC", "price" : 9},
           {"item" : "ItemD", "price" : 8}
         ]
}

然后在您的回复模板中,您可以做类似的事情;

#set($resultList = [])
#set($resMap = {})
## Raise a GraphQL field error in case of a datasource invocation error
#if($ctx.error)
  $util.error($ctx.error.message, $ctx.error.type)
#end
## If the response is not 200 then return an error. Else return the filtered data **
#if($ctx.result.statusCode == 200)
  #foreach($item in $ctx.result.body.data)
    #if($item.price < $ctx.args.price)
      $util.qr($resultList.add($item))
    #end
  #end
  $util.qr($resMap.put("result", $resultList))
  #return($resMap)          
#else
  $utils.appendError($ctx.result.body, "$ctx.result.statusCode")
#end

预期结果:

{
  "result" :
          [
           {"item" : "ItemC", "price" : 9},
           {"item" : "ItemD", "price" : 8}
          ] 
}

希望对您有所帮助。