@catbee/utils 0.0.6 → 0.0.7

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 (122) hide show
  1. package/README.md +51 -1106
  2. package/build/esm/config.d.ts +5 -13
  3. package/build/esm/config.js +0 -12
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/servers/server.builder.d.ts +1 -118
  6. package/build/esm/servers/server.builder.js +0 -20
  7. package/build/esm/servers/server.builder.js.map +1 -1
  8. package/build/esm/servers/server.d.ts +2 -2
  9. package/build/esm/servers/server.js +3 -13
  10. package/build/esm/servers/server.js.map +1 -1
  11. package/build/esm/types/api-response.d.ts +28 -0
  12. package/build/esm/types/api-response.js +10 -1
  13. package/build/esm/types/api-response.js.map +1 -1
  14. package/build/esm/types/server.d.ts +0 -17
  15. package/build/esm/types/server.js.map +1 -1
  16. package/build/esm/utils/async.utils.d.ts +91 -0
  17. package/build/esm/utils/async.utils.js +244 -0
  18. package/build/esm/utils/async.utils.js.map +1 -1
  19. package/build/esm/utils/context-store.utils.d.ts +3 -0
  20. package/build/esm/utils/context-store.utils.js +9 -6
  21. package/build/esm/utils/context-store.utils.js.map +1 -1
  22. package/build/esm/utils/date.utils.d.ts +159 -0
  23. package/build/esm/utils/date.utils.js +389 -0
  24. package/build/esm/utils/date.utils.js.map +1 -0
  25. package/build/esm/utils/logger.utils.d.ts +3 -9
  26. package/build/esm/utils/logger.utils.js +3 -9
  27. package/build/esm/utils/logger.utils.js.map +1 -1
  28. package/build/esm/utils/middleware.utils.js +2 -1
  29. package/build/esm/utils/middleware.utils.js.map +1 -1
  30. package/build/esm/utils/performance.utils.d.ts +136 -0
  31. package/build/esm/utils/performance.utils.js +376 -0
  32. package/build/esm/utils/performance.utils.js.map +1 -0
  33. package/build/esm/utils/request.utils.d.ts +9 -0
  34. package/build/esm/utils/request.utils.js +32 -5
  35. package/build/esm/utils/request.utils.js.map +1 -1
  36. package/build/esm/utils/stream.utils.d.ts +88 -0
  37. package/build/esm/utils/stream.utils.js +284 -0
  38. package/build/esm/utils/stream.utils.js.map +1 -0
  39. package/build/esm/utils/type.utils.d.ts +90 -0
  40. package/build/esm/utils/type.utils.js +190 -0
  41. package/build/esm/utils/type.utils.js.map +1 -0
  42. package/build/esnext/config.d.ts +5 -13
  43. package/build/esnext/config.js +0 -12
  44. package/build/esnext/config.js.map +1 -1
  45. package/build/esnext/servers/server.builder.d.ts +1 -118
  46. package/build/esnext/servers/server.builder.js +0 -20
  47. package/build/esnext/servers/server.builder.js.map +1 -1
  48. package/build/esnext/servers/server.d.ts +2 -2
  49. package/build/esnext/servers/server.js +3 -13
  50. package/build/esnext/servers/server.js.map +1 -1
  51. package/build/esnext/types/api-response.d.ts +28 -0
  52. package/build/esnext/types/api-response.js +10 -1
  53. package/build/esnext/types/api-response.js.map +1 -1
  54. package/build/esnext/types/server.d.ts +0 -17
  55. package/build/esnext/types/server.js.map +1 -1
  56. package/build/esnext/utils/async.utils.d.ts +91 -0
  57. package/build/esnext/utils/async.utils.js +190 -0
  58. package/build/esnext/utils/async.utils.js.map +1 -1
  59. package/build/esnext/utils/context-store.utils.d.ts +3 -0
  60. package/build/esnext/utils/context-store.utils.js +9 -6
  61. package/build/esnext/utils/context-store.utils.js.map +1 -1
  62. package/build/esnext/utils/date.utils.d.ts +159 -0
  63. package/build/esnext/utils/date.utils.js +384 -0
  64. package/build/esnext/utils/date.utils.js.map +1 -0
  65. package/build/esnext/utils/logger.utils.d.ts +3 -9
  66. package/build/esnext/utils/logger.utils.js +3 -9
  67. package/build/esnext/utils/logger.utils.js.map +1 -1
  68. package/build/esnext/utils/middleware.utils.js +2 -1
  69. package/build/esnext/utils/middleware.utils.js.map +1 -1
  70. package/build/esnext/utils/performance.utils.d.ts +136 -0
  71. package/build/esnext/utils/performance.utils.js +271 -0
  72. package/build/esnext/utils/performance.utils.js.map +1 -0
  73. package/build/esnext/utils/request.utils.d.ts +9 -0
  74. package/build/esnext/utils/request.utils.js +23 -5
  75. package/build/esnext/utils/request.utils.js.map +1 -1
  76. package/build/esnext/utils/stream.utils.d.ts +88 -0
  77. package/build/esnext/utils/stream.utils.js +210 -0
  78. package/build/esnext/utils/stream.utils.js.map +1 -0
  79. package/build/esnext/utils/type.utils.d.ts +90 -0
  80. package/build/esnext/utils/type.utils.js +187 -0
  81. package/build/esnext/utils/type.utils.js.map +1 -0
  82. package/build/src/config.d.ts +5 -13
  83. package/build/src/config.js +0 -12
  84. package/build/src/config.js.map +1 -1
  85. package/build/src/servers/server.builder.d.ts +1 -118
  86. package/build/src/servers/server.builder.js +0 -20
  87. package/build/src/servers/server.builder.js.map +1 -1
  88. package/build/src/servers/server.d.ts +2 -2
  89. package/build/src/servers/server.js +2 -12
  90. package/build/src/servers/server.js.map +1 -1
  91. package/build/src/types/api-response.d.ts +28 -0
  92. package/build/src/types/api-response.js +11 -0
  93. package/build/src/types/api-response.js.map +1 -1
  94. package/build/src/types/server.d.ts +0 -17
  95. package/build/src/types/server.js.map +1 -1
  96. package/build/src/utils/async.utils.d.ts +91 -0
  97. package/build/src/utils/async.utils.js +194 -0
  98. package/build/src/utils/async.utils.js.map +1 -1
  99. package/build/src/utils/context-store.utils.d.ts +3 -0
  100. package/build/src/utils/context-store.utils.js +9 -6
  101. package/build/src/utils/context-store.utils.js.map +1 -1
  102. package/build/src/utils/date.utils.d.ts +159 -0
  103. package/build/src/utils/date.utils.js +396 -0
  104. package/build/src/utils/date.utils.js.map +1 -0
  105. package/build/src/utils/logger.utils.d.ts +3 -9
  106. package/build/src/utils/logger.utils.js +4 -10
  107. package/build/src/utils/logger.utils.js.map +1 -1
  108. package/build/src/utils/middleware.utils.js +2 -1
  109. package/build/src/utils/middleware.utils.js.map +1 -1
  110. package/build/src/utils/performance.utils.d.ts +136 -0
  111. package/build/src/utils/performance.utils.js +278 -0
  112. package/build/src/utils/performance.utils.js.map +1 -0
  113. package/build/src/utils/request.utils.d.ts +9 -0
  114. package/build/src/utils/request.utils.js +25 -5
  115. package/build/src/utils/request.utils.js.map +1 -1
  116. package/build/src/utils/stream.utils.d.ts +88 -0
  117. package/build/src/utils/stream.utils.js +218 -0
  118. package/build/src/utils/stream.utils.js.map +1 -0
  119. package/build/src/utils/type.utils.d.ts +90 -0
  120. package/build/src/utils/type.utils.js +196 -0
  121. package/build/src/utils/type.utils.js.map +1 -0
  122. package/package.json +6 -2
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Options for timing function execution.
3
+ */
4
+ export interface TimingOptions {
5
+ /** Optional label for the timing (defaults to function name) */
6
+ label?: string;
7
+ /** Whether to log the timing (default: false) */
8
+ log?: boolean;
9
+ /** Log level to use if logging is enabled (default: 'debug') */
10
+ logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';
11
+ }
12
+ /**
13
+ * Result of a timing operation.
14
+ */
15
+ export interface TimingResult {
16
+ /** Duration in milliseconds */
17
+ durationMs: number;
18
+ /** Duration in seconds */
19
+ durationSec: number;
20
+ /** Start timestamp */
21
+ startTime: number;
22
+ /** End timestamp */
23
+ endTime: number;
24
+ /** Label used for the timing */
25
+ label: string;
26
+ }
27
+ /**
28
+ * Measure the execution time of a synchronous function.
29
+ *
30
+ * @param fn - Function to measure
31
+ * @param options - Timing options
32
+ * @returns Result containing the return value and timing information
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * const { result, timing } = timeSync(() => {
37
+ * // Some expensive operation
38
+ * return computeResult();
39
+ * }, { label: 'Computation', log: true });
40
+ *
41
+ * console.log(`Result: ${result}, took ${timing.durationMs}ms`);
42
+ * ```
43
+ */
44
+ export declare function timeSync<T>(fn: () => T, options?: TimingOptions): {
45
+ result: T;
46
+ timing: TimingResult;
47
+ };
48
+ /**
49
+ * Measure the execution time of an asynchronous function.
50
+ *
51
+ * @param fn - Async function to measure
52
+ * @param options - Timing options
53
+ * @returns Promise resolving to result and timing information
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * const { result, timing } = await timeAsync(async () => {
58
+ * // Some expensive async operation
59
+ * const data = await fetchData();
60
+ * return processData(data);
61
+ * }, { label: 'API Request', log: true });
62
+ *
63
+ * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);
64
+ * ```
65
+ */
66
+ export declare function timeAsync<T>(fn: () => Promise<T>, options?: TimingOptions): Promise<{
67
+ result: T;
68
+ timing: TimingResult;
69
+ }>;
70
+ /**
71
+ * Create a timing decorator for class methods.
72
+ *
73
+ * @param options - Timing options
74
+ * @returns Method decorator
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * class DataService {
79
+ * @timed({ log: true, logLevel: 'info' })
80
+ * async fetchData() {
81
+ * // ...implementation
82
+ * }
83
+ * }
84
+ * ```
85
+ */
86
+ export declare function timed(options?: TimingOptions): (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor) => void;
87
+ /**
88
+ * Memoize function results with optional TTL and max cache size.
89
+ *
90
+ * @param fn - Function to memoize
91
+ * @param options - Memoization options
92
+ * @returns Memoized function
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * // Cache results for 30 seconds, with a maximum of 100 entries
97
+ * const cachedFetch = memoize(
98
+ * async (url) => {
99
+ * const response = await fetch(url);
100
+ * return response.json();
101
+ * },
102
+ * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }
103
+ * );
104
+ * ```
105
+ */
106
+ export declare function memoize<T, Args extends any[]>(fn: (...args: Args) => T, options?: {
107
+ /** Time-to-live in milliseconds (default: indefinite) */
108
+ ttl?: number;
109
+ /** Maximum cache size (default: unlimited) */
110
+ maxSize?: number;
111
+ /** Function to generate a cache key from arguments */
112
+ cacheKey?: (...args: Args) => string;
113
+ /** Auto-cleanup interval in milliseconds (default: disabled) */
114
+ autoCleanupMs?: number;
115
+ }): (...args: Args) => T;
116
+ /**
117
+ * Track memory usage for a function execution.
118
+ *
119
+ * @param fn - Function to track
120
+ * @param options - Memory tracking options
121
+ * @returns Result and memory usage information
122
+ */
123
+ export declare function trackMemoryUsage<T>(fn: () => T, options?: {
124
+ /** Whether to log the memory usage (default: false) */
125
+ log?: boolean;
126
+ /** Label for the memory tracking (default: function name) */
127
+ label?: string;
128
+ }): {
129
+ result: T;
130
+ memoryUsage: {
131
+ before: NodeJS.MemoryUsage;
132
+ after: NodeJS.MemoryUsage;
133
+ diff: Record<string, number>;
134
+ };
135
+ };
136
+ //# sourceMappingURL=performance.utils.d.ts.map
@@ -0,0 +1,271 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
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 !== null && descriptor !== void 0 ? descriptor : Object.getOwnPropertyDescriptor(target, propertyKey);
165
+ }
166
+ else {
167
+ // Legacy decorator: second argument is property key
168
+ propertyKey = propertyKeyOrContext;
169
+ actualDescriptor = descriptor !== null && descriptor !== void 0 ? descriptor : Object.getOwnPropertyDescriptor(target, propertyKey);
170
+ }
171
+ const originalMethod = actualDescriptor.value;
172
+ actualDescriptor.value = function (...args) {
173
+ const methodOptions = Object.assign(Object.assign({}, options), { label: options.label || `${target.constructor.name}.${String(propertyKey)}` });
174
+ if (originalMethod.constructor.name === 'AsyncFunction') {
175
+ return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);
176
+ }
177
+ else {
178
+ return timeSync(() => originalMethod.apply(this, args), methodOptions).result;
179
+ }
180
+ };
181
+ // For legacy decorators, assign the new descriptor
182
+ if (descriptor) {
183
+ descriptor.value = actualDescriptor.value;
184
+ }
185
+ else {
186
+ Object.defineProperty(target, propertyKey, actualDescriptor);
187
+ }
188
+ // No return needed for method decorators
189
+ };
190
+ }
191
+ /**
192
+ * Memoize function results with optional TTL and max cache size.
193
+ *
194
+ * @param fn - Function to memoize
195
+ * @param options - Memoization options
196
+ * @returns Memoized function
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * // Cache results for 30 seconds, with a maximum of 100 entries
201
+ * const cachedFetch = memoize(
202
+ * async (url) => {
203
+ * const response = await fetch(url);
204
+ * return response.json();
205
+ * },
206
+ * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }
207
+ * );
208
+ * ```
209
+ */
210
+ export function memoize(fn, options = {}) {
211
+ const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;
212
+ // Create a properly configured TTLCache instance
213
+ const cache = new TTLCache({
214
+ ttlMs: ttl,
215
+ maxSize: maxSize,
216
+ autoCleanupMs: autoCleanupMs
217
+ });
218
+ return function (...args) {
219
+ const key = cacheKey(...args);
220
+ // Try to get from cache first - TTLCache handles expiration internally
221
+ const cachedValue = cache.get(key);
222
+ if (cachedValue !== undefined) {
223
+ return cachedValue;
224
+ }
225
+ // Calculate the value and store in cache with configured TTL
226
+ const value = fn(...args);
227
+ cache.set(key, value);
228
+ return value;
229
+ };
230
+ }
231
+ /**
232
+ * Track memory usage for a function execution.
233
+ *
234
+ * @param fn - Function to track
235
+ * @param options - Memory tracking options
236
+ * @returns Result and memory usage information
237
+ */
238
+ export function trackMemoryUsage(fn, options = {}) {
239
+ const { log = false, label = fn.name || 'anonymous function' } = options;
240
+ // Collect garbage before measuring (optional)
241
+ if (global.gc) {
242
+ global.gc();
243
+ }
244
+ const beforeMemory = process.memoryUsage();
245
+ const result = fn();
246
+ const afterMemory = process.memoryUsage();
247
+ // Calculate differences
248
+ const diff = {};
249
+ for (const key in afterMemory) {
250
+ if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {
251
+ diff[key] = afterMemory[key] - beforeMemory[key];
252
+ }
253
+ }
254
+ if (log) {
255
+ getLogger().info({
256
+ label,
257
+ memoryBefore: beforeMemory,
258
+ memoryAfter: afterMemory,
259
+ memoryDiff: diff
260
+ }, `Memory usage for ${label}`);
261
+ }
262
+ return {
263
+ result,
264
+ memoryUsage: {
265
+ before: beforeMemory,
266
+ after: afterMemory,
267
+ diff
268
+ }
269
+ };
270
+ }
271
+ //# sourceMappingURL=performance.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"performance.utils.js","sourceRoot":"","sources":["../../../src/utils/performance.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AA8B3C;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,QAAQ,CAAI,EAAW,EAAE,UAAyB,EAAE;IAClE,MAAM,EAAE,KAAK,GAAG,EAAE,CAAC,IAAI,IAAI,oBAAoB,EAAE,GAAG,GAAG,KAAK,EAAE,QAAQ,GAAG,OAAO,EAAE,GAAG,OAAO,CAAC;IAE7F,MAAM,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACpC,MAAM,MAAM,GAAG,EAAE,EAAE,CAAC;IACpB,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAElC,MAAM,UAAU,GAAG,OAAO,GAAG,SAAS,CAAC;IACvC,MAAM,WAAW,GAAG,UAAU,GAAG,IAAI,CAAC;IAEtC,MAAM,MAAM,GAAiB;QAC3B,UAAU;QACV,WAAW;QACX,SAAS;QACT,O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AE,KAAK,GAAG,EAAE,CAAC,IAAI,IAAI,oBAAoB,EAAE,GAAG,OAAO,CAAC;IAEzE,8CAA8C;IAC9C,IAAI,MAAM,CAAC,EAAE,EAAE,CAAC;QACd,MAAM,CAAC,EAAE,EAAE,CAAC;IACd,CAAC;IAED,MAAM,YAAY,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,MAAM,GAAG,EAAE,EAAE,CAAC;IACpB,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAE1C,wBAAwB;IACxB,MAAM,IAAI,GAA2B,EAAE,CAAC;IACxC,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QAC9B,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,CAAC;YAC3D,IAAI,CAAC,GAAG,CAAC,GAAI,WAAmB,CAAC,GAAG,CAAC,GAAI,YAAoB,CAAC,GAAG,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IAED,IAAI,GAAG,EAAE,CAAC;QACR,SAAS,EAAE,CAAC,IAAI,CACd;YACE,KAAK;YACL,YAAY,EAAE,YAAY;YAC1B,WAAW,EAAE,WAAW;YACxB,UAAU,EAAE,IAAI;SACjB,EACD,oBAAoB,KAAK,EAAE,CAC5B,CAAC;IACJ,CAAC;IAED,OAAO;QACL,MAAM;QACN,WAAW,EAAE;YACX,MAAM,EAAE,YAAY;YACpB,KAAK,EAAE,WAAW;YAClB,IAAI;SACL;KACF,CAAC;AACJ,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { TTLCache } from './cache.utils';\nimport { getLogger } from './logger.utils';\n\n/**\n * Options for timing function execution.\n */\nexport interface TimingOptions {\n /** Optional label for the timing (defaults to function name) */\n label?: string;\n /** Whether to log the timing (default: false) */\n log?: boolean;\n /** Log level to use if logging is enabled (default: 'debug') */\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * Result of a timing operation.\n */\nexport interface TimingResult {\n /** Duration in milliseconds */\n durationMs: number;\n /** Duration in seconds */\n durationSec: number;\n /** Start timestamp */\n startTime: number;\n /** End timestamp */\n endTime: number;\n /** Label used for the timing */\n label: string;\n}\n\n/**\n * Measure the execution time of a synchronous function.\n *\n * @param fn - Function to measure\n * @param options - Timing options\n * @returns Result containing the return value and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = timeSync(() => {\n * // Some expensive operation\n * return computeResult();\n * }, { label: 'Computation', log: true });\n *\n * console.log(`Result: ${result}, took ${timing.durationMs}ms`);\n * ```\n */\nexport function timeSync<T>(fn: () => T, options: TimingOptions = {}): { result: T; timing: TimingResult } {\n const { label = fn.name || 'anonymous function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Measure the execution time of an asynchronous function.\n *\n * @param fn - Async function to measure\n * @param options - Timing options\n * @returns Promise resolving to result and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = await timeAsync(async () => {\n * // Some expensive async operation\n * const data = await fetchData();\n * return processData(data);\n * }, { label: 'API Request', log: true });\n *\n * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);\n * ```\n */\nexport async function timeAsync<T>(\n fn: () => Promise<T>,\n options: TimingOptions = {}\n): Promise<{ result: T; timing: TimingResult }> {\n const { label = fn.name || 'anonymous async function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = await fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Create a timing decorator for class methods.\n *\n * @param options - Timing options\n * @returns Method decorator\n *\n * @example\n * ```typescript\n * class DataService {\n * @timed({ log: true, logLevel: 'info' })\n * async fetchData() {\n * // ...implementation\n * }\n * }\n * ```\n */\nexport function timed(options: TimingOptions = {}) {\n return function (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor): void {\n let propertyKey: string | symbol;\n let actualDescriptor: PropertyDescriptor;\n\n // ESNext decorator: second argument is context object\n if (typeof propertyKeyOrContext === 'object' && propertyKeyOrContext !== null && 'name' in propertyKeyOrContext) {\n propertyKey = propertyKeyOrContext.name;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n } else {\n // Legacy decorator: second argument is property key\n propertyKey = propertyKeyOrContext;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n }\n\n const originalMethod = actualDescriptor.value;\n\n actualDescriptor.value = function (...args: any[]) {\n const methodOptions = {\n ...options,\n label: options.label || `${target.constructor.name}.${String(propertyKey)}`\n };\n\n if (originalMethod.constructor.name === 'AsyncFunction') {\n return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);\n } else {\n return timeSync(() => originalMethod.apply(this, args), methodOptions).result;\n }\n };\n\n // For legacy decorators, assign the new descriptor\n if (descriptor) {\n descriptor.value = actualDescriptor.value;\n } else {\n Object.defineProperty(target, propertyKey, actualDescriptor);\n }\n // No return needed for method decorators\n };\n}\n\n/**\n * Memoize function results with optional TTL and max cache size.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized function\n *\n * @example\n * ```typescript\n * // Cache results for 30 seconds, with a maximum of 100 entries\n * const cachedFetch = memoize(\n * async (url) => {\n * const response = await fetch(url);\n * return response.json();\n * },\n * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }\n * );\n * ```\n */\nexport function memoize<T, Args extends any[]>(\n fn: (...args: Args) => T,\n options: {\n /** Time-to-live in milliseconds (default: indefinite) */\n ttl?: number;\n /** Maximum cache size (default: unlimited) */\n maxSize?: number;\n /** Function to generate a cache key from arguments */\n cacheKey?: (...args: Args) => string;\n /** Auto-cleanup interval in milliseconds (default: disabled) */\n autoCleanupMs?: number;\n } = {}\n) {\n const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;\n\n // Create a properly configured TTLCache instance\n const cache = new TTLCache<string, T>({\n ttlMs: ttl,\n maxSize: maxSize,\n autoCleanupMs: autoCleanupMs\n });\n\n return function (...args: Args): T {\n const key = cacheKey(...args);\n\n // Try to get from cache first - TTLCache handles expiration internally\n const cachedValue = cache.get(key);\n if (cachedValue !== undefined) {\n return cachedValue;\n }\n\n // Calculate the value and store in cache with configured TTL\n const value = fn(...args);\n cache.set(key, value);\n return value;\n };\n}\n\n/**\n * Track memory usage for a function execution.\n *\n * @param fn - Function to track\n * @param options - Memory tracking options\n * @returns Result and memory usage information\n */\nexport function trackMemoryUsage<T>(\n fn: () => T,\n options: {\n /** Whether to log the memory usage (default: false) */\n log?: boolean;\n /** Label for the memory tracking (default: function name) */\n label?: string;\n } = {}\n): { result: T; memoryUsage: { before: NodeJS.MemoryUsage; after: NodeJS.MemoryUsage; diff: Record<string, number> } } {\n const { log = false, label = fn.name || 'anonymous function' } = options;\n\n // Collect garbage before measuring (optional)\n if (global.gc) {\n global.gc();\n }\n\n const beforeMemory = process.memoryUsage();\n const result = fn();\n const afterMemory = process.memoryUsage();\n\n // Calculate differences\n const diff: Record<string, number> = {};\n for (const key in afterMemory) {\n if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {\n diff[key] = (afterMemory as any)[key] - (beforeMemory as any)[key];\n }\n }\n\n if (log) {\n getLogger().info(\n {\n label,\n memoryBefore: beforeMemory,\n memoryAfter: afterMemory,\n memoryDiff: diff\n },\n `Memory usage for ${label}`\n );\n }\n\n return {\n result,\n memoryUsage: {\n before: beforeMemory,\n after: afterMemory,\n diff\n }\n };\n}\n"]}
@@ -1,3 +1,5 @@
1
+ import { Request } from 'express';
2
+ import { WithPagination } from '../types/api-response';
1
3
  /**
2
4
  * Options for parsing and validating request parameters.
3
5
  */
