In this guide you will learn how to implement sorting in a GraphQL API. In our example, you will implement sorting results by date in either an ascending or descending order by implementing an additional data access pattern leveraging a DynamoDB Global Secondary Index using the @index
GraphQL Transformer directive.
To get started, let's start with a basic GraphQL schema for a Todo app:
When the API is created with an @model
directive, the following queries will automatically be created for you:
Next, take a look at the ModelTodoConnection
type to get an idea of the data that will be returned when the listTodos
query is run:
By default, the listTodos
query will return the items
array unordered. Many times you will need these items to be ordered by title, by creation date, or in some other way.
To enable this, you can use the @index directive. This directive will allow you to set a custom sortKey
on any field in your API.
In this example, you will enable sorting by the createdAt
field. By default, Amplify will populate this createdAt
field with a timestamp if none is passed in.
To enable this, update your schema with the following:
When created a Todo, you must now populate the type
field for this to work properly.
Next, create a few todos being sure to populate the type
field:
Now, you can query for todos by date in an ascending or descending order using the new todosByDate
query:
To learn more about the @index
directive, check out the documentation here
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4