Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting results in AWS Amplify GraphQL without filtering

Provided a very simple model in graphql.schema, how would I perform a simple sort query?

type Todo @model
  id: ID!
  text: String!
}

Which generates the following in queries.js.

export const listTodos = /* GraphQL */ `
  query ListTodos(
    $filter: ModelTodoFilterInput
    $limit: Int
    $nextToken: String
  ) {
    listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {
      items {
        id
        text
      }
      nextToken
    }
  }
`;

I have found multiple sources pointing me in the direction of the @key directive. This similar question addresses that approach (GraphQL with AWS Amplify - how to enable sorting on query).

While that may seem promising and successfully generates new queries I can use, all the approaches I have tried require that I filter the data before sorting it. All I want to do is sort my todo results on a given column name, with a given sort direction (ASC/DESC).

This is how I would perform a simple (unsorted) query: const todos = await API.graphql(graphqlOperation(listTodos));

I would be looking to do something along the lines of: const todos = await API.graphql(graphqlOperation(listTodos, {sortField: "text", sortDirection: "ASC"} )).

like image 879
IanBussieres Avatar asked Oct 15 '22 02:10

IanBussieres


2 Answers

Decorate your model with the @searchable directive, like so:

type Todo @model @searchable
{
  id: ID!
  text: String!
}

After that, you can query your data with sorting capabilities like below:

import { searchToDos } from '../graphql/queries';
import { API, graphqlOperation } from 'aws-amplify';

const toDoData = await API.graphql(graphqlOperation(searchToDos, {
  sort: {
    direction: 'asc',
    field: 'text'
  }
}));
console.log(toDoData.data.searchToDos.items);

For more information, see

  • https://github.com/aws-amplify/amplify-cli/issues/1851#issuecomment-545245633
  • https://docs.amplify.aws/cli/graphql-transformer/directives#searchable
like image 79
MTran Avatar answered Oct 20 '22 23:10

MTran


I've accepted MTran's answer because it feels to me it is the nearest thing to an actual solution, but I've also decided to actually opt for a workaround. This way, I avoid adding a dependency to ElasticSearch.

I ended up adding a field to my schema and every single entry has the same value for that field. That way, I can filter by that value and still have the entire table of values, that I can then sort against.

like image 45
IanBussieres Avatar answered Oct 21 '22 00:10

IanBussieres