Reputation: 1887
I've seen several useful posts on how to create schemas in AWS-Amplify's GrahphQL API package that will return a sorted response. In brief, if you have the following in your schema.graphql
file
type Record @model
@key(name: "byDateCreated", fields: ["status", "createdAt"], queryField: "RecordsByDateCreated") {
id: ID!
status: RecordStatus!
description: String!
createdAt: String
}
It will create a custom query called recordsByDateCreated
. Using it as follows (js here, folks):
await API.graphql(graphqlOperation(recordsByDateCreated, { status: 'unused', limit: 10 }));
will return the first 10 records in the table sorted by their createdAt
values. By default, this data will be returned in ascending order, which means that you'll get the oldest records first.
However, what I need is a response that has the newest records first. What do I have to add to in schema or my query so I can set the order of the sorting?
Upvotes: 3
Views: 5456
Reputation: 27
(Can't comment with a reputation below 50 lol so need to make a whole other answer)
As you mentioned adding sortDirection
as one of the variables arguments allows you to choose the direction, but also if you're looking to sort the items by a specific attribute other than the default one, you'll have to make that choice in the graphql schema model definition.
So for the model User
you'd choose the attribute in the second key field
type User
@model
@key(fields: ["id", "DoB"]) {
id: ID!
name: String!
DoB: String!
createdAt: String!
}
and a query would sort the items by their DoB
Upvotes: 0
Reputation: 1887
(Spoiler alert: I'm answering my own question here in case anyone else is looking for help with this.)
You would need a way to order the table's records in descending order. If you go and look at the file generated by AWS-Amplify you'll see that the new query you've created accepts a series of arguments:
export const recordsByDateCreated = /* GraphQL */ `
query RecordsByDateCreated(
$status: RecordStatus
$createdAt: ModelStringKeyConditionInput
$sortDirection: ModelSortDirection
$filter: ModelRecordFilterInput
$limit: Int
$nextToken: String
) {
RecordsByDateCreated(
status: $status
createdAt: $createdAt
sortDirection: $sortDirection
filter: $filter
limit: $limit
nextToken: $nextToken
) {
items {
id
description
status
createdAt
updatedAt
}
nextToken
}
}
`
It turns out that if you know what the possible values are for ModelSortDirection
(they are are 'ASC' and 'DESC') you can pass one in as one of the variables arguments when you make that query like so:
await API.graphql(graphqlOperation(recordsByDateCreated, { status: 'unused', limit: 10, sortDirection: 'DESC' }));
(Note that the key for the variable you're passing is sortDirection
and not $sortDirection
, or ModelSortDirection
.)
I couldn't find this in AWS-Amplify's docs and relied on other posts that I've found. If you've found any documentation relevant to this then maybe you could add a link in the comments.
Upvotes: 3