Deep Arora
Deep Arora

Reputation: 2040

AWS App Sync dynamodb resolver usage with begin_with expression in Sort Key not working

I am trying to get the list of pets that belongs to a specific username.

Table Design (PetTable):

username: partition key
petId: sort key, 

The value of petId is generate by concatenating the string "petId:" and random autoId value. So, if autoId is 3838380022, then the value of petId sort key will be "petId:3838380022"

Schema:

type Pet {
    username: String!
    petId: ID!
}

type PetsConnection {
    pets: [Pet]
}

type Query {
    getPets(username: String): PetsConnection
}

Resolver:

{
    "version" : "2017-02-28",
    "operation" : "Query",
    "query" : {
        ## Provide a query expression. **
        "expression": "username = :username and begins_with(petId, :petId)",
        "expressionValues" : {
            ":username" : {
                "S" : "${ctx.args.username}"
            },
            ":petId" : {
                "S" : "pet"
            }

        }
    }
}

Query:

query GetUserPets {
  getPets(username: "test") {
    pets {
      petId
    }
  }
}

Query Response:

{
  "data": {
    "getPets": {
      "pets": null
    }
  }
}

In the Dynamodb, I have 2 entires where the petId(SortKey) starts with the text pet.enter image description here

Expecting the query should return 2 entries, but it doesn't return anything. Not sure where the mistake is. Any help will be greatly appreciated. Thanks.

Upvotes: 1

Views: 2802

Answers (2)

KoingDev
KoingDev

Reputation: 620

I tried to reproduce your schema and test it as much as possible. It works fine for me

type Pet {
    username: String!
    petID: ID!
}

type Query {
    getPets(username: String!): [Pet]
}

schema {
    query: Query
}

Make sure when you create resource for PetTable (username as PK and petID as sort-key)

enter image description here

Attach resolver for the query

enter image description here

DynamoDB

enter image description here

Testing result

enter image description here

Upvotes: 3

Tinou
Tinou

Reputation: 6158

What is your response mapping template? You probably left the default mapping template that returns a list of results, instead of mapping the query results from DynamoDB to your PetConnection type.

I reproduced your API and I was able to get results using the same GraphQL query.

Here is my Response template:

#set($petConnection = { 'pets': $ctx.result.items })
$util.toJson($petConnection)

And results:

{
  "data": {
    "getPets": {
      "pets": [
        {
          "petId": "petId:1234"
        },
        {
          "petId": "petId:12345"
        }
      ]
    }
  }
}

Note: One great way to debug your application is to enable logs from the API settings page. See below how to enable logs. Once enabled, head to the Queries pane, tick the logs checkbox and execute a GraphQL query. Your application logs should appear right in the console. enter image description here

Upvotes: 2

Related Questions