@catbee/utils 0.0.4 → 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 -242
- package/build/esm/config.d.ts +20 -5
- package/build/esm/config.js +26 -6
- 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 +291 -0
- 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/logger.utils.d.ts +107 -0
- package/build/esm/utils/logger.utils.js +207 -14
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +27 -7
- package/build/esm/utils/middleware.utils.js +25 -9
- 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 +20 -5
- package/build/esnext/config.js +26 -6
- 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 +291 -0
- 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/logger.utils.d.ts +107 -0
- package/build/esnext/utils/logger.utils.js +178 -14
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +27 -7
- package/build/esnext/utils/middleware.utils.js +25 -9
- 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 +20 -5
- package/build/src/config.js +29 -7
- 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 +291 -0
- 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/logger.utils.d.ts +107 -0
- package/build/src/utils/logger.utils.js +184 -14
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +27 -7
- package/build/src/utils/middleware.utils.js +24 -8
- 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 +12 -7
|
@@ -5,7 +5,6 @@ exports.responseTime = responseTime;
|
|
|
5
5
|
exports.timeout = timeout;
|
|
6
6
|
exports.setupRequestContext = setupRequestContext;
|
|
7
7
|
exports.errorHandler = errorHandler;
|
|
8
|
-
const crypto_1 = require("crypto");
|
|
9
8
|
const config_1 = require("../config");
|
|
10
9
|
const id_utils_1 = require("./id.utils");
|
|
11
10
|
const http_status_codes_1 = require("./http-status-codes");
|
|
@@ -28,7 +27,7 @@ function requestId(options) {
|
|
|
28
27
|
return (req, res, next) => {
|
|
29
28
|
// Use existing request ID from header or generate a new one
|
|
30
29
|
const existingId = req.headers[headerName.toLowerCase()];
|
|
31
|
-
const id = existingId || (0,
|
|
30
|
+
const id = existingId || (0, id_utils_1.uuid)();
|
|
32
31
|
// Attach ID to request object
|
|
33
32
|
req.id = id;
|
|
34
33
|
// Add ID to response headers
|
|
@@ -78,7 +77,7 @@ function responseTime(options) {
|
|
|
78
77
|
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
|
|
79
78
|
* @returns {Middleware} Express-compatible middleware
|
|
80
79
|
*/
|
|
81
|
-
function timeout(timeoutMs = config_1.
|
|
80
|
+
function timeout(timeoutMs = config_1.config.http.timeout) {
|
|
82
81
|
return (req, res, next) => {
|
|
83
82
|
// Set timeout for the request
|
|
84
83
|
const timer = setTimeout(() => {
|
|
@@ -108,11 +107,11 @@ function setupRequestContext(options = {}) {
|
|
|
108
107
|
const { headerName = 'x-request-id', autoLog = true } = options;
|
|
109
108
|
return (req, _res, next) => {
|
|
110
109
|
// Generate or use existing request ID
|
|
111
|
-
const requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) ||
|
|
110
|
+
const requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || (0, id_utils_1.uuid)();
|
|
112
111
|
context_store_utils_1.ContextStore.run({ [context_store_utils_1.StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
113
112
|
// Create a child logger for this request
|
|
114
113
|
const childLogger = (0, logger_utils_1.getLogger)().child({
|
|
115
|
-
|
|
114
|
+
requestId,
|
|
116
115
|
method: req.method,
|
|
117
116
|
url: req.originalUrl || req.url
|
|
118
117
|
});
|
|
@@ -128,11 +127,28 @@ function setupRequestContext(options = {}) {
|
|
|
128
127
|
/**
|
|
129
128
|
* Global error handling middleware with enhanced features.
|
|
130
129
|
*
|
|
131
|
-
* @param {
|
|
130
|
+
* @param {ErrorHandlerOptions} options - Error handler options
|
|
132
131
|
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
133
132
|
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
134
|
-
* @
|
|
135
|
-
*
|
|
133
|
+
* @returns Error middleware
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* import express from 'express';
|
|
137
|
+
* import { errorHandler } from '@catbee/utils';
|
|
138
|
+
*
|
|
139
|
+
* const app = express();
|
|
140
|
+
*
|
|
141
|
+
* // Your routes
|
|
142
|
+
* app.get('/ping', (req, res) => {
|
|
143
|
+
* throw new Error('Something went wrong');
|
|
144
|
+
* });
|
|
145
|
+
*
|
|
146
|
+
* // Error handler (must be last middleware)
|
|
147
|
+
* app.use(errorHandler({ includeDetails: true }));
|
|
148
|
+
*
|
|
149
|
+
* app.listen(3000, () => {
|
|
150
|
+
* console.log('Server running on port 3000');
|
|
151
|
+
* });
|
|
136
152
|
*/
|
|
137
153
|
function errorHandler(options) {
|
|
138
154
|
const logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
|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,CAAC,CAAC,IAAI,CAC5B,mBAAmB,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,GAAG,EAAE;YACrE,cAAc;SACf,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from 'crypto';\nimport { Config } from '../config';\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ErrorResponse } from './response.utils';\nimport { Env } from './env.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: { headerName?: string; exposeHeader?: boolean }): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n (req as any).id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n if (addHeader) {\n // Wrap res.end to set header just before sending response\n const originalEnd = res.end;\n res.end = function (chunk?: any, encoding?: any, cb?: any) {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n return originalEnd.call(this, chunk, encoding, cb);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n getLogger().info(`${req.method} ${req.url} - ${duration.toFixed(2)}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: 'Request timeout',\n status: 408,\n timestamp: new Date().toISOString()\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || crypto.randomUUID();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n reqId: requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n childLogger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: { logErrors?: boolean; includeDetails?: boolean }) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ error: err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n });\n }\n\n const createErrorResponse = (message: string, req: Request, error: any, options?: { includeDetails?: boolean }) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n };\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || 'Internal Server Error', req, err, {\n includeDetails\n })\n );\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":";;AAoBA,8BAmBC;AAUD,oCA4BC;AASD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AAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { config } from '../config';\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ErrorResponse } from './response.utils';\nimport { Env } from './env.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: { headerName?: string; exposeHeader?: boolean }): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || uuid();\n\n // Attach ID to request object\n (req as any).id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n if (addHeader) {\n // Wrap res.end to set header just before sending response\n const originalEnd = res.end;\n res.end = function (chunk?: any, encoding?: any, cb?: any) {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n return originalEnd.call(this, chunk, encoding, cb);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n getLogger().info(`${req.method} ${req.url} - ${duration.toFixed(2)}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = config.http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: 'Request timeout',\n status: 408,\n timestamp: new Date().toISOString()\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || uuid();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n childLogger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\nexport interface ErrorHandlerOptions {\n /** Whether to log errors (default: true) */\n logErrors?: boolean;\n /** Whether to include error details in non-production (default: false) */\n includeDetails?: boolean;\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {ErrorHandlerOptions} options - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns Error middleware\n *\n * @example\n * import express from 'express';\n * import { errorHandler } from '@catbee/utils';\n *\n * const app = express();\n *\n * // Your routes\n * app.get('/ping', (req, res) => {\n * throw new Error('Something went wrong');\n * });\n *\n * // Error handler (must be last middleware)\n * app.use(errorHandler({ includeDetails: true }));\n *\n * app.listen(3000, () => {\n * console.log('Server running on port 3000');\n * });\n */\nexport function errorHandler(options?: ErrorHandlerOptions) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ error: err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n });\n }\n\n const createErrorResponse = (message: string, req: Request, error: any, options?: { includeDetails?: boolean }) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n };\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || 'Internal Server Error', req, err, {\n includeDetails\n })\n );\n };\n}\n"]}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for parsing and validating request parameters.
|
|
3
|
+
*/
|
|
4
|
+
export interface ValidationOptions {
|
|
5
|
+
/** Whether to throw an error on validation failure */
|
|
6
|
+
throwOnError?: boolean;
|
|
7
|
+
/** Custom error message for validation failures */
|
|
8
|
+
errorMessage?: string;
|
|
9
|
+
/** Default value to use if parameter is missing */
|
|
10
|
+
defaultValue?: any;
|
|
11
|
+
/** Whether the parameter is required */
|
|
12
|
+
required?: boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Result of a parameter validation operation.
|
|
16
|
+
*/
|
|
17
|
+
export interface ValidationResult<T> {
|
|
18
|
+
/** Whether validation was successful */
|
|
19
|
+
isValid: boolean;
|
|
20
|
+
/** The validated and potentially transformed value */
|
|
21
|
+
value: T | null;
|
|
22
|
+
/** Error message if validation failed */
|
|
23
|
+
error?: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Safely parses a string parameter to a number.
|
|
27
|
+
*
|
|
28
|
+
* @param value - String value to parse
|
|
29
|
+
* @param options - Validation options
|
|
30
|
+
* @returns Validation result containing the parsed number or error
|
|
31
|
+
*/
|
|
32
|
+
export declare function parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>;
|
|
33
|
+
/**
|
|
34
|
+
* Safely parses a string parameter to a boolean.
|
|
35
|
+
*
|
|
36
|
+
* @param value - String value to parse
|
|
37
|
+
* @param options - Validation options
|
|
38
|
+
* @returns Validation result containing the parsed boolean or error
|
|
39
|
+
*/
|
|
40
|
+
export declare function parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>;
|
|
41
|
+
/**
|
|
42
|
+
* Extracts pagination parameters from request query parameters.
|
|
43
|
+
*
|
|
44
|
+
* @param query - Query parameters object
|
|
45
|
+
* @param defaultPage - Default page number if not specified (defaults to 1)
|
|
46
|
+
* @param defaultLimit - Default per page size if not specified (defaults to 20)
|
|
47
|
+
* @param maxLimitSize - Maximum allowed per page size (defaults to 100)
|
|
48
|
+
* @returns Object containing validated page and limit
|
|
49
|
+
*/
|
|
50
|
+
export declare function extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): {
|
|
51
|
+
page: number;
|
|
52
|
+
limit: number;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Extracts sorting parameters from request query parameters.
|
|
56
|
+
*
|
|
57
|
+
* @param query - Query parameters object
|
|
58
|
+
* @param allowedFields - Array of field names that are allowed to be sorted
|
|
59
|
+
* @param defaultSort - Default sort configuration if not specified
|
|
60
|
+
* @returns Object containing sort field and direction
|
|
61
|
+
*/
|
|
62
|
+
export declare function extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?: {
|
|
63
|
+
sortBy: string;
|
|
64
|
+
sortOrder: 'asc' | 'desc';
|
|
65
|
+
}): {
|
|
66
|
+
sortBy: string;
|
|
67
|
+
sortOrder: 'asc' | 'desc';
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Extracts filter parameters from query parameters based on allowed filter fields.
|
|
71
|
+
*
|
|
72
|
+
* @param query - Query parameters object
|
|
73
|
+
* @param allowedFilters - Array of field names that are allowed to be used as filters
|
|
74
|
+
* @returns Object containing the filters as key-value pairs
|
|
75
|
+
*/
|
|
76
|
+
export declare function extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>;
|
|
77
|
+
//# sourceMappingURL=request.utils.d.ts.map
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseNumberParam = parseNumberParam;
|
|
4
|
+
exports.parseBooleanParam = parseBooleanParam;
|
|
5
|
+
exports.extractPaginationParams = extractPaginationParams;
|
|
6
|
+
exports.extractSortParams = extractSortParams;
|
|
7
|
+
exports.extractFilterParams = extractFilterParams;
|
|
8
|
+
/**
|
|
9
|
+
* Safely parses a string parameter to a number.
|
|
10
|
+
*
|
|
11
|
+
* @param value - String value to parse
|
|
12
|
+
* @param options - Validation options
|
|
13
|
+
* @returns Validation result containing the parsed number or error
|
|
14
|
+
*/
|
|
15
|
+
function parseNumberParam(value, options = {}) {
|
|
16
|
+
const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;
|
|
17
|
+
// Handle undefined case
|
|
18
|
+
if (value === undefined) {
|
|
19
|
+
if (required) {
|
|
20
|
+
const error = `Required number parameter is missing`;
|
|
21
|
+
if (throwOnError)
|
|
22
|
+
throw new Error(error);
|
|
23
|
+
return { isValid: false, value: null, error };
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
isValid: defaultValue !== undefined,
|
|
27
|
+
value: defaultValue !== undefined ? defaultValue : null,
|
|
28
|
+
error: defaultValue === undefined ? 'Missing parameter with no default' : undefined
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
// Parse and validate the number
|
|
32
|
+
const num = Number(value);
|
|
33
|
+
if (isNaN(num)) {
|
|
34
|
+
if (throwOnError)
|
|
35
|
+
throw new Error(errorMessage);
|
|
36
|
+
return { isValid: false, value: null, error: errorMessage };
|
|
37
|
+
}
|
|
38
|
+
return { isValid: true, value: num };
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Safely parses a string parameter to a boolean.
|
|
42
|
+
*
|
|
43
|
+
* @param value - String value to parse
|
|
44
|
+
* @param options - Validation options
|
|
45
|
+
* @returns Validation result containing the parsed boolean or error
|
|
46
|
+
*/
|
|
47
|
+
function parseBooleanParam(value, options = {}) {
|
|
48
|
+
const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;
|
|
49
|
+
// Handle undefined case
|
|
50
|
+
if (value === undefined) {
|
|
51
|
+
if (required) {
|
|
52
|
+
const error = `Required boolean parameter is missing`;
|
|
53
|
+
if (throwOnError)
|
|
54
|
+
throw new Error(error);
|
|
55
|
+
return { isValid: false, value: null, error };
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
isValid: defaultValue !== undefined,
|
|
59
|
+
value: defaultValue !== undefined ? defaultValue : null,
|
|
60
|
+
error: defaultValue === undefined ? 'Missing parameter with no default' : undefined
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
// Parse the boolean value with various allowed formats
|
|
64
|
+
const lowercaseValue = value.toLowerCase();
|
|
65
|
+
if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {
|
|
66
|
+
return { isValid: true, value: true };
|
|
67
|
+
}
|
|
68
|
+
if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {
|
|
69
|
+
return { isValid: true, value: false };
|
|
70
|
+
}
|
|
71
|
+
if (throwOnError)
|
|
72
|
+
throw new Error(errorMessage);
|
|
73
|
+
return { isValid: false, value: null, error: errorMessage };
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Extracts pagination parameters from request query parameters.
|
|
77
|
+
*
|
|
78
|
+
* @param query - Query parameters object
|
|
79
|
+
* @param defaultPage - Default page number if not specified (defaults to 1)
|
|
80
|
+
* @param defaultLimit - Default per page size if not specified (defaults to 20)
|
|
81
|
+
* @param maxLimitSize - Maximum allowed per page size (defaults to 100)
|
|
82
|
+
* @returns Object containing validated page and limit
|
|
83
|
+
*/
|
|
84
|
+
function extractPaginationParams(query, defaultPage = 1, defaultLimit = 20, maxLimitSize = 100) {
|
|
85
|
+
// Parse page parameter
|
|
86
|
+
const pageParam = typeof query.page === 'string' ? query.page : undefined;
|
|
87
|
+
const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });
|
|
88
|
+
// Parse limit parameter
|
|
89
|
+
const limitParam = typeof query.limit === 'string' ? query.limit : undefined;
|
|
90
|
+
const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });
|
|
91
|
+
// Ensure valid values (handle 0 → fallback to default)
|
|
92
|
+
const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;
|
|
93
|
+
const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;
|
|
94
|
+
return { page, limit };
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Extracts sorting parameters from request query parameters.
|
|
98
|
+
*
|
|
99
|
+
* @param query - Query parameters object
|
|
100
|
+
* @param allowedFields - Array of field names that are allowed to be sorted
|
|
101
|
+
* @param defaultSort - Default sort configuration if not specified
|
|
102
|
+
* @returns Object containing sort field and direction
|
|
103
|
+
*/
|
|
104
|
+
function extractSortParams(query, allowedFields, defaultSort = { sortBy: 'createdAt', sortOrder: 'desc' }) {
|
|
105
|
+
let sortBy = defaultSort.sortBy;
|
|
106
|
+
let sortOrder = defaultSort.sortOrder;
|
|
107
|
+
// Extract from `sortBy` or `sort`
|
|
108
|
+
if (typeof query.sortBy === 'string') {
|
|
109
|
+
sortBy = query.sortBy;
|
|
110
|
+
}
|
|
111
|
+
else if (Array.isArray(query.sortBy)) {
|
|
112
|
+
sortBy = query.sortBy[0];
|
|
113
|
+
}
|
|
114
|
+
else if (typeof query.sort === 'string') {
|
|
115
|
+
sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;
|
|
116
|
+
sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';
|
|
117
|
+
}
|
|
118
|
+
else if (Array.isArray(query.sort)) {
|
|
119
|
+
sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];
|
|
120
|
+
sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';
|
|
121
|
+
}
|
|
122
|
+
// Explicit sortOrder (overrides inferred one if valid)
|
|
123
|
+
if (typeof query.sortOrder === 'string') {
|
|
124
|
+
const order = query.sortOrder.toLowerCase();
|
|
125
|
+
if (order === 'asc' || order === 'desc') {
|
|
126
|
+
sortOrder = order;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// Validate field
|
|
130
|
+
if (!allowedFields.includes(sortBy)) {
|
|
131
|
+
sortBy = defaultSort.sortBy;
|
|
132
|
+
}
|
|
133
|
+
return { sortBy, sortOrder };
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Extracts filter parameters from query parameters based on allowed filter fields.
|
|
137
|
+
*
|
|
138
|
+
* @param query - Query parameters object
|
|
139
|
+
* @param allowedFilters - Array of field names that are allowed to be used as filters
|
|
140
|
+
* @returns Object containing the filters as key-value pairs
|
|
141
|
+
*/
|
|
142
|
+
function extractFilterParams(query, allowedFilters) {
|
|
143
|
+
const filters = {};
|
|
144
|
+
// Find filter parameters in the query
|
|
145
|
+
for (const field of allowedFilters) {
|
|
146
|
+
if (field in query) {
|
|
147
|
+
filters[field] = query[field];
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return filters;
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=request.utils.js.map
|
|
@@ -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,CA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AG,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,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Aa,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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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/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",
|
|
@@ -22,7 +23,10 @@
|
|
|
22
23
|
"pretest": "npm run compile",
|
|
23
24
|
"dryrun": "npm pack --dry-run",
|
|
24
25
|
"test": "cross-env LOGGER_LEVEL=silent jest",
|
|
25
|
-
"test:coverage": "cross-env LOGGER_LEVEL=silent jest --coverage"
|
|
26
|
+
"test:coverage": "cross-env LOGGER_LEVEL=silent jest --coverage",
|
|
27
|
+
"coverage": "npm run test:coverage",
|
|
28
|
+
"test:debug": "cross-env LOGGER_LEVEL=info jest",
|
|
29
|
+
"generate:exports": "node scripts/generate-exports.mjs"
|
|
26
30
|
},
|
|
27
31
|
"keywords": [
|
|
28
32
|
"utils",
|
|
@@ -45,16 +49,15 @@
|
|
|
45
49
|
"catbee"
|
|
46
50
|
],
|
|
47
51
|
"dependencies": {
|
|
48
|
-
"
|
|
49
|
-
"abort-controller": "^3.0.0",
|
|
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"
|