Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort by date(createdAt) on a field in list query in aws-amplify?

type Test @model @key(fields: ["id", "createdAt"]) {
  id: ID!
  name: String
  createdAt: String!
}

This model created queries:

getTest(createdAt: String!id: ID!): Test

listTests(
  createdAt: ModelStringKeyConditionInput
  filter: ModelTestFilterInput
  id: ID
  limit: Int
  nextToken: String
  sortDirection: ModelSortDirection
): ModelTestConnection

What should the scheme look like to request a list sorted by date?

like image 349
Дмитрий Инжеваткин Avatar asked Oct 02 '19 14:10

Дмитрий Инжеваткин


1 Answers

When @key specifies multiple fields, the first field is used as the HASH key and subsequent fields as the SORT key.

https://aws-amplify.github.io/docs/cli-toolchain/graphql#key

It is possible to list sorted items which have the same HASH key. For example, listing all comments by a user:

type Comment
  @model
  @key(fields: ["userId", "createdAt"]) {
    userId: ID!
    createdAt: String!
    text: String
}

Assuming you're using AWS Amplify's GraphQL client, this will list all comments by a user, sorted newest first:

import { API, graphqlOperation } from 'aws-amplify';
import { listComments } from '@/graphql/queries';

export default async function listCommentsForUser(userId) {
  const queryParams = {
    userId,
    sortDirection: 'DESC',
  };

  const operation = graphqlOperation(listComments, queryParams);

  return API.graphql(operation);
}

To list comments since a specified date, newest first, change the query params to include a range query:

const queryParams = {
    userId,
    sortDirection: 'DESC',
    createdAt: { gt: timestamp },
  };
like image 188
mattk Avatar answered Oct 13 '22 04:10

mattk