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

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