amplify-category-api icon indicating copy to clipboard operation
amplify-category-api copied to clipboard

Is there a simple way to get a list of items by a set of ids?

Open chrisco512 opened this issue 6 years ago • 11 comments

** Which Category is your question related to? ** API

** What AWS Services are you utilizing? ** AppSync, Amplify

** Provide additional details e.g. code snippets ** Is there a simple way to write a resolver to get a list of items from a table by passing in a set of ids?

I'm currently solving this problem by building a filter expression string rather manually (this is a function for a pipeline resolver):

#set( $expValues = {} )
#set( $expression = "#id IN (" )
#set( $ids = $ctx.stash.get("ids"))

#set( $index = 0 )

#foreach( $id in $ids )
    #set( $index = $index + 1 )
    #if( $ids.size() == $index )
        #set( $expression = "${expression} :id${index})" )
    #else
        #set( $expression = "${expression} :id${index}, " )
    #end
    $util.qr( $expValues.put(":id${index}", { "S" : "${id}" }) )
#end

{
  "operation" : "Scan",
  "filter" : {
      "expression" : "${expression}",
      "expressionNames": {
        "#id" : "id"
      },
      "expressionValues" : $util.toJson($expValues)
  }
}

Is this the best way? For example, I noticed there was a utility, $util.transform.toDynamoDBFilterExpression and tried implementing it as suggested from @mikeparisstuff 's answer on StackOverflow: https://stackoverflow.com/questions/52046495/util-transform-todynamodbfilterexpression

But I kept getting errors in the response about $util and expecting 'null', 'true', or 'false'. So I had to resort to the above approach.

It would be nice to have a better way to build complex queries as DynamoDB-JSON is a bit painful to write. I was hoping to be able to use similar filters (with OR: [{ id: "123" }, {id: "124"}] -type constructs that AppSync/Amplify already provides at the API level, but at the resolver level.

chrisco512 avatar Apr 01 '19 09:04 chrisco512