@catbee/utils 1.1.0 → 2.0.0-next.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 (90) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +79 -43
  3. package/array/index.cjs +355 -0
  4. package/array/index.d.ts +317 -0
  5. package/array/index.mjs +327 -0
  6. package/async/index.cjs +484 -0
  7. package/async/index.d.ts +299 -0
  8. package/async/index.mjs +463 -0
  9. package/cache/index.cjs +292 -0
  10. package/cache/index.d.ts +179 -0
  11. package/cache/index.mjs +290 -0
  12. package/config/index.cjs +150 -0
  13. package/config/index.d.ts +88 -0
  14. package/config/index.mjs +143 -0
  15. package/context-store/index.cjs +267 -0
  16. package/context-store/index.d.ts +216 -0
  17. package/context-store/index.mjs +261 -0
  18. package/crypto/index.cjs +182 -0
  19. package/crypto/index.d.ts +187 -0
  20. package/crypto/index.mjs +166 -0
  21. package/date/index.cjs +340 -0
  22. package/date/index.d.ts +214 -0
  23. package/date/index.mjs +326 -0
  24. package/decorators/index.cjs +2051 -0
  25. package/decorators/index.d.ts +708 -0
  26. package/decorators/index.mjs +2010 -0
  27. package/dir/index.cjs +417 -0
  28. package/dir/index.d.ts +219 -0
  29. package/dir/index.mjs +390 -0
  30. package/env/index.cjs +745 -0
  31. package/env/index.d.ts +403 -0
  32. package/env/index.mjs +742 -0
  33. package/exception/index.cjs +362 -0
  34. package/exception/index.d.ts +256 -0
  35. package/exception/index.mjs +338 -0
  36. package/fs/index.cjs +287 -0
  37. package/fs/index.d.ts +229 -0
  38. package/fs/index.mjs +258 -0
  39. package/http-status-codes/index.cjs +96 -0
  40. package/http-status-codes/index.d.ts +291 -0
  41. package/http-status-codes/index.mjs +94 -0
  42. package/id/index.cjs +62 -0
  43. package/id/index.d.ts +61 -0
  44. package/id/index.mjs +56 -0
  45. package/index.cjs +218 -0
  46. package/index.d.ts +51 -0
  47. package/index.mjs +51 -0
  48. package/logger/index.cjs +334 -0
  49. package/logger/index.d.ts +213 -0
  50. package/logger/index.mjs +313 -0
  51. package/middleware/index.cjs +177 -0
  52. package/middleware/index.d.ts +127 -0
  53. package/middleware/index.mjs +170 -0
  54. package/obj/index.cjs +305 -0
  55. package/obj/index.d.ts +160 -0
  56. package/obj/index.mjs +289 -0
  57. package/package.json +172 -20
  58. package/performance/index.cjs +231 -0
  59. package/performance/index.d.ts +162 -0
  60. package/performance/index.mjs +225 -0
  61. package/request/index.cjs +202 -0
  62. package/request/index.d.ts +265 -0
  63. package/request/index.mjs +194 -0
  64. package/response/index.cjs +234 -0
  65. package/response/index.d.ts +342 -0
  66. package/response/index.mjs +222 -0
  67. package/server/index.cjs +1631 -0
  68. package/server/index.d.ts +809 -0
  69. package/server/index.mjs +1622 -0
  70. package/stream/index.cjs +151 -0
  71. package/stream/index.d.ts +114 -0
  72. package/stream/index.mjs +144 -0
  73. package/string/index.cjs +109 -0
  74. package/string/index.d.ts +126 -0
  75. package/string/index.mjs +95 -0
  76. package/type/index.cjs +129 -0
  77. package/type/index.d.ts +131 -0
  78. package/type/index.mjs +119 -0
  79. package/types/index.cjs +34 -0
  80. package/types/index.d.ts +798 -0
  81. package/types/index.mjs +32 -0
  82. package/url/index.cjs +199 -0
  83. package/url/index.d.ts +166 -0
  84. package/url/index.mjs +187 -0
  85. package/validation/index.cjs +259 -0
  86. package/validation/index.d.ts +209 -0
  87. package/validation/index.mjs +231 -0
  88. package/build/index.cjs +0 -7694
  89. package/build/index.d.ts +0 -5792
  90. package/build/index.mjs +0 -7386
