@catbee/utils 0.0.4 → 0.0.6
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.
- package/LICENSE +21 -201
- package/README.md +911 -242
- package/build/esm/config.d.ts +108 -8
- package/build/esm/config.js +122 -6
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +6 -0
- package/build/esm/index.js +29 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/servers/server.builder.d.ts +625 -0
- package/build/esm/servers/server.builder.js +722 -0
- package/build/esm/servers/server.builder.js.map +1 -0
- package/build/esm/servers/server.d.ts +256 -0
- package/build/esm/servers/server.js +1211 -0
- package/build/esm/servers/server.js.map +1 -0
- package/build/esm/types/api-response.d.ts +5 -7
- package/build/esm/types/api-response.js +23 -0
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/types/index.d.ts +125 -0
- package/build/esm/types/index.js +25 -0
- package/build/esm/types/index.js.map +1 -0
- package/build/esm/types/server.d.ts +285 -0
- package/build/esm/types/server.js +25 -0
- package/build/esm/types/server.js.map +1 -0
- package/build/esm/utils/array.utils.js +23 -0
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.js +23 -0
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +39 -16
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +24 -1
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +26 -2
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +291 -0
- package/build/esm/utils/decorators.utils.js +395 -41
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.js +23 -0
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +186 -23
- package/build/esm/utils/env.utils.js +517 -91
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.js +31 -8
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.js +23 -0
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js +23 -0
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +23 -0
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +118 -0
- package/build/esm/utils/logger.utils.js +251 -15
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +29 -7
- package/build/esm/utils/middleware.utils.js +81 -55
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.d.ts +10 -3
- package/build/esm/utils/obj.utils.js +225 -15
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/request.utils.d.ts +77 -0
- package/build/esm/utils/request.utils.js +196 -0
- package/build/esm/utils/request.utils.js.map +1 -0
- package/build/esm/utils/response.utils.d.ts +15 -1
- package/build/esm/utils/response.utils.js +55 -4
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.js +23 -0
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.js +23 -0
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.d.ts +7 -0
- package/build/esm/utils/validate.utils.js +35 -2
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +108 -8
- package/build/esnext/config.js +122 -6
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +6 -0
- package/build/esnext/index.js +29 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/servers/server.builder.d.ts +625 -0
- package/build/esnext/servers/server.builder.js +677 -0
- package/build/esnext/servers/server.builder.js.map +1 -0
- package/build/esnext/servers/server.d.ts +256 -0
- package/build/esnext/servers/server.js +918 -0
- package/build/esnext/servers/server.js.map +1 -0
- package/build/esnext/types/api-response.d.ts +5 -7
- package/build/esnext/types/api-response.js +23 -0
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/types/index.d.ts +125 -0
- package/build/esnext/types/index.js +25 -0
- package/build/esnext/types/index.js.map +1 -0
- package/build/esnext/types/server.d.ts +285 -0
- package/build/esnext/types/server.js +25 -0
- package/build/esnext/types/server.js.map +1 -0
- package/build/esnext/utils/array.utils.js +23 -0
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.js +23 -0
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +39 -16
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +24 -1
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +26 -2
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +291 -0
- package/build/esnext/utils/decorators.utils.js +371 -22
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.js +23 -0
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +186 -23
- package/build/esnext/utils/env.utils.js +468 -77
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.js +30 -7
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.js +23 -0
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js +23 -0
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +23 -0
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +118 -0
- package/build/esnext/utils/logger.utils.js +222 -15
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +29 -7
- package/build/esnext/utils/middleware.utils.js +77 -55
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.d.ts +10 -3
- package/build/esnext/utils/obj.utils.js +176 -12
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/request.utils.d.ts +77 -0
- package/build/esnext/utils/request.utils.js +168 -0
- package/build/esnext/utils/request.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.d.ts +15 -1
- package/build/esnext/utils/response.utils.js +55 -4
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.js +23 -0
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.js +23 -0
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.d.ts +7 -0
- package/build/esnext/utils/validate.utils.js +33 -0
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +108 -8
- package/build/src/config.js +125 -7
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +6 -0
- package/build/src/index.js +32 -0
- package/build/src/index.js.map +1 -1
- package/build/src/servers/server.builder.d.ts +625 -0
- package/build/src/servers/server.builder.js +681 -0
- package/build/src/servers/server.builder.js.map +1 -0
- package/build/src/servers/server.d.ts +256 -0
- package/build/src/servers/server.js +958 -0
- package/build/src/servers/server.js.map +1 -0
- package/build/src/types/api-response.d.ts +5 -7
- package/build/src/types/api-response.js +23 -0
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/types/index.d.ts +125 -0
- package/build/src/types/index.js +26 -0
- package/build/src/types/index.js.map +1 -0
- package/build/src/types/server.d.ts +285 -0
- package/build/src/types/server.js +26 -0
- package/build/src/types/server.js.map +1 -0
- package/build/src/utils/array.utils.js +23 -0
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.js +23 -0
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +38 -15
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +24 -1
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +25 -1
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +291 -0
- package/build/src/utils/decorators.utils.js +373 -22
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.js +23 -0
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +186 -23
- package/build/src/utils/env.utils.js +467 -76
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.js +30 -7
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.js +23 -0
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js +23 -0
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +23 -0
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +118 -0
- package/build/src/utils/logger.utils.js +228 -15
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +29 -7
- package/build/src/utils/middleware.utils.js +76 -54
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.d.ts +10 -3
- package/build/src/utils/obj.utils.js +177 -12
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/request.utils.d.ts +77 -0
- package/build/src/utils/request.utils.js +175 -0
- package/build/src/utils/request.utils.js.map +1 -0
- package/build/src/utils/response.utils.d.ts +15 -1
- package/build/src/utils/response.utils.js +56 -4
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.js +23 -0
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.js +23 -0
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.d.ts +7 -0
- package/build/src/utils/validate.utils.js +36 -2
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +40 -9
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for parsing and validating request parameters.
|
|
3
|
+
*/
|
|
4
|
+
export interface ValidationOptions {
|
|
5
|
+
/** Whether to throw an error on validation failure */
|
|
6
|
+
throwOnError?: boolean;
|
|
7
|
+
/** Custom error message for validation failures */
|
|
8
|
+
errorMessage?: string;
|
|
9
|
+
/** Default value to use if parameter is missing */
|
|
10
|
+
defaultValue?: any;
|
|
11
|
+
/** Whether the parameter is required */
|
|
12
|
+
required?: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Result of a parameter validation operation.
|
|
16
|
+
*/
|
|
17
|
+
export interface ValidationResult<T> {
|
|
18
|
+
/** Whether validation was successful */
|
|
19
|
+
isValid: boolean;
|
|
20
|
+
/** The validated and potentially transformed value */
|
|
21
|
+
value: T | null;
|
|
22
|
+
/** Error message if validation failed */
|
|
23
|
+
error?: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Safely parses a string parameter to a number.
|
|
27
|
+
*
|
|
28
|
+
* @param value - String value to parse
|
|
29
|
+
* @param options - Validation options
|
|
30
|
+
* @returns Validation result containing the parsed number or error
|
|
31
|
+
*/
|
|
32
|
+
export declare function parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>;
|
|
33
|
+
/**
|
|
34
|
+
* Safely parses a string parameter to a boolean.
|
|
35
|
+
*
|
|
36
|
+
* @param value - String value to parse
|
|
37
|
+
* @param options - Validation options
|
|
38
|
+
* @returns Validation result containing the parsed boolean or error
|
|
39
|
+
*/
|
|
40
|
+
export declare function parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>;
|
|
41
|
+
/**
|
|
42
|
+
* Extracts pagination parameters from request query parameters.
|
|
43
|
+
*
|
|
44
|
+
* @param query - Query parameters object
|
|
45
|
+
* @param defaultPage - Default page number if not specified (defaults to 1)
|
|
46
|
+
* @param defaultLimit - Default per page size if not specified (defaults to 20)
|
|
47
|
+
* @param maxLimitSize - Maximum allowed per page size (defaults to 100)
|
|
48
|
+
* @returns Object containing validated page and limit
|
|
49
|
+
*/
|
|
50
|
+
export declare function extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): {
|
|
51
|
+
page: number;
|
|
52
|
+
limit: number;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Extracts sorting parameters from request query parameters.
|
|
56
|
+
*
|
|
57
|
+
* @param query - Query parameters object
|
|
58
|
+
* @param allowedFields - Array of field names that are allowed to be sorted
|
|
59
|
+
* @param defaultSort - Default sort configuration if not specified
|
|
60
|
+
* @returns Object containing sort field and direction
|
|
61
|
+
*/
|
|
62
|
+
export declare function extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?: {
|
|
63
|
+
sortBy: string;
|
|
64
|
+
sortOrder: 'asc' | 'desc';
|
|
65
|
+
}): {
|
|
66
|
+
sortBy: string;
|
|
67
|
+
sortOrder: 'asc' | 'desc';
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Extracts filter parameters from query parameters based on allowed filter fields.
|
|
71
|
+
*
|
|
72
|
+
* @param query - Query parameters object
|
|
73
|
+
* @param allowedFilters - Array of field names that are allowed to be used as filters
|
|
74
|
+
* @returns Object containing the filters as key-value pairs
|
|
75
|
+
*/
|
|
76
|
+
export declare function extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>;
|
|
77
|
+
//# sourceMappingURL=request.utils.d.ts.map
|
|
@@ -0,0 +1,168 @@
|
|
|
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
|
+
/**
|
|
25
|
+
* Safely parses a string parameter to a number.
|
|
26
|
+
*
|
|
27
|
+
* @param value - String value to parse
|
|
28
|
+
* @param options - Validation options
|
|
29
|
+
* @returns Validation result containing the parsed number or error
|
|
30
|
+
*/
|
|
31
|
+
export function parseNumberParam(value, options = {}) {
|
|
32
|
+
const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;
|
|
33
|
+
// Handle undefined case
|
|
34
|
+
if (value === undefined) {
|
|
35
|
+
if (required) {
|
|
36
|
+
const error = `Required number parameter is missing`;
|
|
37
|
+
if (throwOnError)
|
|
38
|
+
throw new Error(error);
|
|
39
|
+
return { isValid: false, value: null, error };
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
isValid: defaultValue !== undefined,
|
|
43
|
+
value: defaultValue !== undefined ? defaultValue : null,
|
|
44
|
+
error: defaultValue === undefined ? 'Missing parameter with no default' : undefined
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// Parse and validate the number
|
|
48
|
+
const num = Number(value);
|
|
49
|
+
if (isNaN(num)) {
|
|
50
|
+
if (throwOnError)
|
|
51
|
+
throw new Error(errorMessage);
|
|
52
|
+
return { isValid: false, value: null, error: errorMessage };
|
|
53
|
+
}
|
|
54
|
+
return { isValid: true, value: num };
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Safely parses a string parameter to a boolean.
|
|
58
|
+
*
|
|
59
|
+
* @param value - String value to parse
|
|
60
|
+
* @param options - Validation options
|
|
61
|
+
* @returns Validation result containing the parsed boolean or error
|
|
62
|
+
*/
|
|
63
|
+
export function parseBooleanParam(value, options = {}) {
|
|
64
|
+
const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;
|
|
65
|
+
// Handle undefined case
|
|
66
|
+
if (value === undefined) {
|
|
67
|
+
if (required) {
|
|
68
|
+
const error = `Required boolean parameter is missing`;
|
|
69
|
+
if (throwOnError)
|
|
70
|
+
throw new Error(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 the boolean value with various allowed formats
|
|
80
|
+
const lowercaseValue = value.toLowerCase();
|
|
81
|
+
if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {
|
|
82
|
+
return { isValid: true, value: true };
|
|
83
|
+
}
|
|
84
|
+
if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {
|
|
85
|
+
return { isValid: true, value: false };
|
|
86
|
+
}
|
|
87
|
+
if (throwOnError)
|
|
88
|
+
throw new Error(errorMessage);
|
|
89
|
+
return { isValid: false, value: null, error: errorMessage };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Extracts pagination parameters from request query parameters.
|
|
93
|
+
*
|
|
94
|
+
* @param query - Query parameters object
|
|
95
|
+
* @param defaultPage - Default page number if not specified (defaults to 1)
|
|
96
|
+
* @param defaultLimit - Default per page size if not specified (defaults to 20)
|
|
97
|
+
* @param maxLimitSize - Maximum allowed per page size (defaults to 100)
|
|
98
|
+
* @returns Object containing validated page and limit
|
|
99
|
+
*/
|
|
100
|
+
export function extractPaginationParams(query, defaultPage = 1, defaultLimit = 20, maxLimitSize = 100) {
|
|
101
|
+
// Parse page parameter
|
|
102
|
+
const pageParam = typeof query.page === 'string' ? query.page : undefined;
|
|
103
|
+
const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });
|
|
104
|
+
// Parse limit parameter
|
|
105
|
+
const limitParam = typeof query.limit === 'string' ? query.limit : undefined;
|
|
106
|
+
const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });
|
|
107
|
+
// Ensure valid values (handle 0 → fallback to default)
|
|
108
|
+
const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;
|
|
109
|
+
const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;
|
|
110
|
+
return { page, limit };
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Extracts sorting parameters from request query parameters.
|
|
114
|
+
*
|
|
115
|
+
* @param query - Query parameters object
|
|
116
|
+
* @param allowedFields - Array of field names that are allowed to be sorted
|
|
117
|
+
* @param defaultSort - Default sort configuration if not specified
|
|
118
|
+
* @returns Object containing sort field and direction
|
|
119
|
+
*/
|
|
120
|
+
export function extractSortParams(query, allowedFields, defaultSort = { sortBy: 'createdAt', sortOrder: 'desc' }) {
|
|
121
|
+
let sortBy = defaultSort.sortBy;
|
|
122
|
+
let sortOrder = defaultSort.sortOrder;
|
|
123
|
+
// Extract from `sortBy` or `sort`
|
|
124
|
+
if (typeof query.sortBy === 'string') {
|
|
125
|
+
sortBy = query.sortBy;
|
|
126
|
+
}
|
|
127
|
+
else if (Array.isArray(query.sortBy)) {
|
|
128
|
+
sortBy = query.sortBy[0];
|
|
129
|
+
}
|
|
130
|
+
else if (typeof query.sort === 'string') {
|
|
131
|
+
sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;
|
|
132
|
+
sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';
|
|
133
|
+
}
|
|
134
|
+
else if (Array.isArray(query.sort)) {
|
|
135
|
+
sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];
|
|
136
|
+
sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';
|
|
137
|
+
}
|
|
138
|
+
// Explicit sortOrder (overrides inferred one if valid)
|
|
139
|
+
if (typeof query.sortOrder === 'string') {
|
|
140
|
+
const order = query.sortOrder.toLowerCase();
|
|
141
|
+
if (order === 'asc' || order === 'desc') {
|
|
142
|
+
sortOrder = order;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// Validate field
|
|
146
|
+
if (!allowedFields.includes(sortBy)) {
|
|
147
|
+
sortBy = defaultSort.sortBy;
|
|
148
|
+
}
|
|
149
|
+
return { sortBy, sortOrder };
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Extracts filter parameters from query parameters based on allowed filter fields.
|
|
153
|
+
*
|
|
154
|
+
* @param query - Query parameters object
|
|
155
|
+
* @param allowedFilters - Array of field names that are allowed to be used as filters
|
|
156
|
+
* @returns Object containing the filters as key-value pairs
|
|
157
|
+
*/
|
|
158
|
+
export function extractFilterParams(query, allowedFilters) {
|
|
159
|
+
const filters = {};
|
|
160
|
+
// Find filter parameters in the query
|
|
161
|
+
for (const field of allowedFilters) {
|
|
162
|
+
if (field in query) {
|
|
163
|
+
filters[field] = query[field];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return filters;
|
|
167
|
+
}
|
|
168
|
+
//# sourceMappingURL=request.utils.js.map
|
|
@@ -0,0 +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,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI;YACvD,KAAK,EAAE,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,mCAAmC,CAAC,CAAC,CAAC,SAAS;SACpF,CAAC;IACJ,CAAC;IAED,gCAAgC;IAChC,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC1B,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACf,IAAI,YAAY;YAAE,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;QAChD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,CAAC;IAC9D,CAAC;IA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C,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;IAC7D,CAAC;IAED,uDAAuD;IACvD,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;QACxC,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,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,CAAC,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACpC,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\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,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Request } from 'express';
|
|
2
|
+
import { ApiErrorResponse, ApiResponse } from '../types/api-response';
|
|
2
3
|
/**
|
|
3
4
|
* Standard HTTP response wrapper for successful responses.
|
|
4
5
|
* Implements the `ApiResponse<T>` interface and sets default values.
|
|
@@ -128,6 +129,19 @@ export declare function createSuccessResponse<T>(data: T, message?: string): Suc
|
|
|
128
129
|
* @returns {ErrorResponse} A properly formatted error response.
|
|
129
130
|
*/
|
|
130
131
|
export declare function createErrorResponse(message: string, statusCode?: number): ErrorResponse;
|
|
132
|
+
/**
|
|
133
|
+
* Creates a final error response with request information.
|
|
134
|
+
*
|
|
135
|
+
* @param req - The original request object.
|
|
136
|
+
* @param status - The HTTP status code.
|
|
137
|
+
* @param message - The error message.
|
|
138
|
+
* @param error - The original error object (optional).
|
|
139
|
+
* @param options - Additional options for the response (optional).
|
|
140
|
+
* @returns A properly formatted final error response.
|
|
141
|
+
*/
|
|
142
|
+
export declare function createFinalErrorResponse(req: Request, status: number, message: string, error?: any, options?: {
|
|
143
|
+
includeDetails?: boolean;
|
|
144
|
+
}): ApiErrorResponse;
|
|
131
145
|
/**
|
|
132
146
|
* Creates a paginated response from array data.
|
|
133
147
|
*
|
|
@@ -1,5 +1,29 @@
|
|
|
1
|
-
|
|
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
|
+
*/
|
|
2
24
|
import { getRequestId } from './context-store.utils';
|
|
25
|
+
import { Env } from './env.utils';
|
|
26
|
+
import { uuid } from './id.utils';
|
|
3
27
|
/**
|
|
4
28
|
* Standard HTTP response wrapper for successful responses.
|
|
5
29
|
* Implements the `ApiResponse<T>` interface and sets default values.
|
|
@@ -24,7 +48,7 @@ export class SuccessResponse {
|
|
|
24
48
|
/** Timestamp when the response was generated, in ISO format. */
|
|
25
49
|
this.timestamp = new Date().toISOString();
|
|
26
50
|
/** Unique identifier for this response, useful for request tracing. */
|
|
27
|
-
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
51
|
+
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
28
52
|
if (message)
|
|
29
53
|
this.message = message;
|
|
30
54
|
this.data = data !== null && data !== void 0 ? data : null;
|
|
@@ -49,7 +73,7 @@ export class ErrorResponse extends Error {
|
|
|
49
73
|
/** Timestamp when the error occurred, in ISO format. */
|
|
50
74
|
this.timestamp = new Date().toISOString();
|
|
51
75
|
/** Unique identifier for this error instance. */
|
|
52
|
-
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
76
|
+
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
53
77
|
this.status = status;
|
|
54
78
|
this.name = this.constructor.name;
|
|
55
79
|
Error.captureStackTrace(this, this.constructor);
|
|
@@ -110,7 +134,7 @@ export class RedirectResponse {
|
|
|
110
134
|
/** Whether the response is a redirect */
|
|
111
135
|
this.isRedirect = true;
|
|
112
136
|
/** Unique identifier for this response */
|
|
113
|
-
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
137
|
+
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
114
138
|
this.redirectUrl = url;
|
|
115
139
|
this.statusCode = statusCode;
|
|
116
140
|
}
|
|
@@ -136,6 +160,33 @@ export function createSuccessResponse(data, message = 'Success') {
|
|
|
136
160
|
export function createErrorResponse(message, statusCode = 500) {
|
|
137
161
|
return new ErrorResponse(message, statusCode);
|
|
138
162
|
}
|
|
163
|
+
/**
|
|
164
|
+
* Creates a final error response with request information.
|
|
165
|
+
*
|
|
166
|
+
* @param req - The original request object.
|
|
167
|
+
* @param status - The HTTP status code.
|
|
168
|
+
* @param message - The error message.
|
|
169
|
+
* @param error - The original error object (optional).
|
|
170
|
+
* @param options - Additional options for the response (optional).
|
|
171
|
+
* @returns A properly formatted final error response.
|
|
172
|
+
*/
|
|
173
|
+
export function createFinalErrorResponse(req, status, message, error, options) {
|
|
174
|
+
const isDev = Env.isDev();
|
|
175
|
+
const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
|
|
176
|
+
const response = {
|
|
177
|
+
error: true,
|
|
178
|
+
message,
|
|
179
|
+
timestamp: new Date().toISOString(),
|
|
180
|
+
requestId: (error === null || error === void 0 ? void 0 : error.requestId) || (req === null || req === void 0 ? void 0 : req.id) || uuid(),
|
|
181
|
+
status,
|
|
182
|
+
path: req.originalUrl || req.url
|
|
183
|
+
};
|
|
184
|
+
// Include stack trace in development mode if requested
|
|
185
|
+
if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
|
|
186
|
+
response.stack = error.stack.split('\n').map((line) => line.trim());
|
|
187
|
+
}
|
|
188
|
+
return response;
|
|
189
|
+
}
|
|
139
190
|
/**
|
|
140
191
|
* Creates a paginated response from array data.
|
|
141
192
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response.utils.js","sourceRoot":"","sources":["../../../src/utils/response.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD;;;;;GAKG;AACH,MAAM,OAAO,eAAe;IAgB1B;;;;;OAKG;IACH,YAAY,OAAe,EAAE,IAAQ;;QArBrC,sDAAsD;QACtD,YAAO,GAAW,SAAS,CAAC;QAE5B,2EAA2E;QAC3E,UAAK,GAAY,KAAK,CAAC;QAEvB,yCAAyC;QACzC,SAAI,GAAa,IAAI,CAAC;QAEtB,gEAAgE;QAChE,cAAS,GAAW,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAE7C,uEAAuE;QACvE,cAAS,GAAW,MAAA,YAAY,EAAE,mCAAI,UAAU,EAAE,CAAC;QASjD,IAAI,OAAO;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACpC,IAAI,CAAC,IAAI,GAAG,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,IAAI,CAAC;IAC3B,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,aAAc,SAAQ,KAAK;IAatC;;;;;OAKG;IACH,YAAY,OAAe,EAAE,SAAiB,GAAG;;QAC/C,KAAK,CAAC,OAAO,CAAC,CAAC;QAhBjB,oDAAoD;QACpD,UAAK,GAAY,IAAI,CAAC;QAEtB,wDAAwD;QACxD,cAAS,GAAW,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAE7C,iDAAiD;QACjD,cAAS,GAAW,MAAA,YAAY,EAAE,mCAAI,U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,WAAW,CAAC,WAAW,CAAC,CAAC;QAC9D,OAAO;IACT,CAAC;IAED,gBAAgB;IAChB,IAAI,OAAO,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,EAAE,CAAC;QAChD,MAAM,aAAa,GAAG,WAA4B,CAAC;QACnD,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;YACpC,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,aAAa,CAAC,OAAO;YAC9B,SAAS,EAAE,aAAa,CAAC,SAAS;YAClC,SAAS,EAAE,aAAa,CAAC,SAAS;SACnC,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,2BAA2B;IAC3B,MAAM,eAAe,GAAG,WAAmC,CAAC;IAE5D,2CAA2C;IAC3C,IAAI,eAAe,YAAY,iBAAiB,EAAE,CAAC;QACjD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { randomUUID } from 'crypto';\nimport { ApiResponse } from '../types/api-response';\nimport { getRequestId } from './context-store.utils';\n\n/**\n * Standard HTTP response wrapper for successful responses.\n * Implements the `ApiResponse<T>` interface and sets default values.\n *\n * @typeParam T - The shape of the data returned in the response.\n */\nexport class SuccessResponse<T> implements ApiResponse<T> {\n /** Message describing the result of the operation. */\n message: string = 'Success';\n\n /** Whether the response is an error. Always false in success responses. */\n error: boolean = false;\n\n /** The payload returned from the API. */\n data: T | null = null;\n\n /** Timestamp when the response was generated, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this response, useful for request tracing. */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new success response.\n *\n * @param {string} message - Optional message to override the default.\n * @param {T} [data] - Optional data payload.\n */\n constructor(message: string, data?: T) {\n if (message) this.message = message;\n this.data = data ?? null;\n }\n}\n\n/**\n * Wrapper for error responses that extends the native `Error` object.\n * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).\n */\nexport class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {\n /** HTTP status code associated with the error (e.g., 404, 500). */\n status: number;\n\n /** Indicates that this is an error. Always true. */\n error: boolean = true;\n\n /** Timestamp when the error occurred, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this error instance. */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new error response.\n *\n * @param {string} message - The error message to display or log.\n * @param {number} [status=500] - Optional HTTP status code (defaults to 500).\n */\n constructor(message: string, status: number = 500) {\n super(message);\n this.status = status;\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Response with paginated data extending the standard success response.\n * Useful for APIs that return large collections of data.\n *\n * @typeParam T - The shape of each item in the paginated collection.\n */\nexport class PaginatedResponse<T> extends SuccessResponse<T[]> {\n /** Total number of items across all pages */\n total: number;\n\n /** Current page number (1-based) */\n page: number;\n\n /** Number of items per page */\n pageSize: number;\n\n /** Total number of pages */\n totalPages: number;\n\n /** Whether there's a next page available */\n hasNext: boolean;\n\n /** Whether there's a previous page available */\n hasPrevious: boolean;\n\n /**\n * Constructs a new paginated response.\n *\n * @param {T[]} items - The current page of items.\n * @param {Object} pagination - Pagination information.\n * @param {number} pagination.total - Total number of items across all pages.\n * @param {number} pagination.page - Current page number (1-based).\n * @param {number} pagination.pageSize - Number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n */\n constructor(items: T[], pagination: { total: number; page: number; pageSize: number }, message: string = 'Success') {\n super(message, items);\n\n this.total = pagination.total;\n this.page = pagination.page;\n this.pageSize = pagination.pageSize;\n\n this.totalPages = Math.ceil(this.total / this.pageSize);\n this.hasNext = this.page < this.totalPages;\n this.hasPrevious = this.page > 1;\n }\n}\n\n/**\n * Specialized response for operations that don't return data (HTTP 204).\n */\nexport class NoContentResponse extends SuccessResponse<null> {\n /**\n * Constructs a new no-content response.\n *\n * @param {string} [message=\"Operation completed successfully\"] - Optional custom message.\n */\n constructor(message: string = 'Operation completed successfully') {\n super(message, null);\n }\n}\n\n/**\n * Specialized response for redirects.\n */\nexport class RedirectResponse {\n /** The URL to redirect to */\n redirectUrl: string;\n\n /** HTTP status code for the redirect (301, 302, 303, 307, 308) */\n statusCode: number;\n\n /** Whether the response is a redirect */\n isRedirect: boolean = true;\n\n /** Unique identifier for this response */\n requestId: string = getRequestId() ?? randomUUID();\n\n /**\n * Constructs a new redirect response.\n *\n * @param {string} url - The URL to redirect to.\n * @param {number} [statusCode=302] - HTTP status code for the redirect.\n */\n constructor(url: string, statusCode: number = 302) {\n this.redirectUrl = url;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Creates a standard success response.\n *\n * @typeParam T - The shape of the data returned in the response.\n * @param {T} data - The data to include in the response.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {SuccessResponse<T>} A properly formatted success response.\n */\nexport function createSuccessResponse<T>(data: T, message: string = 'Success'): SuccessResponse<T> {\n return new SuccessResponse<T>(message, data);\n}\n\n/**\n * Creates a standard error response.\n *\n * @param {string} message - The error message.\n * @param {number} [statusCode=500] - HTTP status code for the error.\n * @returns {ErrorResponse} A properly formatted error response.\n */\nexport function createErrorResponse(message: string, statusCode: number = 500): ErrorResponse {\n return new ErrorResponse(message, statusCode);\n}\n\n/**\n * Creates a paginated response from array data.\n *\n * @typeParam T - The shape of each item in the collection.\n * @param {T[]} allItems - The complete array of items to paginate.\n * @param {number} page - The requested page (1-based).\n * @param {number} pageSize - The number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {PaginatedResponse<T>} A properly formatted paginated response.\n */\nexport function createPaginatedResponse<T>(\n allItems: T[],\n page: number,\n pageSize: number,\n message: string = 'Success'\n): PaginatedResponse<T> {\n // Ensure valid pagination parameters\n const validPage = Math.max(1, page);\n const validPageSize = Math.max(1, pageSize);\n\n // Calculate slice indices\n const startIndex = (validPage - 1) * validPageSize;\n const endIndex = startIndex + validPageSize;\n\n // Get current page items\n const pageItems = allItems.slice(startIndex, endIndex);\n\n return new PaginatedResponse<T>(\n pageItems,\n {\n total: allItems.length,\n page: validPage,\n pageSize: validPageSize\n },\n message\n );\n}\n\n/**\n * Adapter to convert API responses to Express.js response format.\n *\n * @param {any} res - Express response object.\n * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.\n */\nexport function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void {\n // Handle redirects\n if ('redirectUrl' in apiResponse) {\n res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);\n return;\n }\n\n // Handle errors\n if ('error' in apiResponse && apiResponse.error) {\n const errorResponse = apiResponse as ErrorResponse;\n res.status(errorResponse.status).json({\n error: true,\n message: errorResponse.message,\n timestamp: errorResponse.timestamp,\n requestId: errorResponse.requestId\n });\n return;\n }\n\n // Handle success responses\n const successResponse = apiResponse as SuccessResponse<any>;\n\n // No content (204) shouldn't return a body\n if (successResponse instanceof NoContentResponse) {\n res.status(204).end();\n return;\n }\n\n res.status(200).json(successResponse);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"response.utils.js","sourceRoot":"","sources":["../../../src/utils/response.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAIH,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAElC;;;;;GAKG;AACH,MAAM,OAAO,eAAe;IAgB1B;;;;;OAKG;IACH,YAAY,OAAe,EAAE,IAAQ;;QArBrC,sDAAsD;QACtD,YAAO,GAAW,SAAS,CAAC;QAE5B,2EAA2E;QAC3E,UAAK,GAAY,KAAK,CAAC;QAEvB,yCAAyC;QACzC,SAA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,iBAAiB,CAC1B,SAAS,EACT;QACE,KAAK,EAAE,QAAQ,CAAC,MAAM;QACtB,IAAI,EAAE,SAAS;QACf,QAAQ,EAAE,aAAa;KACxB,EACD,OAAO,CACR,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,GAAQ,EAAE,WAAoE;IACzG,mBAAmB;IACnB,IAAI,aAAa,IAAI,WAAW,EAAE,CAAC;QACjC,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,WAAW,CAAC,WAAW,CAAC,CAAC;QAC9D,OAAO;IACT,CAAC;IAED,gBAAgB;IAChB,IAAI,OAAO,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,EAAE,CAAC;QAChD,MAAM,aAAa,GAAG,WAA4B,CAAC;QACnD,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;YACpC,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,aAAa,CAAC,OAAO;YAC9B,SAAS,EAAE,aAAa,CAAC,SAAS;YAClC,SAAS,EAAE,aAAa,CAAC,SAAS;SACnC,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,2BAA2B;IAC3B,MAAM,eAAe,GAAG,WAAmC,CAAC;IAE5D,2CAA2C;IAC3C,IAAI,eAAe,YAAY,iBAAiB,EAAE,CAAC;QACjD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACxC,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 { ApiErrorResponse, ApiResponse } from '../types/api-response';\nimport { getRequestId } from './context-store.utils';\nimport { Env } from './env.utils';\nimport { uuid } from './id.utils';\n\n/**\n * Standard HTTP response wrapper for successful responses.\n * Implements the `ApiResponse<T>` interface and sets default values.\n *\n * @typeParam T - The shape of the data returned in the response.\n */\nexport class SuccessResponse<T> implements ApiResponse<T> {\n /** Message describing the result of the operation. */\n message: string = 'Success';\n\n /** Whether the response is an error. Always false in success responses. */\n error: boolean = false;\n\n /** The payload returned from the API. */\n data: T | null = null;\n\n /** Timestamp when the response was generated, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this response, useful for request tracing. */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new success response.\n *\n * @param {string} message - Optional message to override the default.\n * @param {T} [data] - Optional data payload.\n */\n constructor(message: string, data?: T) {\n if (message) this.message = message;\n this.data = data ?? null;\n }\n}\n\n/**\n * Wrapper for error responses that extends the native `Error` object.\n * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).\n */\nexport class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {\n /** HTTP status code associated with the error (e.g., 404, 500). */\n status: number;\n\n /** Indicates that this is an error. Always true. */\n error: boolean = true;\n\n /** Timestamp when the error occurred, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this error instance. */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new error response.\n *\n * @param {string} message - The error message to display or log.\n * @param {number} [status=500] - Optional HTTP status code (defaults to 500).\n */\n constructor(message: string, status: number = 500) {\n super(message);\n this.status = status;\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Response with paginated data extending the standard success response.\n * Useful for APIs that return large collections of data.\n *\n * @typeParam T - The shape of each item in the paginated collection.\n */\nexport class PaginatedResponse<T> extends SuccessResponse<T[]> {\n /** Total number of items across all pages */\n total: number;\n\n /** Current page number (1-based) */\n page: number;\n\n /** Number of items per page */\n pageSize: number;\n\n /** Total number of pages */\n totalPages: number;\n\n /** Whether there's a next page available */\n hasNext: boolean;\n\n /** Whether there's a previous page available */\n hasPrevious: boolean;\n\n /**\n * Constructs a new paginated response.\n *\n * @param {T[]} items - The current page of items.\n * @param {Object} pagination - Pagination information.\n * @param {number} pagination.total - Total number of items across all pages.\n * @param {number} pagination.page - Current page number (1-based).\n * @param {number} pagination.pageSize - Number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n */\n constructor(items: T[], pagination: { total: number; page: number; pageSize: number }, message: string = 'Success') {\n super(message, items);\n\n this.total = pagination.total;\n this.page = pagination.page;\n this.pageSize = pagination.pageSize;\n\n this.totalPages = Math.ceil(this.total / this.pageSize);\n this.hasNext = this.page < this.totalPages;\n this.hasPrevious = this.page > 1;\n }\n}\n\n/**\n * Specialized response for operations that don't return data (HTTP 204).\n */\nexport class NoContentResponse extends SuccessResponse<null> {\n /**\n * Constructs a new no-content response.\n *\n * @param {string} [message=\"Operation completed successfully\"] - Optional custom message.\n */\n constructor(message: string = 'Operation completed successfully') {\n super(message, null);\n }\n}\n\n/**\n * Specialized response for redirects.\n */\nexport class RedirectResponse {\n /** The URL to redirect to */\n redirectUrl: string;\n\n /** HTTP status code for the redirect (301, 302, 303, 307, 308) */\n statusCode: number;\n\n /** Whether the response is a redirect */\n isRedirect: boolean = true;\n\n /** Unique identifier for this response */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new redirect response.\n *\n * @param {string} url - The URL to redirect to.\n * @param {number} [statusCode=302] - HTTP status code for the redirect.\n */\n constructor(url: string, statusCode: number = 302) {\n this.redirectUrl = url;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Creates a standard success response.\n *\n * @typeParam T - The shape of the data returned in the response.\n * @param {T} data - The data to include in the response.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {SuccessResponse<T>} A properly formatted success response.\n */\nexport function createSuccessResponse<T>(data: T, message: string = 'Success'): SuccessResponse<T> {\n return new SuccessResponse<T>(message, data);\n}\n\n/**\n * Creates a standard error response.\n *\n * @param {string} message - The error message.\n * @param {number} [statusCode=500] - HTTP status code for the error.\n * @returns {ErrorResponse} A properly formatted error response.\n */\nexport function createErrorResponse(message: string, statusCode: number = 500): ErrorResponse {\n return new ErrorResponse(message, statusCode);\n}\n\n/**\n * Creates a final error response with request information.\n *\n * @param req - The original request object.\n * @param status - The HTTP status code.\n * @param message - The error message.\n * @param error - The original error object (optional).\n * @param options - Additional options for the response (optional).\n * @returns A properly formatted final error response.\n */\nexport function createFinalErrorResponse(\n req: Request,\n status: number,\n message: string,\n error?: any,\n options?: { includeDetails?: boolean }\n) {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: ApiErrorResponse = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n}\n\n/**\n * Creates a paginated response from array data.\n *\n * @typeParam T - The shape of each item in the collection.\n * @param {T[]} allItems - The complete array of items to paginate.\n * @param {number} page - The requested page (1-based).\n * @param {number} pageSize - The number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {PaginatedResponse<T>} A properly formatted paginated response.\n */\nexport function createPaginatedResponse<T>(\n allItems: T[],\n page: number,\n pageSize: number,\n message: string = 'Success'\n): PaginatedResponse<T> {\n // Ensure valid pagination parameters\n const validPage = Math.max(1, page);\n const validPageSize = Math.max(1, pageSize);\n\n // Calculate slice indices\n const startIndex = (validPage - 1) * validPageSize;\n const endIndex = startIndex + validPageSize;\n\n // Get current page items\n const pageItems = allItems.slice(startIndex, endIndex);\n\n return new PaginatedResponse<T>(\n pageItems,\n {\n total: allItems.length,\n page: validPage,\n pageSize: validPageSize\n },\n message\n );\n}\n\n/**\n * Adapter to convert API responses to Express.js response format.\n *\n * @param {any} res - Express response object.\n * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.\n */\nexport function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void {\n // Handle redirects\n if ('redirectUrl' in apiResponse) {\n res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);\n return;\n }\n\n // Handle errors\n if ('error' in apiResponse && apiResponse.error) {\n const errorResponse = apiResponse as ErrorResponse;\n res.status(errorResponse.status).json({\n error: true,\n message: errorResponse.message,\n timestamp: errorResponse.timestamp,\n requestId: errorResponse.requestId\n });\n return;\n }\n\n // Handle success responses\n const successResponse = apiResponse as SuccessResponse<any>;\n\n // No content (204) shouldn't return a body\n if (successResponse instanceof NoContentResponse) {\n res.status(204).end();\n return;\n }\n\n res.status(200).json(successResponse);\n}\n"]}
|
|
@@ -1,3 +1,26 @@
|
|
|
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
|
+
*/
|
|
1
24
|
/**
|
|
2
25
|
* Capitalizes the first character of a string.
|
|
3
26
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string.utils.js","sourceRoot":"","sources":["../../../src/utils/string.utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,OAAO,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC5E,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,OAAO,G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AAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAW,EAAE,SAAiB,EAAE,gBAAyB,IAAI;IAC5F,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QACxB,SAAS,GAAG,SAAS,CAAC,WAAW,EAAE,CAAC;IACtC,CAAC;IAED,OAAO,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Capitalizes the first character of a string.\n *\n * @param {string} str - The input string.\n * @returns {string} The string with the first character in uppercase.\n */\nexport function capitalize(str: string): string {\n return str.length === 0 ? '' : str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Converts a string to kebab-case (e.g., \"FooBar test\" → \"foo-bar-test\").\n *\n * @param {string} str - The input string.\n * @returns {string} The kebab-cased string.\n */\nexport function toKebabCase(str: string): string {\n return str\n .replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase -> camel-Case\n .replace(/\\s+/g, '-') // spaces to dash\n .replace(/_+/g, '-') // underscores to dash\n .toLowerCase();\n}\n\n/**\n * Converts a kebab-case or snake_case string to camelCase.\n *\n * @param {string} str - The input string.\n * @returns {string} The camelCased string.\n */\nexport function toCamelCase(str: string): string {\n return str.replace(/[-_](.)/g, (_, c: string) => c.toUpperCase());\n}\n\n/**\n * Converts a string to a URL-friendly slug (lowercase, dashes, alphanumeric).\n *\n * @param {string} str - The input string.\n * @returns {string} The slugified string.\n */\nexport function slugify(str: string): string {\n return str\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '') // remove non-word\n .replace(/\\s+/g, '-') // spaces to dash\n .replace(/-+/g, '-') // multiple dashes to one\n .replace(/^-+|-+$/g, ''); // trim leading/trailing dashes\n}\n\n/**\n * Truncates a string to a specific length, appending '...' if truncated.\n *\n * @param {string} str - The input string.\n * @param {number} len - The maximum length.\n * @returns {string} The truncated string.\n */\nexport function truncate(str: string, len: number): string {\n return str.length > len ? str.slice(0, len) + '...' : str;\n}\n\n/**\n * Converts a string to PascalCase (e.g., \"foo-bar\" → \"FooBar\").\n *\n * @param {string} str - The input string.\n * @returns {string} The PascalCased string.\n */\nexport function toPascalCase(str: string): string {\n return capitalize(toCamelCase(str));\n}\n\n/**\n * Converts a string to snake_case (e.g., \"FooBar test\" → \"foo_bar_test\").\n *\n * @param {string} str - The input string.\n * @returns {string} The snake_cased string.\n */\nexport function toSnakeCase(str: string): string {\n return str\n .trim()\n .replace(/([a-z])([A-Z])/g, '$1_$2') // camelCase -> camel_Case\n .replace(/\\s+/g, '_') // spaces to underscore\n .replace(/-+/g, '_') // dashes to underscore\n .toLowerCase();\n}\n\n/**\n * Masks a string by replacing characters with a mask character.\n * Useful for hiding sensitive information like credit cards or passwords.\n *\n * @param {string} str - The string to mask.\n * @param {number} [visibleStart=0] - Number of characters to show at start.\n * @param {number} [visibleEnd=0] - Number of characters to show at end.\n * @param {string} [maskChar=\"*\"] - Character to use for masking.\n * @returns {string} The masked string.\n */\nexport function mask(str: string, visibleStart: number = 0, visibleEnd: number = 0, maskChar: string = '*'): string {\n if (!str || str.length === 0) return '';\n if (visibleStart >= str.length) return str;\n\n const start = str.slice(0, visibleStart);\n const end = visibleEnd > 0 ? str.slice(-visibleEnd) : '';\n const masked = maskChar.repeat(Math.max(0, str.length - visibleStart - visibleEnd));\n\n return start + masked + end;\n}\n\n/**\n * Removes all HTML tags from a string.\n *\n * @param {string} str - The HTML string to process.\n * @returns {string} The string with HTML tags removed.\n */\nexport function stripHtml(str: string): string {\n return str.replace(/<[^>]*>/g, '');\n}\n\n/**\n * Performs case-insensitive string comparison.\n *\n * @param {string} a - First string.\n * @param {string} b - Second string.\n * @returns {boolean} True if the strings are equal ignoring case.\n */\nexport function equalsIgnoreCase(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n\n/**\n * Reverses a string.\n *\n * @param {string} str - The string to reverse.\n * @returns {string} The reversed string.\n */\nexport function reverse(str: string): string {\n return str.split('').reverse().join('');\n}\n\n/**\n * Counts occurrences of a substring within a string.\n *\n * @param {string} str - The source string.\n * @param {string} substring - The substring to count.\n * @param {boolean} [caseSensitive=true] - Whether to perform case-sensitive counting.\n * @returns {number} Number of occurrences.\n */\nexport function countOccurrences(str: string, substring: string, caseSensitive: boolean = true): number {\n if (!caseSensitive) {\n str = str.toLowerCase();\n substring = substring.toLowerCase();\n }\n\n return str.split(substring).length - 1;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"string.utils.js","sourceRoot":"","sources":["../../../src/utils/string.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,OAAO,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC5E,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,OAAO,GAAG;SACP,OAAO,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC,0BAA0B;SAC9D,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,iBAAiB;SACtC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,sBAAsB;SAC1C,WAAW,EAAE,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,OAAO,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AACpE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,O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ereby 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 * Capitalizes the first character of a string.\n *\n * @param {string} str - The input string.\n * @returns {string} The string with the first character in uppercase.\n */\nexport function capitalize(str: string): string {\n return str.length === 0 ? '' : str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Converts a string to kebab-case (e.g., \"FooBar test\" → \"foo-bar-test\").\n *\n * @param {string} str - The input string.\n * @returns {string} The kebab-cased string.\n */\nexport function toKebabCase(str: string): string {\n return str\n .replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase -> camel-Case\n .replace(/\\s+/g, '-') // spaces to dash\n .replace(/_+/g, '-') // underscores to dash\n .toLowerCase();\n}\n\n/**\n * Converts a kebab-case or snake_case string to camelCase.\n *\n * @param {string} str - The input string.\n * @returns {string} The camelCased string.\n */\nexport function toCamelCase(str: string): string {\n return str.replace(/[-_](.)/g, (_, c: string) => c.toUpperCase());\n}\n\n/**\n * Converts a string to a URL-friendly slug (lowercase, dashes, alphanumeric).\n *\n * @param {string} str - The input string.\n * @returns {string} The slugified string.\n */\nexport function slugify(str: string): string {\n return str\n .toLowerCase()\n .replace(/[^\\w\\s-]/g, '') // remove non-word\n .replace(/\\s+/g, '-') // spaces to dash\n .replace(/-+/g, '-') // multiple dashes to one\n .replace(/^-+|-+$/g, ''); // trim leading/trailing dashes\n}\n\n/**\n * Truncates a string to a specific length, appending '...' if truncated.\n *\n * @param {string} str - The input string.\n * @param {number} len - The maximum length.\n * @returns {string} The truncated string.\n */\nexport function truncate(str: string, len: number): string {\n return str.length > len ? str.slice(0, len) + '...' : str;\n}\n\n/**\n * Converts a string to PascalCase (e.g., \"foo-bar\" → \"FooBar\").\n *\n * @param {string} str - The input string.\n * @returns {string} The PascalCased string.\n */\nexport function toPascalCase(str: string): string {\n return capitalize(toCamelCase(str));\n}\n\n/**\n * Converts a string to snake_case (e.g., \"FooBar test\" → \"foo_bar_test\").\n *\n * @param {string} str - The input string.\n * @returns {string} The snake_cased string.\n */\nexport function toSnakeCase(str: string): string {\n return str\n .trim()\n .replace(/([a-z])([A-Z])/g, '$1_$2') // camelCase -> camel_Case\n .replace(/\\s+/g, '_') // spaces to underscore\n .replace(/-+/g, '_') // dashes to underscore\n .toLowerCase();\n}\n\n/**\n * Masks a string by replacing characters with a mask character.\n * Useful for hiding sensitive information like credit cards or passwords.\n *\n * @param {string} str - The string to mask.\n * @param {number} [visibleStart=0] - Number of characters to show at start.\n * @param {number} [visibleEnd=0] - Number of characters to show at end.\n * @param {string} [maskChar=\"*\"] - Character to use for masking.\n * @returns {string} The masked string.\n */\nexport function mask(str: string, visibleStart: number = 0, visibleEnd: number = 0, maskChar: string = '*'): string {\n if (!str || str.length === 0) return '';\n if (visibleStart >= str.length) return str;\n\n const start = str.slice(0, visibleStart);\n const end = visibleEnd > 0 ? str.slice(-visibleEnd) : '';\n const masked = maskChar.repeat(Math.max(0, str.length - visibleStart - visibleEnd));\n\n return start + masked + end;\n}\n\n/**\n * Removes all HTML tags from a string.\n *\n * @param {string} str - The HTML string to process.\n * @returns {string} The string with HTML tags removed.\n */\nexport function stripHtml(str: string): string {\n return str.replace(/<[^>]*>/g, '');\n}\n\n/**\n * Performs case-insensitive string comparison.\n *\n * @param {string} a - First string.\n * @param {string} b - Second string.\n * @returns {boolean} True if the strings are equal ignoring case.\n */\nexport function equalsIgnoreCase(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase();\n}\n\n/**\n * Reverses a string.\n *\n * @param {string} str - The string to reverse.\n * @returns {string} The reversed string.\n */\nexport function reverse(str: string): string {\n return str.split('').reverse().join('');\n}\n\n/**\n * Counts occurrences of a substring within a string.\n *\n * @param {string} str - The source string.\n * @param {string} substring - The substring to count.\n * @param {boolean} [caseSensitive=true] - Whether to perform case-sensitive counting.\n * @returns {number} Number of occurrences.\n */\nexport function countOccurrences(str: string, substring: string, caseSensitive: boolean = true): number {\n if (!caseSensitive) {\n str = str.toLowerCase();\n substring = substring.toLowerCase();\n }\n\n return str.split(substring).length - 1;\n}\n"]}
|
|
@@ -1,3 +1,26 @@
|
|
|
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
|
+
*/
|
|
1
24
|
import { URL, URLSearchParams } from 'url';
|
|
2
25
|
/**
|
|
3
26
|
* Appends query parameters to a given URL.
|