Search code examples
graphqlaws-appsync

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


Is it possible in AWS AppSync to query an HTTP resolver with an additional where/filter clause.

example, the http resolver returns a product list (all rows). Some use causes require a filter on the results.

Example; where price < $10.


Solution

  • Yes, it is possible to filter data from your HTTP data source. One way I can think of is to use if/else condition in the response template to filter data you need.

    Assuming you are taking price as in input in your query definition and your result body from your request template looks something like this;

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

    Then in your response template, you can do something like;

    #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
    

    Expected result:

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

    Hope this helps.