refactor: 💡 add custom sort to resources (#2860)

* refactor: 💡 add custom sort

* test: 💍 fix tests

* test: 💍 fix more tests

* refactor: 💡 use reusable sort function for name

* refactor: 💡 use sort util in all resources w/ optional name

* Add missing copyright headers

* test: 💍 fix broken tests & add tests for new util

* refactor: 💡 add name custom sort to users

* test: 💍 fix import in tests

* refactor: 💡 add custom name sort to scopes

* test: 💍 pr feedback on util test cases

* refactor: 💡 move sort function into object (pr feedback)
This commit is contained in:
Lisbet Alvarez authored and GitHub committed 2025-06-05 11:00:25 -07:00
1 parent 4c959ab297
commit 738fa1f15f
27 files changed
+331 -41

No files matched your search

+12 -1
View File
@@ -42,7 +42,7 @@ export const sortResults = (results, { querySort, schema }) => {
// Default sort direction is ascending unless we are sorting by `created_time` (default sort attribute)
const defaultSortDirection =
sortAttribute === SORT_DEFAULT_ATTRIBUTE
sortAttribute === SORT_DEFAULT_ATTRIBUTE && !querySort.sortFunction
? SORT_DIRECTION_DESCENDING
: SORT_DIRECTION_ASCENDING;
const sortDirection = querySort.direction || defaultSortDirection;
@@ -55,6 +55,17 @@ export const sortResults = (results, { querySort, schema }) => {
throw new Error('Invalid sort direction');
}
// Execute custom sort function if one is provided.
if (querySort.sortFunction) {
return results.toSorted((a, b) => {
const sortResult = querySort.sortFunction(a, b);
return sortDirection === SORT_DIRECTION_ASCENDING
? sortResult
: -1 * sortResult;
});
}
const sortAttributeDataType = schema.attributes.get(sortAttribute)?.type;
const sortFunction =