How to sort and filter by createdAt and updatedAt in aws AppSync?

Viewed 1751

I used AWS Amplify to create an GraphQL API. In DynamoDB the fields createdAt and updatedAt are created automatically. I have no way of filter values for this fields with Appsync. I would like to query data with appsync with filter range between two createdAt field but it doesn't appear in my appsync query schema.

So how can I do a query with createdAt filter or sort?

This is an AWS-Amplify specific question. It's not about how to do this with generic GraphQL.

1 Answers

I found the solution finally.

You have to add auto generated fields "createdAt" and "updatedAt" directly on the schema.graphql

Like that:

According to this inital schema.graphql:

type User @model(timestamps: { createdAt: "createdOn", updatedAt: "updatedOn" })
{
  id: String!
  username: String!
  firstName: String!
  lastName: String!
} 

It will become:

type User @model
{
  id: String!
  username: String!
  firstName: String!
  lastName: String!
  createdAt: AWSDateTime! #important to keep it to have filter with keys
  updatedAt: AWSDateTime! #important to keep it to have filter with keys
} 

After the amplify push, we can get items by date directly, simply like that:

query MyQuery {
  listUsers(filter: {updatedAt: {between: ["2021-04-29T16:02:21.285Z", "2021-05-29T16:02:21.285Z"]}}) {
    items {
      id
      lastName
    }
  }
}
Related