@@ -0,0 +1,202 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ 'use strict';
26
+
27
+ var exception = require('@catbee/utils/exception');
28
+
29
+ var __defProp = Object.defineProperty;
30
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
31
+ var getPaginationParams = /* @__PURE__ */ __name((req) => {
32
+ const query = req.query;
33
+ const { page, limit } = extractPaginationParams(query, 1, 20, 100);
34
+ const { sortBy, sortOrder } = extractSortParams(query, []);
35
+ const search = typeof query.search === "string" ? query.search : void 0;
36
+ return {
37
+ ...query,
38
+ page,
39
+ limit,
40
+ sortBy,
41
+ sortOrder,
42
+ search
43
+ };
44
+ }, "getPaginationParams");
45
+ function parseNumberParam(value, options = {}) {
46
+ const { throwOnError = false, errorMessage = "Invalid number parameter", defaultValue, required = false } = options;
47
+ if (value === void 0) {
48
+ if (required) {
49
+ const error = `Required number parameter is missing`;
50
+ if (throwOnError) throw new exception.BadRequestException(error);
51
+ return {
52
+ isValid: false,
53
+ value: null,
54
+ error
55
+ };
56
+ }
57
+ return {
58
+ isValid: defaultValue !== void 0,
59
+ value: defaultValue !== void 0 ? defaultValue : null,
60
+ error: defaultValue === void 0 ? "Missing parameter with no default" : void 0
61
+ };
62
+ }
63
+ const num = Number(value);
64
+ if (Number.isNaN(num)) {
65
+ if (throwOnError) throw new exception.BadRequestException(errorMessage);
66
+ return {
67
+ isValid: false,
68
+ value: null,
69
+ error: errorMessage
70
+ };
71
+ }
72
+ return {
73
+ isValid: true,
74
+ value: num
75
+ };
76
+ }
77
+ __name(parseNumberParam, "parseNumberParam");
78
+ function parseBooleanParam(value, options = {}) {
79
+ const { throwOnError = false, errorMessage = "Invalid boolean parameter", defaultValue, required = false } = options;
80
+ if (value === void 0) {
81
+ if (required) {
82
+ const error = `Required boolean parameter is missing`;
83
+ if (throwOnError) throw new exception.BadRequestException(error);
84
+ return {
85
+ isValid: false,
86
+ value: null,
87
+ error
88
+ };
89
+ }
90
+ return {
91
+ isValid: defaultValue !== void 0,
92
+ value: defaultValue !== void 0 ? defaultValue : null,
93
+ error: defaultValue === void 0 ? "Missing parameter with no default" : void 0
94
+ };
95
+ }
96
+ const lowercaseValue = value.toLowerCase();
97
+ if ([
98
+ "true",
99
+ "t",
100
+ "yes",
101
+ "y",
102
+ "1"
103
+ ].includes(lowercaseValue)) {
104
+ return {
105
+ isValid: true,
106
+ value: true
107
+ };
108
+ }
109
+ if ([
110
+ "false",
111
+ "f",
112
+ "no",
113
+ "n",
114
+ "0"
115
+ ].includes(lowercaseValue)) {
116
+ return {
117
+ isValid: true,
118
+ value: false
119
+ };
120
+ }
121
+ if (throwOnError) throw new exception.BadRequestException(errorMessage);
122
+ return {
123
+ isValid: false,
124
+ value: null,
125
+ error: errorMessage
126
+ };
127
+ }
128
+ __name(parseBooleanParam, "parseBooleanParam");
129
+ function extractPaginationParams(query, defaultPage = 1, defaultLimit = 20, maxLimitSize = 100) {
130
+ const pageParam = typeof query.page === "string" ? query.page : void 0;
131
+ const pageResult = parseNumberParam(pageParam, {
132
+ defaultValue: defaultPage
133
+ });
134
+ const limitParam = typeof query.limit === "string" ? query.limit : void 0;
135
+ const limitResult = parseNumberParam(limitParam, {
136
+ defaultValue: defaultLimit
137
+ });
138
+ const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;
139
+ const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;
140
+ return {
141
+ page,
142
+ limit
143
+ };
144
+ }
145
+ __name(extractPaginationParams, "extractPaginationParams");
146
+ function extractSortParams(query, allowedFields, defaultSort = {
147
+ sortBy: "createdAt",
148
+ sortOrder: "desc"
149
+ }) {
150
+ let sortBy = defaultSort.sortBy;
151
+ let sortOrder = defaultSort.sortOrder;
152
+ if (typeof query.sortBy === "string") {
153
+ sortBy = query.sortBy;
154
+ } else if (Array.isArray(query.sortBy)) {
155
+ sortBy = query.sortBy[0];
156
+ } else if (typeof query.sort === "string") {
157
+ sortBy = query.sort.startsWith("-") ? query.sort.slice(1) : query.sort;
158
+ sortOrder = query.sort.startsWith("-") ? "desc" : "asc";
159
+ } else if (Array.isArray(query.sort)) {
160
+ sortBy = query.sort[0].startsWith("-") ? query.sort[0].slice(1) : query.sort[0];
161
+ sortOrder = query.sort[0].startsWith("-") ? "desc" : "asc";
162
+ }
163
+ if (typeof query.sortOrder === "string") {
164
+ const order = query.sortOrder.toLowerCase();
165
+ if (order === "asc" || order === "desc") {
166
+ sortOrder = order;
167
+ }
168
+ }
169
+ if (allowedFields.length && !allowedFields.includes(sortBy)) {
170
+ sortBy = defaultSort.sortBy;
171
+ }
172
+ return {
173
+ sortBy,
174
+ sortOrder
175
+ };
176
+ }
177
+ __name(extractSortParams, "extractSortParams");
178
+ function extractFilterParams(query, allowedFilters) {
179
+ const filters = {};
180
+ for (const field of allowedFilters) {
181
+ if (field in query) {
182
+ filters[field] = query[field];
183
+ }
184
+ }
185
+ return filters;
186
+ }
187
+ __name(extractFilterParams, "extractFilterParams");
188
+
189
+ // src/types/api-response.ts
190
+ var SortDirection = /* @__PURE__ */ (function(SortDirection2) {
191
+ SortDirection2["ASC"] = "asc";
192
+ SortDirection2["DESC"] = "desc";
193
+ return SortDirection2;
194
+ })({});
195
+
196
+ exports.SortDirection = SortDirection;
197
+ exports.extractFilterParams = extractFilterParams;
198
+ exports.extractPaginationParams = extractPaginationParams;
199
+ exports.extractSortParams = extractSortParams;
200
+ exports.getPaginationParams = getPaginationParams;
201
+ exports.parseBooleanParam = parseBooleanParam;
202
+ exports.parseNumberParam = parseNumberParam;
@@ -0,0 +1,265 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { Request } from 'express';
26
+ import { WithPagination as WithPagination$1 } from '@catbee/utils/response';
27
+
28
+ /**
29
+ * Options for parsing and validating request parameters.
30
+ */
31
+ interface ValidationOptions {
32
+ /** Whether to throw an error on validation failure */
33
+ throwOnError?: boolean;
34
+ /** Custom error message for validation failures */
35
+ errorMessage?: string;
36
+ /** Default value to use if parameter is missing */
37
+ defaultValue?: any;
38
+ /** Whether the parameter is required */
39
+ required?: boolean;
40
+ }
41
+ /**
42
+ * Result of a parameter validation operation.
43
+ */
44
+ interface ValidationResult<T> {
45
+ /** Whether validation was successful */
46
+ isValid: boolean;
47
+ /** The validated and potentially transformed value */
48
+ value: T | null;
49
+ /** Error message if validation failed */
50
+ error?: string;
51
+ }
52
+ /**
53
+ * Extracts pagination, sorting, and optional search params from a request.
54
+ *
55
+ * @param req - Express request
56
+ * @returns Object containing validated pagination, sorting, and additional query params
57
+ */
58
+ declare const getPaginationParams: <T = {}>(req: Request) => WithPagination$1<T>;
59
+ /**
60
+ * Safely parses a string parameter to a number.
61
+ *
62
+ * @param value - String value to parse
63
+ * @param options - Validation options
64
+ * @returns Validation result containing the parsed number or error
65
+ */
66
+ declare function parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>;
67
+ /**
68
+ * Safely parses a string parameter to a boolean.
69
+ *
70
+ * @param value - String value to parse
71
+ * @param options - Validation options
72
+ * @returns Validation result containing the parsed boolean or error
73
+ */
74
+ declare function parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>;
75
+ /**
76
+ * Extracts pagination parameters from request query parameters.
77
+ *
78
+ * @param query - Query parameters object
79
+ * @param defaultPage - Default page number if not specified (defaults to 1)
80
+ * @param defaultLimit - Default per page size if not specified (defaults to 20)
81
+ * @param maxLimitSize - Maximum allowed per page size (defaults to 100)
82
+ * @returns Object containing validated page and limit
83
+ */
84
+ declare function extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): {
85
+ page: number;
86
+ limit: number;
87
+ };
88
+ /**
89
+ * Extracts sorting parameters from request query parameters.
90
+ *
91
+ * @param query - Query parameters object
92
+ * @param allowedFields - Array of field names that are allowed to be sorted
93
+ * @param defaultSort - Default sort configuration if not specified
94
+ * @returns Object containing sort field and direction
95
+ */
96
+ declare function extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?: {
97
+ sortBy: string;
98
+ sortOrder: 'asc' | 'desc';
99
+ }): {
100
+ sortBy: string;
101
+ sortOrder: 'asc' | 'desc';
102
+ };
103
+ /**
104
+ * Extracts filter parameters from query parameters based on allowed filter fields.
105
+ *
106
+ * @param query - Query parameters object
107
+ * @param allowedFilters - Array of field names that are allowed to be used as filters
108
+ * @returns Object containing the filters as key-value pairs
109
+ */
110
+ declare function extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>;
111
+
112
+ /**
113
+ * Generic API response format.
114
+ * Used to wrap any successful or failed response from the server.
115
+ */
116
+ interface ApiResponse<T = any> {
117
+ /** Payload returned from the API. Can be any shape depending on the endpoint. */
118
+ data: T | null;
119
+ /** Indicates whether an error occurred (true = error, false = success). */
120
+ error: boolean;
121
+ /** Success message describing the result of the operation. */
122
+ message: string;
123
+ /** Unique request ID for traceability in logs (e.g., from a middleware). */
124
+ requestId: string;
125
+ /** ISO timestamp when the response was generated. */
126
+ timestamp: string;
127
+ }
128
+ /**
129
+ * Generic pagination structure used for paged lists (e.g., /users?page=1).
130
+ */
131
+ interface Pagination<T = any> {
132
+ /** List of records for the current page. */
133
+ content: T[];
134
+ /** Metadata about the pagination state. */
135
+ pagination: {
136
+ /** Total number of records across all pages. */
137
+ totalRecords: number;
138
+ /** Total number of pages available. */
139
+ totalPages: number;
140
+ /** Current page number (1-based index). */
141
+ page: number;
142
+ /** Number of records per page. */
143
+ limit: number;
144
+ /** Field by which the data is sorted. */
145
+ sortBy: string;
146
+ /** Sort order: ascending or descending. */
147
+ sortOrder: 'asc' | 'desc';
148
+ };
149
+ }
150
+ /**
151
+ * Alias for paginated API response.
152
+ * Allows semantic naming like `PaginationResponse<User>` or `PaginationResponse<Post>`.
153
+ */
154
+ type PaginationResponse<T = any> = Pagination<T>;
155
+ /**
156
+ * Error response structure with additional metadata.
157
+ * Used for providing richer error information to clients.
158
+ */
159
+ interface ApiErrorResponse extends Omit<ApiResponse<never>, 'data'> {
160
+ /** Error always true for error responses */
161
+ error: true;
162
+ /** HTTP status code */
163
+ status: number;
164
+ /** Path to the resource that caused the error */
165
+ path: string;
166
+ /** Stack trace of the error (if available) */
167
+ stack?: string[];
168
+ }
169
+ /**
170
+ * Success response structure with strongly typed data.
171
+ * Used for providing successful responses to clients.
172
+ */
173
+ interface ApiSuccessResponse<T = any> extends ApiResponse<T> {
174
+ /** Error always false for success responses */
175
+ error: false;
176
+ /** HTTP status code (usually 200) */
177
+ status?: number;
178
+ }
179
+ /**
180
+ * Response structure for batch operations.
181
+ * Used when multiple operations are performed in a single request.
182
+ */
183
+ interface BatchResponse<T = any> {
184
+ /** Overall success/failure indicator */
185
+ success: boolean;
186
+ /** Total number of operations */
187
+ total: number;
188
+ /** Number of successful operations */
189
+ successful: number;
190
+ /** Number of failed operations */
191
+ failed: number;
192
+ /** Results of individual operations */
193
+ results: Array<{
194
+ /** Identifier for this operation */
195
+ id: string | number;
196
+ /** Success/failure indicator for this operation */
197
+ success: boolean;
198
+ /** Response data for this operation */
199
+ data?: T;
200
+ /** Error information if this operation failed */
201
+ error?: {
202
+ message: string;
203
+ code?: string;
204
+ };
205
+ }>;
206
+ }
207
+ /**
208
+ * Response structure for asynchronous operations.
209
+ * Used when the operation will complete in the future.
210
+ */
211
+ interface AsyncOperationResponse {
212
+ /** Always true for async operations */
213
+ async: true;
214
+ /** Job or task ID to check status later */
215
+ jobId: string;
216
+ /** Estimated completion time in seconds (if known) */
217
+ estimatedTime?: number;
218
+ /** URL to check status */
219
+ statusUrl: string;
220
+ }
221
+ /**
222
+ * Response structure for streaming operations.
223
+ * Used when data is returned as a stream rather than all at once.
224
+ */
225
+ interface StreamResponse {
226
+ /** Stream identifier */
227
+ streamId: string;
228
+ /** Stream type (e.g., 'json', 'binary') */
229
+ streamType: string;
230
+ /** Total size in bytes (if known) */
231
+ totalSize?: number;
232
+ /** Chunk size in bytes */
233
+ chunkSize: number;
234
+ }
235
+ /**
236
+ * Sort direction enumeration.
237
+ */
238
+ declare enum SortDirection {
239
+ /** Ascending sort order */
240
+ ASC = "asc",
241
+ /** Descending sort order */
242
+ DESC = "desc"
243
+ }
244
+ /**
245
+ * Pagination parameters for API requests.
246
+ */
247
+ interface PaginationParams {
248
+ /** Current page number (1-based index) */
249
+ page: number;
250
+ /** Number of records per page */
251
+ limit: number;
252
+ /** Field by which the data is sorted */
253
+ sortBy: string;
254
+ /** Sort order: ascending or descending */
255
+ sortOrder: SortDirection;
256
+ /** Optional search query */
257
+ search?: string;
258
+ }
259
+ /**
260
+ * Type that combines pagination parameters with additional data.
261
+ */
262
+ type WithPagination<T = {}> = PaginationParams & T;
263
+
264
+ export { SortDirection, extractFilterParams, extractPaginationParams, extractSortParams, getPaginationParams, parseBooleanParam, parseNumberParam };
265
+ export type { ApiErrorResponse, ApiResponse, ApiSuccessResponse, AsyncOperationResponse, BatchResponse, Pagination, PaginationParams, PaginationResponse, StreamResponse, ValidationOptions, ValidationResult, WithPagination };
@@ -0,0 +1,194 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { BadRequestException } from '@catbee/utils/exception';
26
+
27
+ var __defProp = Object.defineProperty;
28
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
29
+ var getPaginationParams = /* @__PURE__ */ __name((req) => {
30
+ const query = req.query;
31
+ const { page, limit } = extractPaginationParams(query, 1, 20, 100);
32
+ const { sortBy, sortOrder } = extractSortParams(query, []);
33
+ const search = typeof query.search === "string" ? query.search : void 0;
34
+ return {
35
+ ...query,
36
+ page,
37
+ limit,
38
+ sortBy,
39
+ sortOrder,
40
+ search
41
+ };
42
+ }, "getPaginationParams");
43
+ function parseNumberParam(value, options = {}) {
44
+ const { throwOnError = false, errorMessage = "Invalid number parameter", defaultValue, required = false } = options;
45
+ if (value === void 0) {
46
+ if (required) {
47
+ const error = `Required number parameter is missing`;
48
+ if (throwOnError) throw new BadRequestException(error);
49
+ return {
50
+ isValid: false,
51
+ value: null,
52
+ error
53
+ };
54
+ }
55
+ return {
56
+ isValid: defaultValue !== void 0,
57
+ value: defaultValue !== void 0 ? defaultValue : null,
58
+ error: defaultValue === void 0 ? "Missing parameter with no default" : void 0
59
+ };
60
+ }
61
+ const num = Number(value);
62
+ if (Number.isNaN(num)) {
63
+ if (throwOnError) throw new BadRequestException(errorMessage);
64
+ return {
65
+ isValid: false,
66
+ value: null,
67
+ error: errorMessage
68
+ };
69
+ }
70
+ return {
71
+ isValid: true,
72
+ value: num
73
+ };
74
+ }
75
+ __name(parseNumberParam, "parseNumberParam");
76
+ function parseBooleanParam(value, options = {}) {
77
+ const { throwOnError = false, errorMessage = "Invalid boolean parameter", defaultValue, required = false } = options;
78
+ if (value === void 0) {
79
+ if (required) {
80
+ const error = `Required boolean parameter is missing`;
81
+ if (throwOnError) throw new BadRequestException(error);
82
+ return {
83
+ isValid: false,
84
+ value: null,
85
+ error
86
+ };
87
+ }
88
+ return {
89
+ isValid: defaultValue !== void 0,
90
+ value: defaultValue !== void 0 ? defaultValue : null,
91
+ error: defaultValue === void 0 ? "Missing parameter with no default" : void 0
92
+ };
93
+ }
94
+ const lowercaseValue = value.toLowerCase();
95
+ if ([
96
+ "true",
97
+ "t",
98
+ "yes",
99
+ "y",
100
+ "1"
101
+ ].includes(lowercaseValue)) {
102
+ return {
103
+ isValid: true,
104
+ value: true
105
+ };
106
+ }
107
+ if ([
108
+ "false",
109
+ "f",
110
+ "no",
111
+ "n",
112
+ "0"
113
+ ].includes(lowercaseValue)) {
114
+ return {
115
+ isValid: true,
116
+ value: false
117
+ };
118
+ }
119
+ if (throwOnError) throw new BadRequestException(errorMessage);
120
+ return {
121
+ isValid: false,
122
+ value: null,
123
+ error: errorMessage
124
+ };
125
+ }
126
+ __name(parseBooleanParam, "parseBooleanParam");
127
+ function extractPaginationParams(query, defaultPage = 1, defaultLimit = 20, maxLimitSize = 100) {
128
+ const pageParam = typeof query.page === "string" ? query.page : void 0;
129
+ const pageResult = parseNumberParam(pageParam, {
130
+ defaultValue: defaultPage
131
+ });
132
+ const limitParam = typeof query.limit === "string" ? query.limit : void 0;
133
+ const limitResult = parseNumberParam(limitParam, {
134
+ defaultValue: defaultLimit
135
+ });
136
+ const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;
137
+ const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;
138
+ return {
139
+ page,
140
+ limit
141
+ };
142
+ }
143
+ __name(extractPaginationParams, "extractPaginationParams");
144
+ function extractSortParams(query, allowedFields, defaultSort = {
145
+ sortBy: "createdAt",
146
+ sortOrder: "desc"
147
+ }) {
148
+ let sortBy = defaultSort.sortBy;
149
+ let sortOrder = defaultSort.sortOrder;
150
+ if (typeof query.sortBy === "string") {
151
+ sortBy = query.sortBy;
152
+ } else if (Array.isArray(query.sortBy)) {
153
+ sortBy = query.sortBy[0];
154
+ } else if (typeof query.sort === "string") {
155
+ sortBy = query.sort.startsWith("-") ? query.sort.slice(1) : query.sort;
156
+ sortOrder = query.sort.startsWith("-") ? "desc" : "asc";
157
+ } else if (Array.isArray(query.sort)) {
158
+ sortBy = query.sort[0].startsWith("-") ? query.sort[0].slice(1) : query.sort[0];
159
+ sortOrder = query.sort[0].startsWith("-") ? "desc" : "asc";
160
+ }
161
+ if (typeof query.sortOrder === "string") {
162
+ const order = query.sortOrder.toLowerCase();
163
+ if (order === "asc" || order === "desc") {
164
+ sortOrder = order;
165
+ }
166
+ }
167
+ if (allowedFields.length && !allowedFields.includes(sortBy)) {
168
+ sortBy = defaultSort.sortBy;
169
+ }
170
+ return {
171
+ sortBy,
172
+ sortOrder
173
+ };
174
+ }
175
+ __name(extractSortParams, "extractSortParams");
176
+ function extractFilterParams(query, allowedFilters) {
177
+ const filters = {};
178
+ for (const field of allowedFilters) {
179
+ if (field in query) {
180
+ filters[field] = query[field];
181
+ }
182
+ }
183
+ return filters;
184
+ }
185
+ __name(extractFilterParams, "extractFilterParams");
186
+
187
+ // src/types/api-response.ts
188
+ var SortDirection = /* @__PURE__ */ (function(SortDirection2) {
189
+ SortDirection2["ASC"] = "asc";
190
+ SortDirection2["DESC"] = "desc";
191
+ return SortDirection2;
192
+ })({});
193
+
194
+ export { SortDirection, extractFilterParams, extractPaginationParams, extractSortParams, getPaginationParams, parseBooleanParam, parseNumberParam };