@catbee/utils 0.0.8-rc.2 → 0.0.8-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/build/index.cjs +6591 -0
  2. package/build/index.d.ts +5131 -0
  3. package/build/index.mjs +6321 -0
  4. package/package.json +12 -36
  5. package/build/esm/config.d.ts +0 -121
  6. package/build/esm/config.js +0 -132
  7. package/build/esm/index.d.ts +0 -26
  8. package/build/esm/index.js +0 -49
  9. package/build/esm/servers/server.builder.d.ts +0 -507
  10. package/build/esm/servers/server.builder.js +0 -654
  11. package/build/esm/servers/server.d.ts +0 -255
  12. package/build/esm/servers/server.js +0 -963
  13. package/build/esm/types/api-response.d.ts +0 -151
  14. package/build/esm/types/api-response.js +0 -33
  15. package/build/esm/types/index.d.ts +0 -124
  16. package/build/esm/types/index.js +0 -24
  17. package/build/esm/types/server.d.ts +0 -267
  18. package/build/esm/types/server.js +0 -24
  19. package/build/esm/utils/array.utils.d.ts +0 -167
  20. package/build/esm/utils/array.utils.js +0 -344
  21. package/build/esm/utils/async.utils.d.ts +0 -264
  22. package/build/esm/utils/async.utils.js +0 -619
  23. package/build/esm/utils/cache.utils.d.ts +0 -152
  24. package/build/esm/utils/cache.utils.js +0 -294
  25. package/build/esm/utils/context-store.utils.d.ts +0 -188
  26. package/build/esm/utils/context-store.utils.js +0 -290
  27. package/build/esm/utils/crypto.utils.d.ts +0 -159
  28. package/build/esm/utils/crypto.utils.js +0 -278
  29. package/build/esm/utils/date.utils.d.ts +0 -158
  30. package/build/esm/utils/date.utils.js +0 -383
  31. package/build/esm/utils/decorators.utils.d.ts +0 -511
  32. package/build/esm/utils/decorators.utils.js +0 -1013
  33. package/build/esm/utils/dir.utils.d.ts +0 -195
  34. package/build/esm/utils/dir.utils.js +0 -476
  35. package/build/esm/utils/env.utils.d.ts +0 -376
  36. package/build/esm/utils/env.utils.js +0 -782
  37. package/build/esm/utils/exception.utils.d.ts +0 -229
  38. package/build/esm/utils/exception.utils.js +0 -382
  39. package/build/esm/utils/fs.utils.d.ts +0 -163
  40. package/build/esm/utils/fs.utils.js +0 -348
  41. package/build/esm/utils/http-status-codes.d.ts +0 -265
  42. package/build/esm/utils/http-status-codes.js +0 -294
  43. package/build/esm/utils/id.utils.d.ts +0 -35
  44. package/build/esm/utils/id.utils.js +0 -83
  45. package/build/esm/utils/logger.utils.d.ts +0 -159
  46. package/build/esm/utils/logger.utils.js +0 -304
  47. package/build/esm/utils/middleware.utils.d.ts +0 -99
  48. package/build/esm/utils/middleware.utils.js +0 -235
  49. package/build/esm/utils/obj.utils.d.ts +0 -123
  50. package/build/esm/utils/obj.utils.js +0 -412
  51. package/build/esm/utils/performance.utils.d.ts +0 -135
  52. package/build/esm/utils/performance.utils.js +0 -273
  53. package/build/esm/utils/request.utils.d.ts +0 -85
  54. package/build/esm/utils/request.utils.js +0 -190
  55. package/build/esm/utils/response.utils.d.ts +0 -162
  56. package/build/esm/utils/response.utils.js +0 -261
  57. package/build/esm/utils/stream.utils.d.ts +0 -87
  58. package/build/esm/utils/stream.utils.js +0 -209
  59. package/build/esm/utils/string.utils.d.ts +0 -92
  60. package/build/esm/utils/string.utils.js +0 -164
  61. package/build/esm/utils/type.utils.d.ts +0 -89
  62. package/build/esm/utils/type.utils.js +0 -186
  63. package/build/esm/utils/url.utils.d.ts +0 -140
  64. package/build/esm/utils/url.utils.js +0 -303
  65. package/build/esm/utils/validate.utils.d.ts +0 -176
  66. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,273 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
