From fbb54dfe80fd9aacb6eaf169b5dc4dfc0c37fbbd Mon Sep 17 00:00:00 2001 From: Vyacheslav Tumanov Date: Wed, 19 Apr 2023 23:48:33 +0500 Subject: [PATCH] TSK-1248: sort null last for dates (#3021) Signed-off-by: Vyacheslav Tumanov --- server/mongo/src/storage.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/server/mongo/src/storage.ts b/server/mongo/src/storage.ts index 789eafbf0e..aac8bc94b0 100644 --- a/server/mongo/src/storage.ts +++ b/server/mongo/src/storage.ts @@ -349,6 +349,8 @@ abstract class MongoAdapterBase implements DbAdapter { if (typeof options.sort[_key] === 'object') { const rules = options.sort[_key] as SortingRules fillCustomSort(rules, key, pipeline, sort, options, _key) + } else if (this.isDate(clazz, _key)) { + fillDateSort(key, pipeline, sort, options, _key) } else { // Sort enum if no special sorting is defined. const enumOf = this.getEnumById(clazz, _key) @@ -486,6 +488,14 @@ abstract class MongoAdapterBase implements DbAdapter { ) } + private isDate(_class: Ref>, key: string): boolean { + const attr = this.hierarchy.findAttribute(_class, key) + if (attr !== undefined) { + return attr.type._class === core.class.TypeDate + } + return false + } + private isRulesSort(options?: FindOptions): boolean { if (options?.sort !== undefined) { return Object.values(options.sort).some((it) => typeof it === 'object') @@ -1034,6 +1044,18 @@ function fillEnumSort ( } sort[`sort_${key}`] = options.sort[_key] === SortingOrder.Ascending ? 1 : -1 } +function fillDateSort (key: string, pipeline: any[], sort: any, options: FindOptions, _key: string): void { + if (options.sort === undefined) { + options.sort = {} + } + pipeline.push({ + $addFields: { + [`sort_isNull_${key}`]: { $eq: [`$${key}`, null] } + } + }) + sort[`sort_isNull_${key}`] = options.sort[_key] === SortingOrder.Ascending ? 1 : -1 + sort[key] = options.sort[_key] === SortingOrder.Ascending ? 1 : -1 +} function fillCustomSort ( rules: SortingRules, key: string,