From d48971c95e621d7b88a80c580c909312fca8ba30 Mon Sep 17 00:00:00 2001 From: Avior Date: Sun, 19 May 2024 01:32:23 +0200 Subject: [PATCH] fix: Ordering failing when one value is null (#490) --- ...89-crash-when-sorting-with-null-values.bru | 17 ++++++++++++++++ server/cards-database | 1 + server/src/util.ts | 20 +++++++++++++++---- 3 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 .bruno/fixes/489-crash-when-sorting-with-null-values.bru create mode 160000 server/cards-database diff --git a/.bruno/fixes/489-crash-when-sorting-with-null-values.bru b/.bruno/fixes/489-crash-when-sorting-with-null-values.bru new file mode 100644 index 000000000..75b71802d --- /dev/null +++ b/.bruno/fixes/489-crash-when-sorting-with-null-values.bru @@ -0,0 +1,17 @@ +meta { + name: 489 - Crash When sorting with Null values + type: http + seq: 6 +} + +get { + url: {{BASE_URL}}/v2/en/cards?name=pikachu&sort:field=hp&sort:order=DESC + body: none + auth: none +} + +query { + name: pikachu + sort:field: hp + sort:order: DESC +} diff --git a/server/cards-database b/server/cards-database new file mode 160000 index 000000000..c476d8261 --- /dev/null +++ b/server/cards-database @@ -0,0 +1 @@ +Subproject commit c476d826181afdd121cc80331abfa94d5f06785e diff --git a/server/src/util.ts b/server/src/util.ts index 972b1f7ae..e5b8fbf08 100644 --- a/server/src/util.ts +++ b/server/src/util.ts @@ -150,9 +150,21 @@ export function handleSort(data: Array, query: Query) { * @param order the base ordering * @returns a function that is feed in the `sort` function */ -const advSort = (a: string | number, b: string | number, order: 'ASC' | 'DESC' = 'ASC') => { - a = tryParse(a) ?? a - b = tryParse(b) ?? b +const advSort = (a?: string | number, b?: string | number, order: 'ASC' | 'DESC' = 'ASC') => { + const isANull = isNull(a) + const isBNull = isNull(b) + if (isANull && isBNull) { + return 0 + } + if (isANull) { + return order === 'ASC' ? -1 : 1 + } + if (isBNull) { + return order === 'ASC' ? 1 : -1 + } + + a = tryParse(a!) ?? a + b = tryParse(b!) ?? b if (order === 'DESC') { const tmp = a @@ -164,7 +176,7 @@ const advSort = (a: string | number, b: string | number, order: 'ASC' | 'DESC' = return a - b } - return a.toString().localeCompare(b.toString()) + return a!.toString().localeCompare(b!.toString()) } function tryParse(value: string | number): number | null {