-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapplySort.ts
More file actions
72 lines (66 loc) · 2.32 KB
/
applySort.ts
File metadata and controls
72 lines (66 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { SelectQueryBuilder, Selectable } from "kysely";
import { SortOrder } from "../../../graphql/schemas/enums/sortEnums.js";
import { SupportedDatabase } from "../../../services/database/strategies/QueryStrategy.js";
/**
* Applies sorting to a query based on the provided arguments.
* This function processes each sort condition and applies them in sequence to the query.
*
* @typeParam DB - The database type extending SupportedDatabases
* @typeParam T - The table name type (must be a key of DB and a string)
* @typeParam Args - The arguments type containing optional sortBy property
*
* @param query - The Kysely SelectQueryBuilder instance to apply sorting to
* @param args - The arguments containing sort conditions
*
* @returns The modified query with sorting applied
*
* @remarks
* - If no sort conditions are provided (args.sortBy is undefined), returns the original query
* - Null or undefined sort directions are filtered out
* - Sort conditions are applied in sequence, maintaining the order specified
* - TypeScript type checking should prevent invalid field names at compile time
* - SortOrder.ascending maps to 'asc', SortOrder.descending maps to 'desc'
*
* @example
* ```typescript
* const query = db.selectFrom('users');
* const args = {
* sortBy: {
* name: SortOrder.ascending,
* created_at: SortOrder.descending
* }
* };
* const result = applySort(query, args);
* ```
*/
export function applySort<
DB extends SupportedDatabase,
T extends keyof DB & string,
Args extends {
sortBy?: { [K in keyof DB[T]]?: SortOrder | null | undefined };
},
>(
query: SelectQueryBuilder<DB, T, Selectable<DB[T]>>,
args: Args,
): SelectQueryBuilder<DB, T, Selectable<DB[T]>> {
if (!args.sortBy) {
return query;
}
// Filter out null/undefined values
const sortEntries = Object.entries(args.sortBy).filter(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
([_, direction]) => direction !== null && direction !== undefined,
);
if (sortEntries.length === 0) {
return query;
}
let modifiedQuery = query;
for (const [field, direction] of sortEntries) {
const orderDirection = direction === SortOrder.ascending ? "asc" : "desc";
modifiedQuery = modifiedQuery.orderBy(
field as keyof DB[T] & string,
orderDirection,
);
}
return modifiedQuery;
}