@catbee/utils 0.0.3 → 0.0.5
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/README.md +693 -245
- package/build/esm/config.d.ts +18 -7
- package/build/esm/config.js +23 -7
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +2 -0
- package/build/esm/index.js +2 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/utils/cache.utils.js +16 -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 +1 -1
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +3 -2
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +292 -17
- package/build/esm/utils/decorators.utils.js +372 -40
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +186 -23
- package/build/esm/utils/env.utils.js +494 -91
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.js +1 -1
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +107 -0
- package/build/esm/utils/logger.utils.js +210 -19
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +42 -34
- package/build/esm/utils/middleware.utils.js +88 -51
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/request.utils.d.ts +77 -0
- package/build/esm/utils/request.utils.js +173 -0
- package/build/esm/utils/request.utils.js.map +1 -0
- package/build/esm/utils/response.utils.js +4 -4
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esnext/config.d.ts +18 -7
- package/build/esnext/config.js +23 -7
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +2 -0
- package/build/esnext/index.js +2 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +16 -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 +1 -1
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +3 -2
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +292 -17
- package/build/esnext/utils/decorators.utils.js +348 -21
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +186 -23
- package/build/esnext/utils/env.utils.js +445 -77
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.js +1 -1
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +107 -0
- package/build/esnext/utils/logger.utils.js +181 -19
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +42 -34
- package/build/esnext/utils/middleware.utils.js +86 -51
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/request.utils.d.ts +77 -0
- package/build/esnext/utils/request.utils.js +145 -0
- package/build/esnext/utils/request.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.js +4 -4
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/src/config.d.ts +18 -7
- package/build/src/config.js +26 -8
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +2 -0
- package/build/src/index.js +5 -0
- package/build/src/index.js.map +1 -1
- package/build/src/utils/cache.utils.js +15 -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 +1 -1
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +2 -1
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +292 -17
- package/build/src/utils/decorators.utils.js +350 -21
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +186 -23
- package/build/src/utils/env.utils.js +444 -76
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.js +1 -1
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +107 -0
- package/build/src/utils/logger.utils.js +187 -19
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +42 -34
- package/build/src/utils/middleware.utils.js +86 -50
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/request.utils.d.ts +77 -0
- package/build/src/utils/request.utils.js +152 -0
- package/build/src/utils/request.utils.js.map +1 -0
- package/build/src/utils/response.utils.js +4 -4
- package/build/src/utils/response.utils.js.map +1 -1
- package/package.json +11 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":"AA+BA;;;;;;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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,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/**\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,5 +1,5 @@
|
|
|
1
|
-
import { randomUUID } from 'crypto';
|
|
2
1
|
import { getRequestId } from './context-store.utils';
|
|
2
|
+
import { uuid } from './id.utils';
|
|
3
3
|
/**
|
|
4
4
|
* Standard HTTP response wrapper for successful responses.
|
|
5
5
|
* Implements the `ApiResponse<T>` interface and sets default values.
|
|
@@ -24,7 +24,7 @@ export class SuccessResponse {
|
|
|
24
24
|
/** Timestamp when the response was generated, in ISO format. */
|
|
25
25
|
this.timestamp = new Date().toISOString();
|
|
26
26
|
/** Unique identifier for this response, useful for request tracing. */
|
|
27
|
-
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
27
|
+
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
28
28
|
if (message)
|
|
29
29
|
this.message = message;
|
|
30
30
|
this.data = data !== null && data !== void 0 ? data : null;
|
|
@@ -49,7 +49,7 @@ export class ErrorResponse extends Error {
|
|
|
49
49
|
/** Timestamp when the error occurred, in ISO format. */
|
|
50
50
|
this.timestamp = new Date().toISOString();
|
|
51
51
|
/** Unique identifier for this error instance. */
|
|
52
|
-
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
52
|
+
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
53
53
|
this.status = status;
|
|
54
54
|
this.name = this.constructor.name;
|
|
55
55
|
Error.captureStackTrace(this, this.constructor);
|
|
@@ -110,7 +110,7 @@ export class RedirectResponse {
|
|
|
110
110
|
/** Whether the response is a redirect */
|
|
111
111
|
this.isRedirect = true;
|
|
112
112
|
/** Unique identifier for this response */
|
|
113
|
-
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
113
|
+
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
114
114
|
this.redirectUrl = url;
|
|
115
115
|
this.statusCode = statusCode;
|
|
116
116
|
}
|
|
@@ -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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AG,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":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,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,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,IAAI,EAAE,CAAC;QAS3C,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,G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Q,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":["import { ApiResponse } from '../types/api-response';\nimport { getRequestId } from './context-store.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 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"]}
|
package/build/src/config.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silen
|
|
|
2
2
|
/**
|
|
3
3
|
* Application runtime configuration loaded from environment variables.
|
|
4
4
|
*/
|
|
5
|
-
export declare
|
|
6
|
-
|
|
5
|
+
export declare let config: {
|
|
6
|
+
logger: {
|
|
7
7
|
/**
|
|
8
8
|
* Logging level (e.g., 'info', 'debug', 'warn', 'error').
|
|
9
9
|
*/
|
|
@@ -11,24 +11,35 @@ export declare const Config: {
|
|
|
11
11
|
/**
|
|
12
12
|
* Name of the logger instance (defaults to npm package name).
|
|
13
13
|
*/
|
|
14
|
-
name: string
|
|
14
|
+
name: string;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
16
|
+
* Enables pretty-print logging in development.
|
|
17
|
+
* Has no effect in production.
|
|
17
18
|
*/
|
|
18
|
-
|
|
19
|
+
pretty: boolean;
|
|
19
20
|
};
|
|
20
|
-
|
|
21
|
+
http: {
|
|
21
22
|
/**
|
|
22
23
|
* Timeout for HTTP requests in milliseconds
|
|
23
24
|
*/
|
|
24
25
|
timeout: number;
|
|
25
26
|
};
|
|
26
|
-
|
|
27
|
+
cache: {
|
|
27
28
|
/**
|
|
28
29
|
* Default TTL (time to live) for cache entries in seconds
|
|
29
30
|
*/
|
|
30
31
|
defaultTtl: number;
|
|
31
32
|
};
|
|
32
33
|
};
|
|
34
|
+
/**
|
|
35
|
+
* Update the @catbee/utils configuration.
|
|
36
|
+
* @param value Partial configuration object.
|
|
37
|
+
*/
|
|
38
|
+
export declare function setConfig(value: Partial<typeof config>): void;
|
|
39
|
+
/**
|
|
40
|
+
* Get the current @catbee/utils configuration.
|
|
41
|
+
* @returns The current configuration object.
|
|
42
|
+
*/
|
|
43
|
+
export declare function getConfig(): typeof config;
|
|
33
44
|
export {};
|
|
34
45
|
//# sourceMappingURL=config.d.ts.map
|
package/build/src/config.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.config = void 0;
|
|
4
|
+
exports.setConfig = setConfig;
|
|
5
|
+
exports.getConfig = getConfig;
|
|
4
6
|
const env_utils_1 = require("./utils/env.utils");
|
|
7
|
+
const obj_utils_1 = require("./utils/obj.utils");
|
|
5
8
|
/**
|
|
6
9
|
* Application runtime configuration loaded from environment variables.
|
|
7
10
|
*/
|
|
8
|
-
exports.
|
|
9
|
-
|
|
11
|
+
exports.config = {
|
|
12
|
+
logger: {
|
|
10
13
|
/**
|
|
11
14
|
* Logging level (e.g., 'info', 'debug', 'warn', 'error').
|
|
12
15
|
*/
|
|
@@ -16,21 +19,36 @@ exports.Config = {
|
|
|
16
19
|
*/
|
|
17
20
|
name: env_utils_1.Env.get('LOGGER_NAME', env_utils_1.Env.get('npm_package_name', '@catbee/utils')),
|
|
18
21
|
/**
|
|
19
|
-
*
|
|
22
|
+
* Enables pretty-print logging in development.
|
|
23
|
+
* Has no effect in production.
|
|
20
24
|
*/
|
|
21
|
-
|
|
25
|
+
pretty: env_utils_1.Env.getBoolean('LOGGER_PRETTY', true)
|
|
22
26
|
},
|
|
23
|
-
|
|
27
|
+
http: {
|
|
24
28
|
/**
|
|
25
29
|
* Timeout for HTTP requests in milliseconds
|
|
26
30
|
*/
|
|
27
31
|
timeout: env_utils_1.Env.getNumber('HTTP_TIMEOUT', 30000)
|
|
28
32
|
},
|
|
29
|
-
|
|
33
|
+
cache: {
|
|
30
34
|
/**
|
|
31
35
|
* Default TTL (time to live) for cache entries in seconds
|
|
32
36
|
*/
|
|
33
|
-
defaultTtl: env_utils_1.Env.getNumber('
|
|
37
|
+
defaultTtl: env_utils_1.Env.getNumber('CACHE_DEFAULT_TTL_SECONDS', 3600) * 1000
|
|
34
38
|
}
|
|
35
39
|
};
|
|
40
|
+
/**
|
|
41
|
+
* Update the @catbee/utils configuration.
|
|
42
|
+
* @param value Partial configuration object.
|
|
43
|
+
*/
|
|
44
|
+
function setConfig(value) {
|
|
45
|
+
(0, obj_utils_1.deepObjMerge)(exports.config, value);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Get the current @catbee/utils configuration.
|
|
49
|
+
* @returns The current configuration object.
|
|
50
|
+
*/
|
|
51
|
+
function getConfig() {
|
|
52
|
+
return exports.config;
|
|
53
|
+
}
|
|
36
54
|
//# sourceMappingURL=config.js.map
|
package/build/src/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";;;AA8CA,8BAEC;AAMD,8BAEC;AAxDD,iDAAwC;AACxC,iDAAiD;AAIjD;;GAEG;AACQ,QAAA,MAAM,GAAG;IAClB,MAAM,EAAE;QACN;;WAEG;QACH,KAAK,EAAE,eAAG,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAa;QAElD;;WAEG;QACH,IAAI,EAAE,eAAG,CAAC,GAAG,CAAC,aAAa,EAAE,eAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,eAAe,CAAC,CAAC;QAE1E;;;WAGG;QACH,MAAM,EAAE,eAAG,CAAC,UAAU,CAAC,eAAe,EAAE,IAAI,CAAC;KAC9C;IAED,IAAI,EAAE;QACJ;;WAEG;QACH,OAAO,EAAE,eAAG,CAAC,SAAS,CAAC,cAAc,EAAE,KAAK,CAAC;KAC9C;IAED,KAAK,EAAE;QACL;;WAEG;QACH,UAAU,EAAE,eAAG,CAAC,SAAS,CAAC,2BAA2B,EAAE,IAAI,CAAC,GAAG,IAAI;KACpE;CACF,CAAC;AAEF;;;GAGG;AACH,SAAgB,SAAS,CAAC,KAA6B;IACrD,IAAA,wBAAY,EAAC,cAAM,EAAE,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED;;;GAGG;AACH,SAAgB,SAAS;IACvB,OAAO,cAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Env } from './utils/env.utils';\nimport { deepObjMerge } from './utils/obj.utils';\n\ntype LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent';\n\n/**\n * Application runtime configuration loaded from environment variables.\n */\nexport let config = {\n logger: {\n /**\n * Logging level (e.g., 'info', 'debug', 'warn', 'error').\n */\n level: Env.get('LOGGER_LEVEL', 'info') as LogLevel,\n\n /**\n * Name of the logger instance (defaults to npm package name).\n */\n name: Env.get('LOGGER_NAME', Env.get('npm_package_name', '@catbee/utils')),\n\n /**\n * Enables pretty-print logging in development.\n * Has no effect in production.\n */\n pretty: Env.getBoolean('LOGGER_PRETTY', true)\n },\n\n http: {\n /**\n * Timeout for HTTP requests in milliseconds\n */\n timeout: Env.getNumber('HTTP_TIMEOUT', 30000)\n },\n\n cache: {\n /**\n * Default TTL (time to live) for cache entries in seconds\n */\n defaultTtl: Env.getNumber('CACHE_DEFAULT_TTL_SECONDS', 3600) * 1000\n }\n};\n\n/**\n * Update the @catbee/utils configuration.\n * @param value Partial configuration object.\n */\nexport function setConfig(value: Partial<typeof config>): void {\n deepObjMerge(config, value);\n}\n\n/**\n * Get the current @catbee/utils configuration.\n * @returns The current configuration object.\n */\nexport function getConfig(): typeof config {\n return config;\n}\n"]}
|
package/build/src/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { setConfig, getConfig } from './config';
|
|
1
2
|
export * from './utils/array.utils';
|
|
2
3
|
export * from './utils/async.utils';
|
|
3
4
|
export * from './utils/cache.utils';
|
|
@@ -13,6 +14,7 @@ export * from './utils/id.utils';
|
|
|
13
14
|
export * from './utils/logger.utils';
|
|
14
15
|
export * from './utils/middleware.utils';
|
|
15
16
|
export * from './utils/obj.utils';
|
|
17
|
+
export * from './utils/request.utils';
|
|
16
18
|
export * from './utils/response.utils';
|
|
17
19
|
export * from './utils/string.utils';
|
|
18
20
|
export * from './utils/url.utils';
|
package/build/src/index.js
CHANGED
|
@@ -14,6 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.getConfig = exports.setConfig = void 0;
|
|
18
|
+
var config_1 = require("./config");
|
|
19
|
+
Object.defineProperty(exports, "setConfig", { enumerable: true, get: function () { return config_1.setConfig; } });
|
|
20
|
+
Object.defineProperty(exports, "getConfig", { enumerable: true, get: function () { return config_1.getConfig; } });
|
|
17
21
|
__exportStar(require("./utils/array.utils"), exports);
|
|
18
22
|
__exportStar(require("./utils/async.utils"), exports);
|
|
19
23
|
__exportStar(require("./utils/cache.utils"), exports);
|
|
@@ -29,6 +33,7 @@ __exportStar(require("./utils/id.utils"), exports);
|
|
|
29
33
|
__exportStar(require("./utils/logger.utils"), exports);
|
|
30
34
|
__exportStar(require("./utils/middleware.utils"), exports);
|
|
31
35
|
__exportStar(require("./utils/obj.utils"), exports);
|
|
36
|
+
__exportStar(require("./utils/request.utils"), exports);
|
|
32
37
|
__exportStar(require("./utils/response.utils"), exports);
|
|
33
38
|
__exportStar(require("./utils/string.utils"), exports);
|
|
34
39
|
__exportStar(require("./utils/url.utils"), exports);
|
package/build/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,mCAAgD;AAAvC,mGAAA,SAAS,OAAA;AAAE,mGAAA,SAAS,OAAA;AAE7B,sDAAoC;AACpC,sDAAoC;AACpC,sDAAoC;AACpC,8DAA4C;AAC5C,uDAAqC;AACrC,2DAAyC;AACzC,oDAAkC;AAClC,oDAAkC;AAClC,0DAAwC;AACxC,mDAAiC;AACjC,4DAA0C;AAC1C,mDAAiC;AACjC,uDAAqC;AACrC,2DAAyC;AACzC,oDAAkC;AAClC,wDAAsC;AACtC,yDAAuC;AACvC,uDAAqC;AACrC,oDAAkC;AAClC,yDAAuC;AAEvC,uDAAqC","sourcesContent":["export { setConfig, getConfig } from './config';\n\nexport * from './utils/array.utils';\nexport * from './utils/async.utils';\nexport * from './utils/cache.utils';\nexport * from './utils/context-store.utils';\nexport * from './utils/crypto.utils';\nexport * from './utils/decorators.utils';\nexport * from './utils/dir.utils';\nexport * from './utils/env.utils';\nexport * from './utils/exception.utils';\nexport * from './utils/fs.utils';\nexport * from './utils/http-status-codes';\nexport * from './utils/id.utils';\nexport * from './utils/logger.utils';\nexport * from './utils/middleware.utils';\nexport * from './utils/obj.utils';\nexport * from './utils/request.utils';\nexport * from './utils/response.utils';\nexport * from './utils/string.utils';\nexport * from './utils/url.utils';\nexport * from './utils/validate.utils';\n\nexport * from './types/api-response';\n"]}
|
|
@@ -20,7 +20,7 @@ class TTLCache {
|
|
|
20
20
|
constructor(options = {}) {
|
|
21
21
|
var _a;
|
|
22
22
|
this.cache = new Map();
|
|
23
|
-
this.ttlMs = (_a = options.ttlMs) !== null && _a !== void 0 ? _a : config_1.
|
|
23
|
+
this.ttlMs = (_a = options.ttlMs) !== null && _a !== void 0 ? _a : config_1.config.cache.defaultTtl;
|
|
24
24
|
this.maxSize = options.maxSize;
|
|
25
25
|
// Setup auto-cleanup if enabled
|
|
26
26
|
const autoCleanupMs = options.autoCleanupMs;
|
|
@@ -49,8 +49,10 @@ class TTLCache {
|
|
|
49
49
|
setWithTTL(key, value, ttlMs) {
|
|
50
50
|
const now = Date.now();
|
|
51
51
|
const expiresAt = now + ttlMs;
|
|
52
|
+
if (this.cache.has(key)) {
|
|
53
|
+
this.cache.delete(key); // remove old entry to maintain LRU order
|
|
54
|
+
}
|
|
52
55
|
this.cache.set(key, { value, expiresAt, lastAccessed: now });
|
|
53
|
-
// Enforce max size limit if configured
|
|
54
56
|
if (this.maxSize && this.cache.size > this.maxSize) {
|
|
55
57
|
this.evictLRU();
|
|
56
58
|
}
|
|
@@ -70,8 +72,11 @@ class TTLCache {
|
|
|
70
72
|
this.cache.delete(key);
|
|
71
73
|
return undefined;
|
|
72
74
|
}
|
|
73
|
-
// Update
|
|
75
|
+
// Update lastAccessed and move key to the end (most recently used)
|
|
74
76
|
entry.lastAccessed = now;
|
|
77
|
+
// Re-insert to end of Map to maintain LRU order
|
|
78
|
+
this.cache.delete(key);
|
|
79
|
+
this.cache.set(key, entry);
|
|
75
80
|
return entry.value;
|
|
76
81
|
}
|
|
77
82
|
/**
|
|
@@ -251,21 +256,16 @@ class TTLCache {
|
|
|
251
256
|
* @private
|
|
252
257
|
*/
|
|
253
258
|
evictLRU() {
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
for (const [key, entry] of this.cache.entries()) {
|
|
257
|
-
|
|
258
|
-
if (Date.now() > entry.expiresAt) {
|
|
259
|
+
const now = Date.now();
|
|
260
|
+
// Remove all expired items first
|
|
261
|
+
for (const [key, entry] of Array.from(this.cache.entries())) {
|
|
262
|
+
if (now > entry.expiresAt) {
|
|
259
263
|
this.cache.delete(key);
|
|
260
|
-
return;
|
|
261
|
-
}
|
|
262
|
-
// Find the oldest accessed entry
|
|
263
|
-
if (entry.lastAccessed && entry.lastAccessed < oldestAccess) {
|
|
264
|
-
oldestAccess = entry.lastAccessed;
|
|
265
|
-
oldestKey = key;
|
|
266
264
|
}
|
|
267
265
|
}
|
|
268
|
-
|
|
266
|
+
// Evict oldest entries until within max size
|
|
267
|
+
while (this.maxSize && this.cache.size > this.maxSize) {
|
|
268
|
+
const oldestKey = this.cache.keys().next().value;
|
|
269
269
|
this.cache.delete(oldestKey);
|
|
270
270
|
}
|
|
271
271
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":";;;AAAA,sCAAmC;AAuBnC;;;;;;;;;;GAUG;AACH,MAAa,QAAQ;IAMnB;;OAEG;IACH,YAAY,UAA2B,EAAE;;QARjC,UAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;QAS1C,IAAI,CAAC,KAAK,GAAG,MAAA,OAAO,CAAC,KAAK,mCAAI,eAAM,CAAC,KAAK,CAAC,UAAU,CAAC;QACtD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAE/B,gCAAgC;QAChC,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC5C,IAAI,aAAa,IAAI,aAAa,GAAG,CAAC,EAA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;IACH,CAAC;IAED;;;OAGG;IACK,QAAQ;QACd,IAAI,SAAwB,CAAC;QAC7B,IAAI,YAAY,GAAG,QAAQ,CAAC;QAE5B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,CAAC;YAChD,wCAAwC;YACxC,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;gBACjC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACvB,OAAO;YACT,CAAC;YAED,iCAAiC;YACjC,IAAI,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,GAAG,YAAY,EAAE,CAAC;gBAC5D,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;gBAClC,SAAS,GAAG,GAAG,CAAC;YAClB,CAAC;QACH,CAAC;QAED,IAAI,SAAS,EAAE,CAAC;YACd,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;CACF;AA7RD,4BA6RC","sourcesContent":["import { Config } from '../config';\n\n/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n lastAccessed?: number; // Track last access time for LRU functionality\n};\n\n/**\n * Options for configuring a TTLCache instance.\n */\nexport interface TTLCacheOptions {\n /** Default time-to-live in milliseconds for cache entries */\n ttlMs?: number;\n /** Maximum number of entries to keep in cache (uses LRU eviction policy) */\n maxSize?: number;\n /** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */\n autoCleanupMs?: number;\n}\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>({ ttlMs: 1000 });\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n private ttlMs: number;\n private maxSize?: number;\n private cleanupInterval?: NodeJS.Timeout;\n\n /**\n * @param options - Configuration options for the cache\n */\n constructor(options: TTLCacheOptions = {}) {\n this.ttlMs = options.ttlMs ?? Config.Cache.defaultTtl;\n this.maxSize = options.maxSize;\n\n // Setup auto-cleanup if enabled\n const autoCleanupMs = options.autoCleanupMs;\n if (autoCleanupMs && autoCleanupMs > 0) {\n this.cleanupInterval = setInterval(() => {\n this.cleanup();\n }, autoCleanupMs);\n }\n }\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n this.setWithTTL(key, value, this.ttlMs);\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const now = Date.now();\n const expiresAt = now + ttlMs;\n this.cache.set(key, { value, expiresAt, lastAccessed: now });\n\n // Enforce max size limit if configured\n if (this.maxSize && this.cache.size > this.maxSize) {\n this.evictLRU();\n }\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n\n // Update last access time for LRU tracking\n entry.lastAccessed = now;\n return entry.value;\n }\n\n /**\n * Retrieves or computes a value if it's not in the cache or has expired.\n *\n * @param key - The key to retrieve\n * @param producer - Function to generate the value if not cached\n * @param ttlMs - Optional custom TTL for the computed value\n * @returns The cached or computed value\n */\n async getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V> {\n const value = this.get(key);\n if (value !== undefined) return value;\n\n const newValue = await producer();\n this.setWithTTL(key, newValue, ttlMs ?? this.ttlMs);\n return newValue;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Set multiple key-value pairs at once with the default TTL.\n *\n * @param entries - Array of [key, value] tuples to set\n */\n setMany(entries: [K, V][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get multiple values at once.\n *\n * @param keys - Array of keys to retrieve\n * @returns Array of values (undefined for keys that don't exist or expired)\n */\n getMany(keys: K[]): (V | undefined)[] {\n return keys.map(key => this.get(key));\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n\n /**\n * Extends the expiration of a key by the specified time or default TTL.\n *\n * @param key - The key to refresh\n * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)\n * @returns true if the key was found and refreshed, false otherwise\n */\n refresh(key: K, ttlMs?: number): boolean {\n const entry = this.cache.get(key);\n if (!entry) return false;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return false;\n }\n\n entry.expiresAt = now + (ttlMs ?? this.ttlMs);\n entry.lastAccessed = now;\n return true;\n }\n\n /**\n * Returns a snapshot of cache stats.\n *\n * @returns Object containing cache statistics\n */\n stats() {\n const now = Date.now();\n let expired = 0;\n let valid = 0;\n\n for (const entry of this.cache.values()) {\n if (now > entry.expiresAt) {\n expired++;\n } else {\n valid++;\n }\n }\n\n return {\n size: this.cache.size,\n validEntries: valid,\n expiredEntries: expired,\n maxSize: this.maxSize\n };\n }\n\n /**\n * Stop the auto-cleanup interval if it's running.\n */\n destroy() {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n\n /**\n * Evict the least recently used entry from the cache.\n * @private\n */\n private evictLRU(): void {\n let oldestKey: K | undefined;\n let oldestAccess = Infinity;\n\n for (const [key, entry] of this.cache.entries()) {\n // Skip entries that are already expired\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return;\n }\n\n // Find the oldest accessed entry\n if (entry.lastAccessed && entry.lastAccessed < oldestAccess) {\n oldestAccess = entry.lastAccessed;\n oldestKey = key;\n }\n }\n\n if (oldestKey) {\n this.cache.delete(oldestKey);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":";;;AAAA,sCAAmC;AAuBnC;;;;;;;;;;GAUG;AACH,MAAa,QAAQ;IAMnB;;OAEG;IACH,YAAY,UAA2B,EA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AC,SAAc,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;CACF;AA/RD,4BA+RC","sourcesContent":["import { config } from '../config';\n\n/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n lastAccessed?: number; // Track last access time for LRU functionality\n};\n\n/**\n * Options for configuring a TTLCache instance.\n */\nexport interface TTLCacheOptions {\n /** Default time-to-live in milliseconds for cache entries */\n ttlMs?: number;\n /** Maximum number of entries to keep in cache (uses LRU eviction policy) */\n maxSize?: number;\n /** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */\n autoCleanupMs?: number;\n}\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>({ ttlMs: 1000 });\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n private ttlMs: number;\n private maxSize?: number;\n private cleanupInterval?: NodeJS.Timeout;\n\n /**\n * @param options - Configuration options for the cache\n */\n constructor(options: TTLCacheOptions = {}) {\n this.ttlMs = options.ttlMs ?? config.cache.defaultTtl;\n this.maxSize = options.maxSize;\n\n // Setup auto-cleanup if enabled\n const autoCleanupMs = options.autoCleanupMs;\n if (autoCleanupMs && autoCleanupMs > 0) {\n this.cleanupInterval = setInterval(() => {\n this.cleanup();\n }, autoCleanupMs);\n }\n }\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n this.setWithTTL(key, value, this.ttlMs);\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const now = Date.now();\n const expiresAt = now + ttlMs;\n\n if (this.cache.has(key)) {\n this.cache.delete(key); // remove old entry to maintain LRU order\n }\n\n this.cache.set(key, { value, expiresAt, lastAccessed: now });\n\n if (this.maxSize && this.cache.size > this.maxSize) {\n this.evictLRU();\n }\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n\n // Update lastAccessed and move key to the end (most recently used)\n entry.lastAccessed = now;\n // Re-insert to end of Map to maintain LRU order\n this.cache.delete(key);\n this.cache.set(key, entry);\n\n return entry.value;\n }\n\n /**\n * Retrieves or computes a value if it's not in the cache or has expired.\n *\n * @param key - The key to retrieve\n * @param producer - Function to generate the value if not cached\n * @param ttlMs - Optional custom TTL for the computed value\n * @returns The cached or computed value\n */\n async getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V> {\n const value = this.get(key);\n if (value !== undefined) return value;\n\n const newValue = await producer();\n this.setWithTTL(key, newValue, ttlMs ?? this.ttlMs);\n return newValue;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Set multiple key-value pairs at once with the default TTL.\n *\n * @param entries - Array of [key, value] tuples to set\n */\n setMany(entries: [K, V][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get multiple values at once.\n *\n * @param keys - Array of keys to retrieve\n * @returns Array of values (undefined for keys that don't exist or expired)\n */\n getMany(keys: K[]): (V | undefined)[] {\n return keys.map(key => this.get(key));\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n\n /**\n * Extends the expiration of a key by the specified time or default TTL.\n *\n * @param key - The key to refresh\n * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)\n * @returns true if the key was found and refreshed, false otherwise\n */\n refresh(key: K, ttlMs?: number): boolean {\n const entry = this.cache.get(key);\n if (!entry) return false;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return false;\n }\n\n entry.expiresAt = now + (ttlMs ?? this.ttlMs);\n entry.lastAccessed = now;\n return true;\n }\n\n /**\n * Returns a snapshot of cache stats.\n *\n * @returns Object containing cache statistics\n */\n stats() {\n const now = Date.now();\n let expired = 0;\n let valid = 0;\n\n for (const entry of this.cache.values()) {\n if (now > entry.expiresAt) {\n expired++;\n } else {\n valid++;\n }\n }\n\n return {\n size: this.cache.size,\n validEntries: valid,\n expiredEntries: expired,\n maxSize: this.maxSize\n };\n }\n\n /**\n * Stop the auto-cleanup interval if it's running.\n */\n destroy() {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n\n /**\n * Evict the least recently used entry from the cache.\n * @private\n */\n private evictLRU(): void {\n const now = Date.now();\n\n // Remove all expired items first\n for (const [key, entry] of Array.from(this.cache.entries())) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n }\n }\n\n // Evict oldest entries until within max size\n while (this.maxSize && this.cache.size > this.maxSize) {\n const oldestKey = this.cache.keys().next().value;\n this.cache.delete(oldestKey as K);\n }\n }\n}\n"]}
|
|
@@ -41,7 +41,7 @@ export declare function getFromContext<T>(key: symbol): T | undefined;
|
|
|
41
41
|
* app.use((req, res, next) => {
|
|
42
42
|
* const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
|
|
43
43
|
* ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
44
|
-
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({
|
|
44
|
+
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
|
|
45
45
|
* next();
|
|
46
46
|
* });
|
|
47
47
|
* });
|
|
@@ -43,7 +43,7 @@ function getFromContext(key) {
|
|
|
43
43
|
* app.use((req, res, next) => {
|
|
44
44
|
* const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
|
|
45
45
|
* ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
46
|
-
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({
|
|
46
|
+
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
|
|
47
47
|
* next();
|
|
48
48
|
* });
|
|
49
49
|
* });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils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AAE,CAAC,CAAC,EAAE,CAAC;QAC9G,OAAO,CAAC,GAAQ,EAAE,GAAQ,EAAE,IAAS,EAAE,EAAE;YACvC,MAAM,aAAa,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;YAChD,YAAY,CAAC,GAAG,CAAC,aAAsB,EAAE,IAAI,CAAC,CAAC;QACjD,CAAC,CAAC;IACJ,CAAC;;AAlLH,oCAmLC;AAlLC;;;GAGG;AACqB,oBAAO,GAAG,IAAI,+BAAiB,EAAS,CAAC;AAgLnE;;;;GAIG;AACH,MAAa,eAAe;IAC1B;;;;;OAKG;IACH,YACU,MAAc,EACd,YAAgB;QADhB,WAAM,GAAN,MAAM,CAAQ;QACd,iBAAY,GAAZ,YAAY,CAAI;IACvB,CAAC;IAEJ;;;;OAIG;IACH,GAAG;QACD,MAAM,KAAK,GAAG,YAAY,CAAC,GAAG,CAAI,IAAI,CAAC,MAAM,CAAC,CAAC;QAC/C,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC;IACzD,CAAC;IAED;;;;OAIG;IACH,GAAG,CAAC,KAAQ;QACV,YAAY,CAAC,GAAG,CAAI,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;CACF;AAhDD,0CAgDC","sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol('logger'),\n REQUEST_ID: Symbol('requestId'),\n USER_ID: Symbol('userId'),\n TENANT_ID: Symbol('tenantId'),\n TRACE_ID: Symbol('traceId'),\n CORRELATION_ID: Symbol('correlationId')\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * Type-safe getter for common context values.\n *\n * @param key The store key symbol\n * @returns The typed value from the store\n */\nexport function getFromContext<T>(key: symbol): T | undefined {\n return ContextStore.get<T>(key);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n\n /**\n * Checks if a key exists in the current context store.\n *\n * @param {symbol} key - The symbol key to check.\n * @returns {boolean} True if the key exists, false otherwise.\n */\n static has(key: symbol): boolean {\n const store = this.storage.getStore();\n return store !== undefined && key in store;\n }\n\n /**\n * Removes a value from the current context store by symbol key.\n *\n * @param {symbol} key - The symbol key to delete.\n * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.\n * @throws {Error} If called outside an active context.\n */\n static delete(key: symbol): boolean {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n return delete store[key];\n }\n\n /**\n * Updates multiple values in the current context store at once.\n *\n * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.\n * @throws {Error} If called outside an active context.\n */\n static patch(values: Partial<Record<symbol, unknown>>): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');\n }\n Object.getOwnPropertySymbols(values).forEach(key => {\n store[key] = values[key];\n });\n }\n /**\n * Executes a callback with a temporary store value that only exists during execution.\n * Original store is restored after callback completes.\n *\n * @typeParam T - The callback's return type.\n * @param {symbol} key - The symbol key to temporarily set.\n * @param {unknown} value - The temporary value.\n * @param {() => T} callback - The function to execute with the temporary value.\n * @returns {T} The result of the callback function.\n * @throws {Error} If called outside an active context.\n */\n static withValue<T>(key: symbol, value: unknown, callback: () => T): T {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);\n }\n\n // Save original value\n const hasOriginal = key in store;\n const originalValue = store[key];\n\n // Set temporary value\n store[key] = value;\n\n try {\n // Run callback\n return callback();\n } finally {\n // Restore original value\n if (hasOriginal) {\n store[key] = originalValue;\n } else {\n delete store[key];\n }\n }\n }\n\n /**\n * Creates a new context that inherits values from the current context.\n *\n * @typeParam T - The callback's return type.\n * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.\n * @param {() => T} callback - The function to execute in the new context.\n * @returns {T} The result of the callback function.\n */\n static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T {\n const currentStore = this.storage.getStore() || {};\n\n // Create new store with current values plus new ones\n const newStore: Store = { ...currentStore };\n\n // Add new values\n Object.getOwnPropertySymbols(newValues).forEach(key => {\n newStore[key] = newValues[key];\n });\n\n // Run with extended store\n return this.storage.run(newStore, callback);\n }\n\n /**\n * Creates Express middleware that initializes a context for each request.\n *\n * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.\n * @returns Express middleware function.\n */\n static createExpressMiddleware(initialValuesFactory: (req: any) => Partial<Record<symbol, unknown>> = () => ({})) {\n return (req: any, res: any, next: any) => {\n const initialValues = initialValuesFactory(req);\n ContextStore.run(initialValues as Store, next);\n };\n }\n}\n\n/**\n * Type-safe wrapper for accessing and modifying context values with specific types.\n *\n * @typeParam T - The value type.\n */\nexport class TypedContextKey<T> {\n /**\n * Creates a new typed context key.\n *\n * @param symbol - The unique symbol for this key\n * @param defaultValue - Optional default value if key is not found\n */\n constructor(\n private symbol: symbol,\n private defaultValue?: T\n ) {}\n\n /**\n * Gets the current value for this key.\n *\n * @returns The value or defaultValue if not found\n */\n get(): T | undefined {\n const value = ContextStore.get<T>(this.symbol);\n return value !== undefined ? value : this.defaultValue;\n }\n\n /**\n * Sets the value for this key.\n *\n * @param value The value to set\n */\n set(value: T): void {\n ContextStore.set<T>(this.symbol, value);\n }\n\n /**\n * Checks if this key exists in the context.\n *\n * @returns True if the key exists\n */\n exists(): boolean {\n return ContextStore.has(this.symbol);\n }\n\n /**\n * Deletes this key from the context.\n *\n * @returns True if the key was deleted\n */\n delete(): boolean {\n return ContextStore.delete(this.symbol);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":";;;AA4BA,oCAEC;AAQD,wCAEC;AAxCD,6CAAgD;AAUhD;;;GAGG;AACU,QAAA,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC,UAAU,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC,eAAe,CAAC;CACxC,CAAC;AAEF;;;;GAIG;AACH,SAAgB,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,iBAAS,CAAC,UAAU,CAAC,CAAC;AACxD,CAAC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAAI,GAAW;IAC3C,OAAO,YAAY,CAAC,GAAG,CAAI,GAAG,CAAC,CAAC;AAClC,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAa,YAAY;IAOvB;;;;OAIG;IACH,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,GAAG,CAAI,GAAW;QACvB,MAAM,KAAK,GAAG,IAAI,CAAC,OAA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ACH,MAAM;QACJ,OAAO,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,OAAO,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;CACF;AAhDD,0CAgDC","sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol('logger'),\n REQUEST_ID: Symbol('requestId'),\n USER_ID: Symbol('userId'),\n TENANT_ID: Symbol('tenantId'),\n TRACE_ID: Symbol('traceId'),\n CORRELATION_ID: Symbol('correlationId')\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * Type-safe getter for common context values.\n *\n * @param key The store key symbol\n * @returns The typed value from the store\n */\nexport function getFromContext<T>(key: symbol): T | undefined {\n return ContextStore.get<T>(key);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n\n /**\n * Checks if a key exists in the current context store.\n *\n * @param {symbol} key - The symbol key to check.\n * @returns {boolean} True if the key exists, false otherwise.\n */\n static has(key: symbol): boolean {\n const store = this.storage.getStore();\n return store !== undefined && key in store;\n }\n\n /**\n * Removes a value from the current context store by symbol key.\n *\n * @param {symbol} key - The symbol key to delete.\n * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.\n * @throws {Error} If called outside an active context.\n */\n static delete(key: symbol): boolean {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n return delete store[key];\n }\n\n /**\n * Updates multiple values in the current context store at once.\n *\n * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.\n * @throws {Error} If called outside an active context.\n */\n static patch(values: Partial<Record<symbol, unknown>>): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');\n }\n Object.getOwnPropertySymbols(values).forEach(key => {\n store[key] = values[key];\n });\n }\n /**\n * Executes a callback with a temporary store value that only exists during execution.\n * Original store is restored after callback completes.\n *\n * @typeParam T - The callback's return type.\n * @param {symbol} key - The symbol key to temporarily set.\n * @param {unknown} value - The temporary value.\n * @param {() => T} callback - The function to execute with the temporary value.\n * @returns {T} The result of the callback function.\n * @throws {Error} If called outside an active context.\n */\n static withValue<T>(key: symbol, value: unknown, callback: () => T): T {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);\n }\n\n // Save original value\n const hasOriginal = key in store;\n const originalValue = store[key];\n\n // Set temporary value\n store[key] = value;\n\n try {\n // Run callback\n return callback();\n } finally {\n // Restore original value\n if (hasOriginal) {\n store[key] = originalValue;\n } else {\n delete store[key];\n }\n }\n }\n\n /**\n * Creates a new context that inherits values from the current context.\n *\n * @typeParam T - The callback's return type.\n * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.\n * @param {() => T} callback - The function to execute in the new context.\n * @returns {T} The result of the callback function.\n */\n static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T {\n const currentStore = this.storage.getStore() || {};\n\n // Create new store with current values plus new ones\n const newStore: Store = { ...currentStore };\n\n // Add new values\n Object.getOwnPropertySymbols(newValues).forEach(key => {\n newStore[key] = newValues[key];\n });\n\n // Run with extended store\n return this.storage.run(newStore, callback);\n }\n\n /**\n * Creates Express middleware that initializes a context for each request.\n *\n * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.\n * @returns Express middleware function.\n */\n static createExpressMiddleware(initialValuesFactory: (req: any) => Partial<Record<symbol, unknown>> = () => ({})) {\n return (req: any, res: any, next: any) => {\n const initialValues = initialValuesFactory(req);\n ContextStore.run(initialValues as Store, next);\n };\n }\n}\n\n/**\n * Type-safe wrapper for accessing and modifying context values with specific types.\n *\n * @typeParam T - The value type.\n */\nexport class TypedContextKey<T> {\n /**\n * Creates a new typed context key.\n *\n * @param symbol - The unique symbol for this key\n * @param defaultValue - Optional default value if key is not found\n */\n constructor(\n private symbol: symbol,\n private defaultValue?: T\n ) {}\n\n /**\n * Gets the current value for this key.\n *\n * @returns The value or defaultValue if not found\n */\n get(): T | undefined {\n const value = ContextStore.get<T>(this.symbol);\n return value !== undefined ? value : this.defaultValue;\n }\n\n /**\n * Sets the value for this key.\n *\n * @param value The value to set\n */\n set(value: T): void {\n ContextStore.set<T>(this.symbol, value);\n }\n\n /**\n * Checks if this key exists in the context.\n *\n * @returns True if the key exists\n */\n exists(): boolean {\n return ContextStore.has(this.symbol);\n }\n\n /**\n * Deletes this key from the context.\n *\n * @returns True if the key was deleted\n */\n delete(): boolean {\n return ContextStore.delete(this.symbol);\n }\n}\n"]}
|
|
@@ -17,6 +17,7 @@ exports.createSignedToken = createSignedToken;
|
|
|
17
17
|
exports.verifySignedToken = verifySignedToken;
|
|
18
18
|
const crypto_1 = require("crypto");
|
|
19
19
|
const util_1 = require("util");
|
|
20
|
+
const id_utils_1 = require("./id.utils");
|
|
20
21
|
/**
|
|
21
22
|
* Generates an HMAC digest using the specified algorithm and secret key.
|
|
22
23
|
*
|
|
@@ -85,7 +86,7 @@ function md5(input) {
|
|
|
85
86
|
* @returns {string} Random string hashed with SHA-256 (hex encoding).
|
|
86
87
|
*/
|
|
87
88
|
function randomString() {
|
|
88
|
-
return sha256((0,
|
|
89
|
+
return sha256((0, id_utils_1.uuid)());
|
|
89
90
|
}
|
|
90
91
|
/**
|
|
91
92
|
* Generates a secure random buffer of specified byte length.
|