Skip to content

Commit

Permalink
fix(sort): convert Date to ISO string (#1175)
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz committed May 30, 2022
1 parent fa702b7 commit 0002a38
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/runtime/query/match/utils.ts
Expand Up @@ -67,9 +67,18 @@ export const sortList = (data: any[], params: SortOptions) => {
for (const key of keys) {
data = data.sort((a, b) => {
const values = [get(a, key), get(b, key)]
// `null` values are treated as `"null"` strings and ordered alphabetically
// Turn `null` values into `undefined` so they place at the end of the list
.map(value => value === null ? undefined : value)
.map((value) => {
// `null` values are treated as `"null"` strings and ordered alphabetically
// Turn `null` values into `undefined` so they place at the end of the list
if (value === null) {
return undefined
}
// Convert Date object to ISO string
if (value instanceof Date) {
return value.toISOString()
}
return value
})
if (params[key] === -1) {
values.reverse()
}
Expand Down
22 changes: 22 additions & 0 deletions test/features/query/query.test.ts
Expand Up @@ -75,6 +75,28 @@ describe('Database Provider', () => {
})
})

test('Apply sort Date', async () => {
const dates = [
{ date: new Date('2022-01-01 00:00:00.001Z') },
{ date: new Date('2021-01-01 00:00:00.001Z') },
{ date: new Date('2020-01-01 00:00:00.001Z') },
{ date: new Date('2019-01-01 00:00:00.001Z') },
{ date: new Date('2018-01-01 00:00:00.001Z') },
{ date: new Date('1900-01-01 00:00:00.001Z') }
]
const fetcher = createPipelineFetcher(() => Promise.resolve(dates.sort(() => 1 - Math.random())))

const sortedByDate1 = await createQuery(fetcher).sort({ date: 1 }).find()
;([...dates].reverse()).forEach(({ date }, index) => {
expect(sortedByDate1[index].date).toBe(date)
})

const sortedByDate0 = await createQuery(fetcher).sort({ date: -1 }).find()
dates.forEach(({ date }, index) => {
expect(sortedByDate0[index].date).toBe(date)
})
})

test('Apply sort $numeric', async () => {
// sort string alphabetically
const nonNumericSort = await createQuery(pipelineFetcher).sort({ numberString: 1 }).find()
Expand Down

0 comments on commit 0002a38

Please sign in to comment.