@@ -22,6 +24,13 @@ export interface ValidationResult<T> {
22
24
  /** Error message if validation failed */
23
25
  error?: string;
24
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>;
25
34
  /**
26
35
  * Safely parses a string parameter to a number.
27
36
  *
@@ -21,6 +21,24 @@
21
21
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
22
  * SOFTWARE.
23
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 Object.assign(Object.assign({}, query), { page,
39
+ limit,
40
+ sortBy, sortOrder: sortOrder, search });
41
+ };
24
42
  /**
25
43
  * Safely parses a string parameter to a number.
26
44
  *
@@ -35,7 +53,7 @@ export function parseNumberParam(value, options = {}) {
35
53
  if (required) {
36
54
  const error = `Required number parameter is missing`;
37
55
  if (throwOnError)
38
- throw new Error(error);
56
+ throw new BadRequestException(error);
39
57
  return { isValid: false, value: null, error };
40
58
  }
41
59
  return {
@@ -48,7 +66,7 @@ export function parseNumberParam(value, options = {}) {
48
66
  const num = Number(value);
49
67
  if (isNaN(num)) {
50
68
  if (throwOnError)
51
- throw new Error(errorMessage);
69
+ throw new BadRequestException(errorMessage);
52
70
  return { isValid: false, value: null, error: errorMessage };
53
71
  }
54
72
  return { isValid: true, value: num };
@@ -67,7 +85,7 @@ export function parseBooleanParam(value, options = {}) {
67
85
  if (required) {
68
86
  const error = `Required boolean parameter is missing`;
69
87
  if (throwOnError)
70
- throw new Error(error);
88
+ throw new BadRequestException(error);
71
89
  return { isValid: false, value: null, error };
72
90
  }
73
91
  return {
@@ -85,7 +103,7 @@ export function parseBooleanParam(value, options = {}) {
85
103
  return { isValid: true, value: false };
86
104
  }
87
105
  if (throwOnError)
88
- throw new Error(errorMessage);
106
+ throw new BadRequestException(errorMessage);
89
107
  return { isValid: false, value: null, error: errorMessage };
90
108
  }
91
109
  /**
@@ -143,7 +161,7 @@ export function extractSortParams(query, allowedFields, defaultSort = { sortBy:
143
161
  }
144
162
  }
145
163
  // Validate field
146
- if (!allowedFields.includes(sortBy)) {
164
+ if (allowedFields.length && !allowedFields.includes(sortBy)) {
147
165
  sortBy = defaultSort.sortBy;
148
166
  }
149
167
  return { sortBy, sortOrder };
@@ -1 +1 @@
1
- {"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAiCH;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAyB,EAAE,UAA6B,EAAE;IACzF,MAAM,EAAE,YAAY,GAAG,KAAK,EAAE,YAAY,GAAG,0BAA0B,EAAE,YAAY,EAAE,QAAQ,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC;IAEpH,wBAAwB;IACxB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,KAAK,GAAG,sCAAsC,CAAC;YACrD,IAAI,YAAY;gBAAE,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;YACzC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;QAChD,CAAC;QAED,OAAO;YACL,OAAO,EAAE,YAAY,KAAK,SAAS;YACnC,KAAK,EAAE,YAA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AE,CAAC;YACnB,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Options for parsing and validating request parameters.\n */\nexport interface ValidationOptions {\n /** Whether to throw an error on validation failure */\n throwOnError?: boolean;\n\n /** Custom error message for validation failures */\n errorMessage?: string;\n\n /** Default value to use if parameter is missing */\n defaultValue?: any;\n\n /** Whether the parameter is required */\n required?: boolean;\n}\n\n/**\n * Result of a parameter validation operation.\n */\nexport interface ValidationResult<T> {\n /** Whether validation was successful */\n isValid: boolean;\n\n /** The validated and potentially transformed value */\n value: T | null;\n\n /** Error message if validation failed */\n error?: string;\n}\n\n/**\n * Safely parses a string parameter to a number.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed number or error\n */\nexport function parseNumberParam(value: string | undefined, options: ValidationOptions = {}): ValidationResult<number> {\n const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required number parameter is missing`;\n if (throwOnError) throw new Error(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse and validate the number\n const num = Number(value);\n if (isNaN(num)) {\n if (throwOnError) throw new Error(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n }\n\n return { isValid: true, value: num };\n}\n\n/**\n * Safely parses a string parameter to a boolean.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed boolean or error\n */\nexport function parseBooleanParam(\n value: string | undefined,\n options: ValidationOptions = {}\n): ValidationResult<boolean> {\n const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required boolean parameter is missing`;\n if (throwOnError) throw new Error(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse the boolean value with various allowed formats\n const lowercaseValue = value.toLowerCase();\n if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {\n return { isValid: true, value: true };\n }\n\n if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {\n return { isValid: true, value: false };\n }\n\n if (throwOnError) throw new Error(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n}\n\n/**\n * Extracts pagination parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param defaultPage - Default page number if not specified (defaults to 1)\n * @param defaultLimit - Default per page size if not specified (defaults to 20)\n * @param maxLimitSize - Maximum allowed per page size (defaults to 100)\n * @returns Object containing validated page and limit\n */\nexport function extractPaginationParams(\n query: Record<string, string | string[]>,\n defaultPage: number = 1,\n defaultLimit: number = 20,\n maxLimitSize: number = 100\n): { page: number; limit: number } {\n // Parse page parameter\n const pageParam = typeof query.page === 'string' ? query.page : undefined;\n const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });\n\n // Parse limit parameter\n const limitParam = typeof query.limit === 'string' ? query.limit : undefined;\n const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });\n\n // Ensure valid values (handle 0 → fallback to default)\n const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;\n\n const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;\n\n return { page, limit };\n}\n\n/**\n * Extracts sorting parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param allowedFields - Array of field names that are allowed to be sorted\n * @param defaultSort - Default sort configuration if not specified\n * @returns Object containing sort field and direction\n */\nexport function extractSortParams(\n query: Record<string, string | string[]>,\n allowedFields: string[],\n defaultSort: { sortBy: string; sortOrder: 'asc' | 'desc' } = { sortBy: 'createdAt', sortOrder: 'desc' }\n): { sortBy: string; sortOrder: 'asc' | 'desc' } {\n let sortBy = defaultSort.sortBy;\n let sortOrder: 'asc' | 'desc' = defaultSort.sortOrder;\n\n // Extract from `sortBy` or `sort`\n if (typeof query.sortBy === 'string') {\n sortBy = query.sortBy;\n } else if (Array.isArray(query.sortBy)) {\n sortBy = query.sortBy[0];\n } else if (typeof query.sort === 'string') {\n sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;\n sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';\n } else if (Array.isArray(query.sort)) {\n sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];\n sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';\n }\n\n // Explicit sortOrder (overrides inferred one if valid)\n if (typeof query.sortOrder === 'string') {\n const order = query.sortOrder.toLowerCase();\n if (order === 'asc' || order === 'desc') {\n sortOrder = order;\n }\n }\n\n // Validate field\n if (!allowedFields.includes(sortBy)) {\n sortBy = defaultSort.sortBy;\n }\n\n return { sortBy, sortOrder };\n}\n\n/**\n * Extracts filter parameters from query parameters based on allowed filter fields.\n *\n * @param query - Query parameters object\n * @param allowedFilters - Array of field names that are allowed to be used as filters\n * @returns Object containing the filters as key-value pairs\n */\nexport function extractFilterParams(\n query: Record<string, string | string[]>,\n allowedFilters: string[]\n): Record<string, string | string[]> {\n const filters: Record<string, string | string[]> = {};\n\n // Find filter parameters in the query\n for (const field of allowedFilters) {\n if (field in query) {\n filters[field] = query[field];\n }\n }\n\n return filters;\n}\n"]}
1
+ {"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAiCxD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAS,GAAY,EAAqB,EAAE;IAC7E,MAAM,KAAK,GAAG,GAAG,CAAC,KAA0C,CAAC;IAE7D,uBAAuB;IACvB,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,uBAAuB,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC;IACnE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,iBAAiB,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAE3D,wBAAwB;IACxB,MAAM,MAAM,GAAG,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;IAE3E,uCACM,KAAW,KACf,IAAI;QACJ,KAAK;QACL,MAAM,EACN,SAAS,EAAE,SAA0B,EACrC,MAAM,IACN;AACJ,CAAC,CAAC;AAEF;;;;;;GAMG;AACH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AAS,CAAC,WAAW,EAAE,CAAC;QAC5C,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;YACxC,SAAS,GAAG,KAAK,CAAC;QACpB,CAAC;IACH,CAAC;IAED,iBAAiB;IACjB,IAAI,aAAa,CAAC,MAAM,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAC5D,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AAC/B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CACjC,KAAwC,EACxC,cAAwB;IAExB,MAAM,OAAO,GAAsC,EAAE,CAAC;IAEtD,sCAAsC;IACtC,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE,CAAC;QACnC,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;YACnB,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Request } from 'express';\nimport { SortDirection, WithPagination } from '../types/api-response';\nimport { BadRequestException } from './exception.utils';\n\n/**\n * Options for parsing and validating request parameters.\n */\nexport interface ValidationOptions {\n /** Whether to throw an error on validation failure */\n throwOnError?: boolean;\n\n /** Custom error message for validation failures */\n errorMessage?: string;\n\n /** Default value to use if parameter is missing */\n defaultValue?: any;\n\n /** Whether the parameter is required */\n required?: boolean;\n}\n\n/**\n * Result of a parameter validation operation.\n */\nexport interface ValidationResult<T> {\n /** Whether validation was successful */\n isValid: boolean;\n\n /** The validated and potentially transformed value */\n value: T | null;\n\n /** Error message if validation failed */\n error?: string;\n}\n\n/**\n * Extracts pagination, sorting, and optional search params from a request.\n *\n * @param req - Express request\n * @returns Object containing validated pagination, sorting, and additional query params\n */\nexport const getPaginationParams = <T = {}>(req: Request): WithPagination<T> => {\n const query = req.query as Record<string, string | string[]>;\n\n // Extract page & limit\n const { page, limit } = extractPaginationParams(query, 1, 20, 100);\n const { sortBy, sortOrder } = extractSortParams(query, []);\n\n // Optional search param\n const search = typeof query.search === 'string' ? query.search : undefined;\n\n return {\n ...(query as T),\n page,\n limit,\n sortBy,\n sortOrder: sortOrder as SortDirection,\n search\n };\n};\n\n/**\n * Safely parses a string parameter to a number.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed number or error\n */\nexport function parseNumberParam(value: string | undefined, options: ValidationOptions = {}): ValidationResult<number> {\n const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required number parameter is missing`;\n if (throwOnError) throw new BadRequestException(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse and validate the number\n const num = Number(value);\n if (isNaN(num)) {\n if (throwOnError) throw new BadRequestException(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n }\n\n return { isValid: true, value: num };\n}\n\n/**\n * Safely parses a string parameter to a boolean.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed boolean or error\n */\nexport function parseBooleanParam(\n value: string | undefined,\n options: ValidationOptions = {}\n): ValidationResult<boolean> {\n const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required boolean parameter is missing`;\n if (throwOnError) throw new BadRequestException(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse the boolean value with various allowed formats\n const lowercaseValue = value.toLowerCase();\n if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {\n return { isValid: true, value: true };\n }\n\n if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {\n return { isValid: true, value: false };\n }\n\n if (throwOnError) throw new BadRequestException(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n}\n\n/**\n * Extracts pagination parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param defaultPage - Default page number if not specified (defaults to 1)\n * @param defaultLimit - Default per page size if not specified (defaults to 20)\n * @param maxLimitSize - Maximum allowed per page size (defaults to 100)\n * @returns Object containing validated page and limit\n */\nexport function extractPaginationParams(\n query: Record<string, string | string[]>,\n defaultPage: number = 1,\n defaultLimit: number = 20,\n maxLimitSize: number = 100\n): { page: number; limit: number } {\n // Parse page parameter\n const pageParam = typeof query.page === 'string' ? query.page : undefined;\n const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });\n\n // Parse limit parameter\n const limitParam = typeof query.limit === 'string' ? query.limit : undefined;\n const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });\n\n // Ensure valid values (handle 0 → fallback to default)\n const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;\n\n const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;\n\n return { page, limit };\n}\n\n/**\n * Extracts sorting parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param allowedFields - Array of field names that are allowed to be sorted\n * @param defaultSort - Default sort configuration if not specified\n * @returns Object containing sort field and direction\n */\nexport function extractSortParams(\n query: Record<string, string | string[]>,\n allowedFields: string[],\n defaultSort: { sortBy: string; sortOrder: 'asc' | 'desc' } = { sortBy: 'createdAt', sortOrder: 'desc' }\n): { sortBy: string; sortOrder: 'asc' | 'desc' } {\n let sortBy = defaultSort.sortBy;\n let sortOrder: 'asc' | 'desc' = defaultSort.sortOrder;\n\n // Extract from `sortBy` or `sort`\n if (typeof query.sortBy === 'string') {\n sortBy = query.sortBy;\n } else if (Array.isArray(query.sortBy)) {\n sortBy = query.sortBy[0];\n } else if (typeof query.sort === 'string') {\n sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;\n sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';\n } else if (Array.isArray(query.sort)) {\n sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];\n sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';\n }\n\n // Explicit sortOrder (overrides inferred one if valid)\n if (typeof query.sortOrder === 'string') {\n const order = query.sortOrder.toLowerCase();\n if (order === 'asc' || order === 'desc') {\n sortOrder = order;\n }\n }\n\n // Validate field\n if (allowedFields.length && !allowedFields.includes(sortBy)) {\n sortBy = defaultSort.sortBy;\n }\n\n return { sortBy, sortOrder };\n}\n\n/**\n * Extracts filter parameters from query parameters based on allowed filter fields.\n *\n * @param query - Query parameters object\n * @param allowedFilters - Array of field names that are allowed to be used as filters\n * @returns Object containing the filters as key-value pairs\n */\nexport function extractFilterParams(\n query: Record<string, string | string[]>,\n allowedFilters: string[]\n): Record<string, string | string[]> {\n const filters: Record<string, string | string[]> = {};\n\n // Find filter parameters in the query\n for (const field of allowedFilters) {\n if (field in query) {\n filters[field] = query[field];\n }\n }\n\n return filters;\n}\n"]}