Search code examples
react-nativegraphqlamazon-dynamodbaws-amplifydynamodb-queries

How To Use The Same GraphQL Query Multiple Times In A Single API Call. Amplify, DynamoDB


The user will input multiple usernames and I would like to search my DynamoDB table for all each user's id in a single API call. The following is the important portion of the graphql user schema:

type User
  @model
  @key(name: "byName", fields: ["username"], queryField: "findUsername")
   {
  id: ID!
  email: AWSEmail!
  username: String!
  firstName: String
  lastName: String
  createdAt: AWSDateTime
  updatedAt: AWSDateTime
} 

I would like to create a query which takes the list of usernames and returns each user's user id in a single api call. I am not sure how to dynamically and separately add the usernames to a query. Btw, I am using aws-amplify to help with dynamodb and graphql. This is also a React Native project.


Solution

  • You can run multiple queries and mutations using batch operations in AWS AppSync. Eg: BatchGetItem

    type Post {
        id: ID!
        title: String
    }
    
    type Query {
        batchGet(ids: [ID]): [Post]
    }
    

    Sample query

    query get {
        batchGet(ids:[1,2,3]){
            id
            title
        }
    }
    

    batchGet.request.vtl

    #set($ids = [])
    #foreach($id in ${ctx.args.ids})
        #set($map = {})
        $util.qr($map.put("id", $util.dynamodb.toString($id)))
        $util.qr($ids.add($map))
    #end
    
    {
        "version" : "2018-05-29",
        "operation" : "BatchGetItem",
        "tables" : {
            "Posts": {
                "keys": $util.toJson($ids),
                "consistentRead": true
            }
        }
    }
    

    batchGet.response.vtl

    $util.toJson($ctx.result.data.Posts)
    

    For more details check out this tutorial. https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-batch.html