- import { TTLCache } from './cache.utils';
25
- import { getLogger } from './logger.utils';
26
- /**
27
- * Measure the execution time of a synchronous function.
28
- *
29
- * @param fn - Function to measure
30
- * @param options - Timing options
31
- * @returns Result containing the return value and timing information
32
- *
33
- * @example
34
- * ```typescript
35
- * const { result, timing } = timeSync(() => {
36
- * // Some expensive operation
37
- * return computeResult();
38
- * }, { label: 'Computation', log: true });
39
- *
40
- * console.log(`Result: ${result}, took ${timing.durationMs}ms`);
41
- * ```
42
- */
43
- export function timeSync(fn, options = {}) {
44
- const { label = fn.name || 'anonymous function', log = false, logLevel = 'debug' } = options;
45
- const startTime = performance.now();
46
- const result = fn();
47
- const endTime = performance.now();
48
- const durationMs = endTime - startTime;
49
- const durationSec = durationMs / 1000;
50
- const timing = {
51
- durationMs,
52
- durationSec,
53
- startTime,
54
- endTime,
55
- label
56
- };
57
- if (log) {
58
- const logger = getLogger();
59
- const message = `${label} completed in ${durationMs.toFixed(2)}ms`;
60
- switch (logLevel) {
61
- case 'trace':
62
- logger.trace({ timing }, message);
63
- break;
64
- case 'debug':
65
- logger.debug({ timing }, message);
66
- break;
67
- case 'info':
68
- logger.info({ timing }, message);
69
- break;
70
- case 'warn':
71
- logger.warn({ timing }, message);
72
- break;
73
- case 'error':
74
- logger.error({ timing }, message);
75
- break;
76
- default:
77
- logger.debug({ timing }, message);
78
- break;
79
- }
80
- }
81
- return { result, timing };
82
- }
83
- /**
84
- * Measure the execution time of an asynchronous function.
85
- *
86
- * @param fn - Async function to measure
87
- * @param options - Timing options
88
- * @returns Promise resolving to result and timing information
89
- *
90
- * @example
91
- * ```typescript
92
- * const { result, timing } = await timeAsync(async () => {
93
- * // Some expensive async operation
94
- * const data = await fetchData();
95
- * return processData(data);
96
- * }, { label: 'API Request', log: true });
97
- *
98
- * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);
99
- * ```
100
- */
101
- export async function timeAsync(fn, options = {}) {
102
- const { label = fn.name || 'anonymous async function', log = false, logLevel = 'debug' } = options;
103
- const startTime = performance.now();
104
- const result = await fn();
105
- const endTime = performance.now();
106
- const durationMs = endTime - startTime;
107
- const durationSec = durationMs / 1000;
108
- const timing = {
109
- durationMs,
110
- durationSec,
111
- startTime,
112
- endTime,
113
- label
114
- };
115
- if (log) {
116
- const logger = getLogger();
117
- const message = `${label} completed in ${durationMs.toFixed(2)}ms`;
118
- switch (logLevel) {
119
- case 'trace':
120
- logger.trace({ timing }, message);
121
- break;
122
- case 'debug':
123
- logger.debug({ timing }, message);
124
- break;
125
- case 'info':
126
- logger.info({ timing }, message);
127
- break;
128
- case 'warn':
129
- logger.warn({ timing }, message);
130
- break;
131
- case 'error':
132
- logger.error({ timing }, message);
133
- break;
134
- default:
135
- logger.debug({ timing }, message);
136
- break;
137
- }
138
- }
139
- return { result, timing };
140
- }
141
- /**
142
- * Create a timing decorator for class methods.
143
- *
144
- * @param options - Timing options
145
- * @returns Method decorator
146
- *
147
- * @example
148
- * ```typescript
149
- * class DataService {
150
- * @timed({ log: true, logLevel: 'info' })
151
- * async fetchData() {
152
- * // ...implementation
153
- * }
154
- * }
155
- * ```
156
- */
157
- export function timed(options = {}) {
158
- return function (target, propertyKeyOrContext, descriptor) {
159
- let propertyKey;
160
- let actualDescriptor;
161
- // ESNext decorator: second argument is context object
162
- if (typeof propertyKeyOrContext === 'object' && propertyKeyOrContext !== null && 'name' in propertyKeyOrContext) {
163
- propertyKey = propertyKeyOrContext.name;
164
- actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey);
165
- }
166
- else {
167
- // Legacy decorator: second argument is property key
168
- propertyKey = propertyKeyOrContext;
169
- actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey);
170
- }
171
- const originalMethod = actualDescriptor.value;
172
- actualDescriptor.value = function (...args) {
173
- const methodOptions = {
174
- ...options,
175
- label: options.label || `${target.constructor.name}.${String(propertyKey)}`
176
- };
177
- if (originalMethod.constructor.name === 'AsyncFunction') {
178
- return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);
179
- }
180
- else {
181
- return timeSync(() => originalMethod.apply(this, args), methodOptions).result;
182
- }
183
- };
184
- // For legacy decorators, assign the new descriptor
185
- if (descriptor) {
186
- descriptor.value = actualDescriptor.value;
187
- }
188
- else {
189
- Object.defineProperty(target, propertyKey, actualDescriptor);
190
- }
191
- // No return needed for method decorators
192
- };
193
- }
194
- /**
195
- * Memoize function results with optional TTL and max cache size.
196
- *
197
- * @param fn - Function to memoize
198
- * @param options - Memoization options
199
- * @returns Memoized function
200
- *
201
- * @example
202
- * ```typescript
203
- * // Cache results for 30 seconds, with a maximum of 100 entries
204
- * const cachedFetch = memoize(
205
- * async (url) => {
206
- * const response = await fetch(url);
207
- * return response.json();
208
- * },
209
- * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }
210
- * );
211
- * ```
212
- */
213
- export function memoize(fn, options = {}) {
214
- const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;
215
- // Create a properly configured TTLCache instance
216
- const cache = new TTLCache({
217
- ttlMs: ttl,
218
- maxSize: maxSize,
219
- autoCleanupMs: autoCleanupMs
220
- });
221
- return function (...args) {
222
- const key = cacheKey(...args);
223
- // Try to get from cache first - TTLCache handles expiration internally
224
- const cachedValue = cache.get(key);
225
- if (cachedValue !== undefined) {
226
- return cachedValue;
227
- }
228
- // Calculate the value and store in cache with configured TTL
229
- const value = fn(...args);
230
- cache.set(key, value);
231
- return value;
232
- };
233
- }
234
- /**
235
- * Track memory usage for a function execution.
236
- *
237
- * @param fn - Function to track
238
- * @param options - Memory tracking options
239
- * @returns Result and memory usage information
240
- */
241
- export function trackMemoryUsage(fn, options = {}) {
242
- const { log = false, label = fn.name || 'anonymous function' } = options;
243
- // Collect garbage before measuring (optional)
244
- if (global.gc) {
245
- global.gc();
246
- }
247
- const beforeMemory = process.memoryUsage();
248
- const result = fn();
249
- const afterMemory = process.memoryUsage();
250
- // Calculate differences
251
- const diff = {};
252
- for (const key in afterMemory) {
253
- if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {
254
- diff[key] = afterMemory[key] - beforeMemory[key];
255
- }
256
- }
257
- if (log) {
258
- getLogger().info({
259
- label,
260
- memoryBefore: beforeMemory,
261
- memoryAfter: afterMemory,
262
- memoryDiff: diff
263
- }, `Memory usage for ${label}`);
264
- }
265
- return {
266
- result,
267
- memoryUsage: {
268
- before: beforeMemory,
269
- after: afterMemory,
270
- diff
271
- }
272
- };
273
- }
@@ -1,85 +0,0 @@
1
- import { Request } from 'express';
2
- import { WithPagination } from '../types/api-response';
3
- /**
4
- * Options for parsing and validating request parameters.
5
- */
6
- export interface ValidationOptions {
7
- /** Whether to throw an error on validation failure */
8
- throwOnError?: boolean;
9
- /** Custom error message for validation failures */
10
- errorMessage?: string;
11
- /** Default value to use if parameter is missing */
12
- defaultValue?: any;
13
- /** Whether the parameter is required */
14
- required?: boolean;
15
- }
16
- /**
17
- * Result of a parameter validation operation.
18
- */
19
- export interface ValidationResult<T> {
20
- /** Whether validation was successful */
21
- isValid: boolean;
22
- /** The validated and potentially transformed value */
23
- value: T | null;
24
- /** Error message if validation failed */
25
- error?: string;
26
- }
27
- /**
28
- * Extracts pagination, sorting, and optional search params from a request.
29
- *
30
- * @param req - Express request
31
- * @returns Object containing validated pagination, sorting, and additional query params
32
- */
33
- export declare const getPaginationParams: <T = {}>(req: Request) => WithPagination<T>;
34
- /**
35
- * Safely parses a string parameter to a number.
36
- *
37
- * @param value - String value to parse
38
- * @param options - Validation options
39
- * @returns Validation result containing the parsed number or error
40
- */
41
- export declare function parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>;
42
- /**
43
- * Safely parses a string parameter to a boolean.
44
- *
45
- * @param value - String value to parse
46
- * @param options - Validation options
47
- * @returns Validation result containing the parsed boolean or error
48
- */
49
- export declare function parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>;
50
- /**
51
- * Extracts pagination parameters from request query parameters.
52
- *
53
- * @param query - Query parameters object
54
- * @param defaultPage - Default page number if not specified (defaults to 1)
55
- * @param defaultLimit - Default per page size if not specified (defaults to 20)
56
- * @param maxLimitSize - Maximum allowed per page size (defaults to 100)
57
- * @returns Object containing validated page and limit
58
- */
59
- export declare function extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): {
60
- page: number;
61
- limit: number;
62
- };
63
- /**
64
- * Extracts sorting parameters from request query parameters.
65
- *
66
- * @param query - Query parameters object
67
- * @param allowedFields - Array of field names that are allowed to be sorted
68
- * @param defaultSort - Default sort configuration if not specified
69
- * @returns Object containing sort field and direction
70
- */
71
- export declare function extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?: {
72
- sortBy: string;
73
- sortOrder: 'asc' | 'desc';
74
- }): {
75
- sortBy: string;
76
- sortOrder: 'asc' | 'desc';
77
- };
78
- /**
79
- * Extracts filter parameters from query parameters based on allowed filter fields.
80
- *
81
- * @param query - Query parameters object
82
- * @param allowedFilters - Array of field names that are allowed to be used as filters
83
- * @returns Object containing the filters as key-value pairs
84
- */
85
- export declare function extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>;
@@ -1,190 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
24
- import { BadRequestException } from './exception.utils';
25
- /**
26
- * Extracts pagination, sorting, and optional search params from a request.
27
- *
28
- * @param req - Express request
29
- * @returns Object containing validated pagination, sorting, and additional query params
30
- */
31
- export const getPaginationParams = (req) => {
32
- const query = req.query;
33
- // Extract page & limit
34
- const { page, limit } = extractPaginationParams(query, 1, 20, 100);
35
- const { sortBy, sortOrder } = extractSortParams(query, []);
36
- // Optional search param
37
- const search = typeof query.search === 'string' ? query.search : undefined;
38
- return {
39
- ...query,
40
- page,
41
- limit,
42
- sortBy,
43
- sortOrder: sortOrder,
44
- search
45
- };
46
- };
47
- /**
48
- * Safely parses a string parameter to a number.
49
- *
50
- * @param value - String value to parse
51
- * @param options - Validation options
52
- * @returns Validation result containing the parsed number or error
53
- */
54
- export function parseNumberParam(value, options = {}) {
55
- const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;
56
- // Handle undefined case
57
- if (value === undefined) {
58
- if (required) {
59
- const error = `Required number parameter is missing`;
60
- if (throwOnError)
61
- throw new BadRequestException(error);
62
- return { isValid: false, value: null, error };
63
- }
64
- return {
65
- isValid: defaultValue !== undefined,
66
- value: defaultValue !== undefined ? defaultValue : null,
67
- error: defaultValue === undefined ? 'Missing parameter with no default' : undefined
68
- };
69
- }
70
- // Parse and validate the number
71
- const num = Number(value);
72
- if (isNaN(num)) {
73
- if (throwOnError)
74
- throw new BadRequestException(errorMessage);
75
- return { isValid: false, value: null, error: errorMessage };
76
- }
77
- return { isValid: true, value: num };
78
- }
79
- /**
80
- * Safely parses a string parameter to a boolean.
81
- *
82
- * @param value - String value to parse
83
- * @param options - Validation options
84
- * @returns Validation result containing the parsed boolean or error
85
- */
86
- export function parseBooleanParam(value, options = {}) {
87
- const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;
88
- // Handle undefined case
89
- if (value === undefined) {
90
- if (required) {
91
- const error = `Required boolean parameter is missing`;
92
- if (throwOnError)
93
- throw new BadRequestException(error);
94
- return { isValid: false, value: null, error };
95
- }
96
- return {
97
- isValid: defaultValue !== undefined,
98
- value: defaultValue !== undefined ? defaultValue : null,
99
- error: defaultValue === undefined ? 'Missing parameter with no default' : undefined
100
- };
101
- }
102
- // Parse the boolean value with various allowed formats
103
- const lowercaseValue = value.toLowerCase();
104
- if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {
105
- return { isValid: true, value: true };
106
- }
107
- if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {
108
- return { isValid: true, value: false };
109
- }
110
- if (throwOnError)
111
- throw new BadRequestException(errorMessage);
112
- return { isValid: false, value: null, error: errorMessage };
113
- }
114
- /**
115
- * Extracts pagination parameters from request query parameters.
116
- *
117
- * @param query - Query parameters object
118
- * @param defaultPage - Default page number if not specified (defaults to 1)
119
- * @param defaultLimit - Default per page size if not specified (defaults to 20)
120
- * @param maxLimitSize - Maximum allowed per page size (defaults to 100)
121
- * @returns Object containing validated page and limit
122
- */
123
- export function extractPaginationParams(query, defaultPage = 1, defaultLimit = 20, maxLimitSize = 100) {
124
- // Parse page parameter
125
- const pageParam = typeof query.page === 'string' ? query.page : undefined;
126
- const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });
127
- // Parse limit parameter
128
- const limitParam = typeof query.limit === 'string' ? query.limit : undefined;
129
- const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });
130
- // Ensure valid values (handle 0 → fallback to default)
131
- const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;
132
- const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;
133
- return { page, limit };
134
- }
135
- /**
136
- * Extracts sorting parameters from request query parameters.
137
- *
138
- * @param query - Query parameters object
139
- * @param allowedFields - Array of field names that are allowed to be sorted
140
- * @param defaultSort - Default sort configuration if not specified
141
- * @returns Object containing sort field and direction
142
- */
143
- export function extractSortParams(query, allowedFields, defaultSort = { sortBy: 'createdAt', sortOrder: 'desc' }) {
144
- let sortBy = defaultSort.sortBy;
145
- let sortOrder = defaultSort.sortOrder;
146
- // Extract from `sortBy` or `sort`
147
- if (typeof query.sortBy === 'string') {
148
- sortBy = query.sortBy;
149
- }
150
- else if (Array.isArray(query.sortBy)) {
151
- sortBy = query.sortBy[0];
152
- }
153
- else if (typeof query.sort === 'string') {
154
- sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;
155
- sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';
156
- }
157
- else if (Array.isArray(query.sort)) {
158
- sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];
159
- sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';
160
- }
161
- // Explicit sortOrder (overrides inferred one if valid)
162
- if (typeof query.sortOrder === 'string') {
163
- const order = query.sortOrder.toLowerCase();
164
- if (order === 'asc' || order === 'desc') {
165
- sortOrder = order;
166
- }
167
- }
168
- // Validate field
169
- if (allowedFields.length && !allowedFields.includes(sortBy)) {
170
- sortBy = defaultSort.sortBy;
171
- }
172
- return { sortBy, sortOrder };
173
- }
174
- /**
175
- * Extracts filter parameters from query parameters based on allowed filter fields.
176
- *
177
- * @param query - Query parameters object
178
- * @param allowedFilters - Array of field names that are allowed to be used as filters
179
- * @returns Object containing the filters as key-value pairs
180
- */
181
- export function extractFilterParams(query, allowedFilters) {
182
- const filters = {};
183
- // Find filter parameters in the query
184
- for (const field of allowedFilters) {
185
- if (field in query) {
186
- filters[field] = query[field];
187
- }
188
- }
189
- return filters;
190
- }