TSK-1248: sort null last for dates (#3021)

Signed-off-by: Vyacheslav Tumanov <me@slavatumanov.me>
This commit is contained in:
Vyacheslav Tumanov 2023-04-19 23:48:33 +05:00 committed by GitHub
parent 20305973d4
commit fbb54dfe80
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -349,6 +349,8 @@ abstract class MongoAdapterBase implements DbAdapter {
if (typeof options.sort[_key] === 'object') {
const rules = options.sort[_key] as SortingRules<T>
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<T extends Doc>(_class: Ref<Class<T>>, key: string): boolean {
const attr = this.hierarchy.findAttribute(_class, key)
if (attr !== undefined) {
return attr.type._class === core.class.TypeDate
}
return false
}
private isRulesSort<T extends Doc>(options?: FindOptions<T>): 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<Doc>, _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<T extends Doc> (
rules: SortingRules<T>,
key: string,