@catbee/utils 0.0.8-rc.3 → 1.0.1

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 (129) hide show
  1. package/README.md +3 -2
  2. package/build/index.cjs +6912 -0
  3. package/build/index.d.ts +5284 -0
  4. package/build/index.mjs +6635 -0
  5. package/package.json +13 -292
  6. package/build/cjs/config.d.ts +0 -121
  7. package/build/cjs/config.js +0 -137
  8. package/build/cjs/index.d.ts +0 -26
  9. package/build/cjs/index.js +0 -68
  10. package/build/cjs/servers/server.builder.d.ts +0 -507
  11. package/build/cjs/servers/server.builder.js +0 -658
  12. package/build/cjs/servers/server.d.ts +0 -255
  13. package/build/cjs/servers/server.js +0 -970
  14. package/build/cjs/types/api-response.d.ts +0 -151
  15. package/build/cjs/types/api-response.js +0 -36
  16. package/build/cjs/types/index.d.ts +0 -124
  17. package/build/cjs/types/index.js +0 -25
  18. package/build/cjs/types/server.d.ts +0 -267
  19. package/build/cjs/types/server.js +0 -25
  20. package/build/cjs/utils/array.utils.d.ts +0 -167
  21. package/build/cjs/utils/array.utils.js +0 -363
  22. package/build/cjs/utils/async.utils.d.ts +0 -264
  23. package/build/cjs/utils/async.utils.js +0 -640
  24. package/build/cjs/utils/cache.utils.d.ts +0 -152
  25. package/build/cjs/utils/cache.utils.js +0 -298
  26. package/build/cjs/utils/context-store.utils.d.ts +0 -188
  27. package/build/cjs/utils/context-store.utils.js +0 -297
  28. package/build/cjs/utils/crypto.utils.d.ts +0 -159
  29. package/build/cjs/utils/crypto.utils.js +0 -295
  30. package/build/cjs/utils/date.utils.d.ts +0 -158
  31. package/build/cjs/utils/date.utils.js +0 -395
  32. package/build/cjs/utils/decorators.utils.d.ts +0 -511
  33. package/build/cjs/utils/decorators.utils.js +0 -1035
  34. package/build/cjs/utils/dir.utils.d.ts +0 -195
  35. package/build/cjs/utils/dir.utils.js +0 -500
  36. package/build/cjs/utils/env.utils.d.ts +0 -376
  37. package/build/cjs/utils/env.utils.js +0 -786
  38. package/build/cjs/utils/exception.utils.d.ts +0 -229
  39. package/build/cjs/utils/exception.utils.js +0 -408
  40. package/build/cjs/utils/fs.utils.d.ts +0 -163
  41. package/build/cjs/utils/fs.utils.js +0 -371
  42. package/build/cjs/utils/http-status-codes.d.ts +0 -265
  43. package/build/cjs/utils/http-status-codes.js +0 -297
  44. package/build/cjs/utils/id.utils.d.ts +0 -35
  45. package/build/cjs/utils/id.utils.js +0 -90
  46. package/build/cjs/utils/logger.utils.d.ts +0 -159
  47. package/build/cjs/utils/logger.utils.js +0 -350
  48. package/build/cjs/utils/middleware.utils.d.ts +0 -99
  49. package/build/cjs/utils/middleware.utils.js +0 -243
  50. package/build/cjs/utils/obj.utils.d.ts +0 -123
  51. package/build/cjs/utils/obj.utils.js +0 -428
  52. package/build/cjs/utils/performance.utils.d.ts +0 -135
  53. package/build/cjs/utils/performance.utils.js +0 -280
  54. package/build/cjs/utils/request.utils.d.ts +0 -85
  55. package/build/cjs/utils/request.utils.js +0 -199
  56. package/build/cjs/utils/response.utils.d.ts +0 -162
  57. package/build/cjs/utils/response.utils.js +0 -274
  58. package/build/cjs/utils/stream.utils.d.ts +0 -87
  59. package/build/cjs/utils/stream.utils.js +0 -217
  60. package/build/cjs/utils/string.utils.d.ts +0 -92
  61. package/build/cjs/utils/string.utils.js +0 -178
  62. package/build/cjs/utils/type.utils.d.ts +0 -89
  63. package/build/cjs/utils/type.utils.js +0 -195
  64. package/build/cjs/utils/url.utils.d.ts +0 -140
  65. package/build/cjs/utils/url.utils.js +0 -316
  66. package/build/cjs/utils/validate.utils.d.ts +0 -176
  67. package/build/cjs/utils/validate.utils.js +0 -344
  68. package/build/esm/config.d.ts +0 -121
  69. package/build/esm/config.js +0 -132
  70. package/build/esm/index.d.ts +0 -26
  71. package/build/esm/index.js +0 -49
  72. package/build/esm/servers/server.builder.d.ts +0 -507
  73. package/build/esm/servers/server.builder.js +0 -654
  74. package/build/esm/servers/server.d.ts +0 -255
  75. package/build/esm/servers/server.js +0 -963
  76. package/build/esm/types/api-response.d.ts +0 -151
  77. package/build/esm/types/api-response.js +0 -33
  78. package/build/esm/types/index.d.ts +0 -124
  79. package/build/esm/types/index.js +0 -24
  80. package/build/esm/types/server.d.ts +0 -267
  81. package/build/esm/types/server.js +0 -24
  82. package/build/esm/utils/array.utils.d.ts +0 -167
  83. package/build/esm/utils/array.utils.js +0 -344
  84. package/build/esm/utils/async.utils.d.ts +0 -264
  85. package/build/esm/utils/async.utils.js +0 -619
  86. package/build/esm/utils/cache.utils.d.ts +0 -152
  87. package/build/esm/utils/cache.utils.js +0 -294
  88. package/build/esm/utils/context-store.utils.d.ts +0 -188
  89. package/build/esm/utils/context-store.utils.js +0 -290
  90. package/build/esm/utils/crypto.utils.d.ts +0 -159
  91. package/build/esm/utils/crypto.utils.js +0 -278
  92. package/build/esm/utils/date.utils.d.ts +0 -158
  93. package/build/esm/utils/date.utils.js +0 -383
  94. package/build/esm/utils/decorators.utils.d.ts +0 -511
  95. package/build/esm/utils/decorators.utils.js +0 -1013
  96. package/build/esm/utils/dir.utils.d.ts +0 -195
  97. package/build/esm/utils/dir.utils.js +0 -476
  98. package/build/esm/utils/env.utils.d.ts +0 -376
  99. package/build/esm/utils/env.utils.js +0 -782
  100. package/build/esm/utils/exception.utils.d.ts +0 -229
  101. package/build/esm/utils/exception.utils.js +0 -382
  102. package/build/esm/utils/fs.utils.d.ts +0 -163
  103. package/build/esm/utils/fs.utils.js +0 -348
  104. package/build/esm/utils/http-status-codes.d.ts +0 -265
  105. package/build/esm/utils/http-status-codes.js +0 -294
  106. package/build/esm/utils/id.utils.d.ts +0 -35
  107. package/build/esm/utils/id.utils.js +0 -83
  108. package/build/esm/utils/logger.utils.d.ts +0 -159
  109. package/build/esm/utils/logger.utils.js +0 -304
  110. package/build/esm/utils/middleware.utils.d.ts +0 -99
  111. package/build/esm/utils/middleware.utils.js +0 -235
  112. package/build/esm/utils/obj.utils.d.ts +0 -123
  113. package/build/esm/utils/obj.utils.js +0 -412
  114. package/build/esm/utils/performance.utils.d.ts +0 -135
  115. package/build/esm/utils/performance.utils.js +0 -273
  116. package/build/esm/utils/request.utils.d.ts +0 -85
  117. package/build/esm/utils/request.utils.js +0 -190
  118. package/build/esm/utils/response.utils.d.ts +0 -162
  119. package/build/esm/utils/response.utils.js +0 -261
  120. package/build/esm/utils/stream.utils.d.ts +0 -87
  121. package/build/esm/utils/stream.utils.js +0 -209
  122. package/build/esm/utils/string.utils.d.ts +0 -92
  123. package/build/esm/utils/string.utils.js +0 -164
  124. package/build/esm/utils/type.utils.d.ts +0 -89
  125. package/build/esm/utils/type.utils.js +0 -186
  126. package/build/esm/utils/url.utils.d.ts +0 -140
  127. package/build/esm/utils/url.utils.js +0 -303
  128. package/build/esm/utils/validate.utils.d.ts +0 -176
  129. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,280 +0,0 @@
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
- }
@@ -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,199 +0,0 @@
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
- }