Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(sort): convert Date to ISO string #1175

Merged
merged 4 commits into from May 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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