@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":";;AAsCA,4CA0BC;AASD,8CAiCC;AAWD,0DAoBC;AAUD,8CAmCC;AASD,kDAcC;AA9KD;;;;;;GAMG;AACH,SAAgB,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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,KAAK,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,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"]}
|
|
@@ -5,8 +5,8 @@ exports.createSuccessResponse = createSuccessResponse;
|
|
|
5
5
|
exports.createErrorResponse = createErrorResponse;
|
|
6
6
|
exports.createPaginatedResponse = createPaginatedResponse;
|
|
7
7
|
exports.sendResponse = sendResponse;
|
|
8
|
-
const crypto_1 = require("crypto");
|
|
9
8
|
const context_store_utils_1 = require("./context-store.utils");
|
|
9
|
+
const id_utils_1 = require("./id.utils");
|
|
10
10
|
/**
|
|
11
11
|
* Standard HTTP response wrapper for successful responses.
|
|
12
12
|
* Implements the `ApiResponse<T>` interface and sets default values.
|
|
@@ -31,7 +31,7 @@ class SuccessResponse {
|
|
|
31
31
|
/** Timestamp when the response was generated, in ISO format. */
|
|
32
32
|
this.timestamp = new Date().toISOString();
|
|
33
33
|
/** Unique identifier for this response, useful for request tracing. */
|
|
34
|
-
this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0,
|
|
34
|
+
this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0, id_utils_1.uuid)();
|
|
35
35
|
if (message)
|
|
36
36
|
this.message = message;
|
|
37
37
|
this.data = data !== null && data !== void 0 ? data : null;
|
|
@@ -57,7 +57,7 @@ class ErrorResponse extends Error {
|
|
|
57
57
|
/** Timestamp when the error occurred, in ISO format. */
|
|
58
58
|
this.timestamp = new Date().toISOString();
|
|
59
59
|
/** Unique identifier for this error instance. */
|
|
60
|
-
this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0,
|
|
60
|
+
this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0, id_utils_1.uuid)();
|
|
61
61
|
this.status = status;
|
|
62
62
|
this.name = this.constructor.name;
|
|
63
63
|
Error.captureStackTrace(this, this.constructor);
|
|
@@ -121,7 +121,7 @@ class RedirectResponse {
|
|
|
121
121
|
/** Whether the response is a redirect */
|
|
122
122
|
this.isRedirect = true;
|
|
123
123
|
/** Unique identifier for this response */
|
|
124
|
-
this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0,
|
|
124
|
+
this.requestId = (_a = (0, context_store_utils_1.getRequestId)()) !== null && _a !== void 0 ? _a : (0, id_utils_1.uuid)();
|
|
125
125
|
this.redirectUrl = url;
|
|
126
126
|
this.statusCode = statusCode;
|
|
127
127
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file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,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":";;;AAuKA,sDAEC;AASD,kDAEC;AAYD,0DA0BC;AAQD,oCA6BC;AA9PD,+DAAqD;AACrD,yCAAkC;AAElC;;;;;GAKG;AACH,MAAa,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,IAAA,kCAAY,GAAE,mCAAI,IAAA,eAAI,GAAE,CAAC;QAS3C,IAAI,OAAO;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACpC,I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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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@catbee/utils",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
4
4
|
"main": "build/src/index.js",
|
|
5
5
|
"module": "build/esm/index.js",
|
|
6
6
|
"esnext": "build/esnext/index.js",
|
|
@@ -13,8 +13,9 @@
|
|
|
13
13
|
},
|
|
14
14
|
"license": "Apache-2.0",
|
|
15
15
|
"scripts": {
|
|
16
|
+
"start": "node build/src/index.js",
|
|
16
17
|
"prepack": "npm run compile",
|
|
17
|
-
"compile": "npm run clean && tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json",
|
|
18
|
+
"compile": "npm run clean && tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json && npm run generate:exports",
|
|
18
19
|
"clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json",
|
|
19
20
|
"lint": "eslint src tests",
|
|
20
21
|
"lint:fix": "eslint --fix src tests",
|
|
@@ -23,7 +24,9 @@
|
|
|
23
24
|
"dryrun": "npm pack --dry-run",
|
|
24
25
|
"test": "cross-env LOGGER_LEVEL=silent jest",
|
|
25
26
|
"test:coverage": "cross-env LOGGER_LEVEL=silent jest --coverage",
|
|
26
|
-
"
|
|
27
|
+
"coverage": "npm run test:coverage",
|
|
28
|
+
"test:debug": "cross-env LOGGER_LEVEL=info jest",
|
|
29
|
+
"generate:exports": "node scripts/generate-exports.mjs"
|
|
27
30
|
},
|
|
28
31
|
"keywords": [
|
|
29
32
|
"utils",
|
|
@@ -46,15 +49,15 @@
|
|
|
46
49
|
"catbee"
|
|
47
50
|
],
|
|
48
51
|
"dependencies": {
|
|
49
|
-
"
|
|
50
|
-
"pino": "^9.7.0",
|
|
51
|
-
"reflect-metadata": "^0.2.2"
|
|
52
|
+
"pino": "^9.7.0"
|
|
52
53
|
},
|
|
53
54
|
"devDependencies": {
|
|
55
|
+
"@types/express": "^5.0.3",
|
|
54
56
|
"@types/jest": "^30.0.0",
|
|
55
57
|
"@types/node": "^24.2.0",
|
|
56
58
|
"@typescript-eslint/eslint-plugin": "^8.39.0",
|
|
57
59
|
"@typescript-eslint/parser": "^8.39.0",
|
|
60
|
+
"abort-controller": "^3.0.0",
|
|
58
61
|
"cross-env": "^10.0.0",
|
|
59
62
|
"eslint": "^9.32.0",
|
|
60
63
|
"eslint-config-prettier": "^10.1.8",
|
|
@@ -64,7 +67,9 @@
|
|
|
64
67
|
"jest": "^30.0.5",
|
|
65
68
|
"jest-junit": "^16.0.0",
|
|
66
69
|
"jest-sonar-reporter": "^2.0.0",
|
|
70
|
+
"pino-pretty": "^13.1.1",
|
|
67
71
|
"prettier": "^3.6.2",
|
|
72
|
+
"reflect-metadata": "^0.2.2",
|
|
68
73
|
"ts-jest": "^29.4.1",
|
|
69
74
|
"typescript": "^5.9.2",
|
|
70
75
|
"typescript-eslint": "^8.39.0"
|