@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AA8B3C;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,OAAyD;IACjF,IAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,IAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IAErD,OAAO,UAAC,GAAG,EAAE,GAAG,EAAE,IAAI;QACpB,4DAA4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AAG,CAAE,UAAU,CAAA,IAAI,eAAe,CAAC,qBAAqB,CAAC;QAEvF,uBAAuB;QACvB,IAAI,SAAS,EAAE,CAAC;YACd,IAAM,UAAU,GAAG,kBAAW,GAAG,CAAC,MAAM,cAAI,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG,eAAK,GAAG,CAAC,OAAO,IAAI,eAAe,CAAE,CAAC;YAC5G,MAAM,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAC1B,CAAC;QAED,0DAA0D;QAC1D,IAAI,GAAG,YAAY,aAAa,EAAE,CAAC;YACjC,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;gBAC7B,KAAK,EAAE,GAAG,CAAC,KAAK;gBAChB,OAAO,EAAE,GAAG,CAAC,OAAO;gBACpB,SAAS,EAAE,GAAG,CAAC,SAAS;gBACxB,SAAS,EAAE,GAAG,CAAC,SAAS,IAAI,GAAG,CAAC,EAAE,IAAI,IAAI,EAAE;gBAC5C,IAAI,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC,CAAC;QACL,CAAC;QAED,0BAA0B;QAC1B,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAC5B,mBAAmB,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,GAAG,EAAE;YACrE,cAAc,gBAAA;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';\n\n/**\n * Type definitions for Express-compatible middleware\n */\ntype Request = {\n headers: Record<string, string | string[] | undefined>;\n method: string;\n url: string;\n ip?: string;\n body?: any;\n query?: Record<string, any>;\n params?: Record<string, any>;\n [key: string]: any;\n};\n\ntype Response = {\n status: (code: number) => Response;\n json: (data: any) => void;\n send: (data: any) => void;\n setHeader: (name: string, value: string | string[]) => void;\n end: (data?: any) => void;\n on: (event: string, callback: (...args: any[]) => void) => void;\n [key: string]: any;\n};\n\ntype NextFunction = (err?: Error | any) => void;\n\ntype 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.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 }): Middleware {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req, res, next) => {\n const start = process.hrtime();\n\n // Function to calculate elapsed time\n const calculateDuration = (): number => {\n const diff = process.hrtime(start);\n return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms\n };\n\n // Handle response completion\n res.on('finish', () => {\n const duration = calculateDuration();\n\n if (addHeader) {\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n }\n\n if (logOnComplete) {\n const { method, url } = req;\n getLogger().info(`${method} ${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 a standardized error response object for API errors.\n *\n * @param {string} message - Error message\n * @param {Request} req - Express request object\n * @param {any} error - Original error object\n * @param {object} [options] - Additional options\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns {object} Formatted error response\n */\nconst 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.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/**\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?: {\n logErrors?: boolean;\n includeDetails?: boolean;\n logger?: (message: string, error: any) => void;\n}) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n const logger = options?.logger || getLogger().error;\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 const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || 'Unknown error'}`;\n logger(logMessage, err);\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.id || uuid(),\n path: req.originalUrl || req.url\n });\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":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAIhE;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,OAAyD;IACjF,IAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,IAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IAErD,OAAO,UAAC,GAAG,EAAE,GAAG,EA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IAAI,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC;YAEF,gCAAgC;YAChC,IAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,EAAE,CAAC;gBAChB,QAAQ,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;YAC7B,CAAC;YAED,uDAAuD;YACvD,IAAI,cAAc,KAAI,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,KAAK,CAAA,EAAE,CAAC;gBACnC,QAAQ,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,UAAC,IAAY,IAAK,OAAA,IAAI,CAAC,IAAI,EAAE,EAAX,CAAW,CAAC,CAAC;YAC9E,CAAC;YAED,OAAO,QAAQ,CAAC;QAClB,CAAC,CAAC;QAEF,0BAA0B;QAC1B,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAC5B,mBAAmB,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,GAAG,EAAE;YACrE,cAAc,gBAAA;SACf,CAAC,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,173 @@
|
|
|
1
|
+
var __values = (this && this.__values) || function(o) {
|
|
2
|
+
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
3
|
+
if (m) return m.call(o);
|
|
4
|
+
if (o && typeof o.length === "number") return {
|
|
5
|
+
next: function () {
|
|
6
|
+
if (o && i >= o.length) o = void 0;
|
|
7
|
+
return { value: o && o[i++], done: !o };
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Safely parses a string parameter to a number.
|
|
14
|
+
*
|
|
15
|
+
* @param value - String value to parse
|
|
16
|
+
* @param options - Validation options
|
|
17
|
+
* @returns Validation result containing the parsed number or error
|
|
18
|
+
*/
|
|
19
|
+
export function parseNumberParam(value, options) {
|
|
20
|
+
if (options === void 0) { options = {}; }
|
|
21
|
+
var _a = options.throwOnError, throwOnError = _a === void 0 ? false : _a, _b = options.errorMessage, errorMessage = _b === void 0 ? 'Invalid number parameter' : _b, defaultValue = options.defaultValue, _c = options.required, required = _c === void 0 ? false : _c;
|
|
22
|
+
// Handle undefined case
|
|
23
|
+
if (value === undefined) {
|
|
24
|
+
if (required) {
|
|
25
|
+
var error = "Required number parameter is missing";
|
|
26
|
+
if (throwOnError)
|
|
27
|
+
throw new Error(error);
|
|
28
|
+
return { isValid: false, value: null, error: error };
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
isValid: defaultValue !== undefined,
|
|
32
|
+
value: defaultValue !== undefined ? defaultValue : null,
|
|
33
|
+
error: defaultValue === undefined ? 'Missing parameter with no default' : undefined
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
// Parse and validate the number
|
|
37
|
+
var num = Number(value);
|
|
38
|
+
if (isNaN(num)) {
|
|
39
|
+
if (throwOnError)
|
|
40
|
+
throw new Error(errorMessage);
|
|
41
|
+
return { isValid: false, value: null, error: errorMessage };
|
|
42
|
+
}
|
|
43
|
+
return { isValid: true, value: num };
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Safely parses a string parameter to a boolean.
|
|
47
|
+
*
|
|
48
|
+
* @param value - String value to parse
|
|
49
|
+
* @param options - Validation options
|
|
50
|
+
* @returns Validation result containing the parsed boolean or error
|
|
51
|
+
*/
|
|
52
|
+
export function parseBooleanParam(value, options) {
|
|
53
|
+
if (options === void 0) { options = {}; }
|
|
54
|
+
var _a = options.throwOnError, throwOnError = _a === void 0 ? false : _a, _b = options.errorMessage, errorMessage = _b === void 0 ? 'Invalid boolean parameter' : _b, defaultValue = options.defaultValue, _c = options.required, required = _c === void 0 ? false : _c;
|
|
55
|
+
// Handle undefined case
|
|
56
|
+
if (value === undefined) {
|
|
57
|
+
if (required) {
|
|
58
|
+
var error = "Required boolean parameter is missing";
|
|
59
|
+
if (throwOnError)
|
|
60
|
+
throw new Error(error);
|
|
61
|
+
return { isValid: false, value: null, error: error };
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
isValid: defaultValue !== undefined,
|
|
65
|
+
value: defaultValue !== undefined ? defaultValue : null,
|
|
66
|
+
error: defaultValue === undefined ? 'Missing parameter with no default' : undefined
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
// Parse the boolean value with various allowed formats
|
|
70
|
+
var lowercaseValue = value.toLowerCase();
|
|
71
|
+
if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {
|
|
72
|
+
return { isValid: true, value: true };
|
|
73
|
+
}
|
|
74
|
+
if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {
|
|
75
|
+
return { isValid: true, value: false };
|
|
76
|
+
}
|
|
77
|
+
if (throwOnError)
|
|
78
|
+
throw new Error(errorMessage);
|
|
79
|
+
return { isValid: false, value: null, error: errorMessage };
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Extracts pagination parameters from request query parameters.
|
|
83
|
+
*
|
|
84
|
+
* @param query - Query parameters object
|
|
85
|
+
* @param defaultPage - Default page number if not specified (defaults to 1)
|
|
86
|
+
* @param defaultLimit - Default per page size if not specified (defaults to 20)
|
|
87
|
+
* @param maxLimitSize - Maximum allowed per page size (defaults to 100)
|
|
88
|
+
* @returns Object containing validated page and limit
|
|
89
|
+
*/
|
|
90
|
+
export function extractPaginationParams(query, defaultPage, defaultLimit, maxLimitSize) {
|
|
91
|
+
if (defaultPage === void 0) { defaultPage = 1; }
|
|
92
|
+
if (defaultLimit === void 0) { defaultLimit = 20; }
|
|
93
|
+
if (maxLimitSize === void 0) { maxLimitSize = 100; }
|
|
94
|
+
// Parse page parameter
|
|
95
|
+
var pageParam = typeof query.page === 'string' ? query.page : undefined;
|
|
96
|
+
var pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });
|
|
97
|
+
// Parse limit parameter
|
|
98
|
+
var limitParam = typeof query.limit === 'string' ? query.limit : undefined;
|
|
99
|
+
var limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });
|
|
100
|
+
// Ensure valid values (handle 0 → fallback to default)
|
|
101
|
+
var page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;
|
|
102
|
+
var limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;
|
|
103
|
+
return { page: page, limit: limit };
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Extracts sorting parameters from request query parameters.
|
|
107
|
+
*
|
|
108
|
+
* @param query - Query parameters object
|
|
109
|
+
* @param allowedFields - Array of field names that are allowed to be sorted
|
|
110
|
+
* @param defaultSort - Default sort configuration if not specified
|
|
111
|
+
* @returns Object containing sort field and direction
|
|
112
|
+
*/
|
|
113
|
+
export function extractSortParams(query, allowedFields, defaultSort) {
|
|
114
|
+
if (defaultSort === void 0) { defaultSort = { sortBy: 'createdAt', sortOrder: 'desc' }; }
|
|
115
|
+
var sortBy = defaultSort.sortBy;
|
|
116
|
+
var sortOrder = defaultSort.sortOrder;
|
|
117
|
+
// Extract from `sortBy` or `sort`
|
|
118
|
+
if (typeof query.sortBy === 'string') {
|
|
119
|
+
sortBy = query.sortBy;
|
|
120
|
+
}
|
|
121
|
+
else if (Array.isArray(query.sortBy)) {
|
|
122
|
+
sortBy = query.sortBy[0];
|
|
123
|
+
}
|
|
124
|
+
else if (typeof query.sort === 'string') {
|
|
125
|
+
sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;
|
|
126
|
+
sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';
|
|
127
|
+
}
|
|
128
|
+
else if (Array.isArray(query.sort)) {
|
|
129
|
+
sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];
|
|
130
|
+
sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';
|
|
131
|
+
}
|
|
132
|
+
// Explicit sortOrder (overrides inferred one if valid)
|
|
133
|
+
if (typeof query.sortOrder === 'string') {
|
|
134
|
+
var order = query.sortOrder.toLowerCase();
|
|
135
|
+
if (order === 'asc' || order === 'desc') {
|
|
136
|
+
sortOrder = order;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// Validate field
|
|
140
|
+
if (!allowedFields.includes(sortBy)) {
|
|
141
|
+
sortBy = defaultSort.sortBy;
|
|
142
|
+
}
|
|
143
|
+
return { sortBy: sortBy, sortOrder: sortOrder };
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Extracts filter parameters from query parameters based on allowed filter fields.
|
|
147
|
+
*
|
|
148
|
+
* @param query - Query parameters object
|
|
149
|
+
* @param allowedFilters - Array of field names that are allowed to be used as filters
|
|
150
|
+
* @returns Object containing the filters as key-value pairs
|
|
151
|
+
*/
|
|
152
|
+
export function extractFilterParams(query, allowedFilters) {
|
|
153
|
+
var e_1, _a;
|
|
154
|
+
var filters = {};
|
|
155
|
+
try {
|
|
156
|
+
// Find filter parameters in the query
|
|
157
|
+
for (var allowedFilters_1 = __values(allowedFilters), allowedFilters_1_1 = allowedFilters_1.next(); !allowedFilters_1_1.done; allowedFilters_1_1 = allowedFilters_1.next()) {
|
|
158
|
+
var field = allowedFilters_1_1.value;
|
|
159
|
+
if (field in query) {
|
|
160
|
+
filters[field] = query[field];
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
165
|
+
finally {
|
|
166
|
+
try {
|
|
167
|
+
if (allowedFilters_1_1 && !allowedFilters_1_1.done && (_a = allowedFilters_1.return)) _a.call(allowedFilters_1);
|
|
168
|
+
}
|
|
169
|
+
finally { if (e_1) throw e_1.error; }
|
|
170
|
+
}
|
|
171
|
+
return filters;
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=request.utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":";;;;;;;;;;;AA+BA;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAyB,EAAE,OAA+B;IAA/B,wBAAA,EAAA,YAA+B;IACjF,IAAA,KAAoG,OAAO,aAAvF,EAApB,YAAY,mBAAG,KAAK,KAAA,EAAE,KAA8E,OAAO,aAA5C,EAAzC,YAAY,mBAAG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M,CAAC,CAAC,CAAC,KAAK,CAAC;IAC7D,CAAC;IAED,uDAAuD;IACvD,IAAI,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;QACxC,IAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;QAC5C,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;YACxC,SAAS,GAAG,KAAK,CAAC;QACpB,CAAC;IACH,CAAC;IAED,iBAAiB;IACjB,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACpC,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,MAAM,QAAA,EAAE,SAAS,WAAA,EAAE,CAAC;AAC/B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CACjC,KAAwC,EACxC,cAAwB;;IAExB,IAAM,OAAO,GAAsC,EAAE,CAAC;;QAEtD,sCAAsC;QACtC,KAAoB,IAAA,mBAAA,SAAA,cAAc,CAAA,8CAAA,0EAAE,CAAC;YAAhC,IAAM,KAAK,2BAAA;YACd,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;gBACnB,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YAChC,CAAC;QACH,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"]}
|
|
@@ -13,8 +13,8 @@ var __extends = (this && this.__extends) || (function () {
|
|
|
13
13
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
14
14
|
};
|
|
15
15
|
})();
|
|
16
|
-
import { randomUUID } from 'crypto';
|
|
17
16
|
import { getRequestId } from './context-store.utils';
|
|
17
|
+
import { uuid } from './id.utils';
|
|
18
18
|
/**
|
|
19
19
|
* Standard HTTP response wrapper for successful responses.
|
|
20
20
|
* Implements the `ApiResponse<T>` interface and sets default values.
|
|
@@ -39,7 +39,7 @@ var SuccessResponse = /** @class */ (function () {
|
|
|
39
39
|
/** Timestamp when the response was generated, in ISO format. */
|
|
40
40
|
this.timestamp = new Date().toISOString();
|
|
41
41
|
/** Unique identifier for this response, useful for request tracing. */
|
|
42
|
-
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
42
|
+
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
43
43
|
if (message)
|
|
44
44
|
this.message = message;
|
|
45
45
|
this.data = data !== null && data !== void 0 ? data : null;
|
|
@@ -68,7 +68,7 @@ var ErrorResponse = /** @class */ (function (_super) {
|
|
|
68
68
|
/** Timestamp when the error occurred, in ISO format. */
|
|
69
69
|
_this.timestamp = new Date().toISOString();
|
|
70
70
|
/** Unique identifier for this error instance. */
|
|
71
|
-
_this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
71
|
+
_this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
72
72
|
_this.status = status;
|
|
73
73
|
_this.name = _this.constructor.name;
|
|
74
74
|
Error.captureStackTrace(_this, _this.constructor);
|
|
@@ -142,7 +142,7 @@ var RedirectResponse = /** @class */ (function () {
|
|
|
142
142
|
/** Whether the response is a redirect */
|
|
143
143
|
this.isRedirect = true;
|
|
144
144
|
/** Unique identifier for this response */
|
|
145
|
-
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a :
|
|
145
|
+
this.requestId = (_a = getRequestId()) !== null && _a !== void 0 ? _a : uuid();
|
|
146
146
|
this.redirectUrl = url;
|
|
147
147
|
this.statusCode = statusCode;
|
|
148
148
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response.utils.js","sourceRoot":"","sources":["../../../src/utils/response.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD;;;;;GAKG;AACH;IAgBE;;;;;OAKG;IACH,yBAAY,OAAe,EAAE,IAAQ;;QArBrC,sDAAsD;QACtD,YAAO,GAAW,SAAS,CAAC;QAE5B,2EAA2E;QAC3E,UAAK,GAAY,KAAK,CAAC;QAEvB,yCAAyC;QACzC,SAAI,GAAa,IAAI,CAAC;QAEtB,gEAAgE;QAChE,cAAS,GAAW,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAE7C,uEAAuE;QACvE,cAAS,GAAW,MAAA,YAAY,EAAE,mCAAI,UAAU,EAAE,CAAC;QASjD,I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,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":";;;;;;;;;;;;;;;AACA,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAElC;;;;;GAKG;AACH;IAgBE;;;;;OAKG;IACH,yBAAY,OAAe,EAAE,IAAQ;;QArBrC,sDAAsD;QACtD,YAAO,GAAW,SAAS,CAAC;QAE5B,2EAA2E;QAC3E,UAAK,GAAY,KAAK,CAAC;QAEvB,yCAAyC;QACzC,SAAI,GAAa,IAAI,CAAC;QAEtB,gEAAgE;QAChE,cAAS,GAAW,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAE7C,uEAAuE;QACvE,cAAS,GAAW,MAAA,YAAY,EAAE,mCAAI,IAAI,EAAE,CAAC;QAS3C,IAAI,OAAO;YAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACpC,IAAI,CAAC,IAAI,GAAG,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,IAAI,CAAC;IAC3B,CAAC;IACH,sBAAC;AAAD,CAAC,AA1BD,IA0BC;;AAED;;;GAGG;AACH;IAAmC,iCAAK;IAatC;;;;;OAKG;IACH,uBAAY,OAAe,EAAE,MAAoB;QAApB,uBAAA,EAAA,YAAoB;;QAC/C,YAAA,MAAK,YAAC,OAAO,CAAC,SAAC;QAhBjB,oD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;IAE5C,yBAAyB;IACzB,IAAM,SAAS,GAAG,QAAQ,CAAC,KAAK,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAEvD,OAAO,IAAI,iBAAiB,CAC1B,SAAS,EACT;QACE,KAAK,EAAE,QAAQ,CAAC,MAAM;QACtB,IAAI,EAAE,SAAS;QACf,QAAQ,EAAE,aAAa;KACxB,EACD,OAAO,CACR,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,GAAQ,EAAE,WAAoE;IACzG,mBAAmB;IACnB,IAAI,aAAa,IAAI,WAAW,EAAE,CAAC;QACjC,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,WAAW,CAAC,WAAW,CAAC,CAAC;QAC9D,OAAO;IACT,CAAC;IAED,gBAAgB;IAChB,IAAI,OAAO,IAAI,WAAW,IAAI,WAAW,CAAC,KAAK,EAAE,CAAC;QAChD,IAAM,aAAa,GAAG,WAA4B,CAAC;QACnD,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;YACpC,KAAK,EAAE,IAAI;YACX,OAAO,EAAE,aAAa,CAAC,OAAO;YAC9B,SAAS,EAAE,aAAa,CAAC,SAAS;YAClC,SAAS,EAAE,aAAa,CAAC,SAAS;SACnC,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,2BAA2B;IAC3B,IAAM,eAAe,GAAG,WAAmC,CAAC;IAE5D,2CAA2C;IAC3C,IAAI,eAAe,YAAY,iBAAiB,EAAE,CAAC;QACjD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { ApiResponse } from '../types/api-response';\nimport { getRequestId } from './context-store.utils';\nimport { uuid } from './id.utils';\n\n/**\n * Standard HTTP response wrapper for successful responses.\n * Implements the `ApiResponse<T>` interface and sets default values.\n *\n * @typeParam T - The shape of the data returned in the response.\n */\nexport class SuccessResponse<T> implements ApiResponse<T> {\n /** Message describing the result of the operation. */\n message: string = 'Success';\n\n /** Whether the response is an error. Always false in success responses. */\n error: boolean = false;\n\n /** The payload returned from the API. */\n data: T | null = null;\n\n /** Timestamp when the response was generated, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this response, useful for request tracing. */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new success response.\n *\n * @param {string} message - Optional message to override the default.\n * @param {T} [data] - Optional data payload.\n */\n constructor(message: string, data?: T) {\n if (message) this.message = message;\n this.data = data ?? null;\n }\n}\n\n/**\n * Wrapper for error responses that extends the native `Error` object.\n * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).\n */\nexport class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {\n /** HTTP status code associated with the error (e.g., 404, 500). */\n status: number;\n\n /** Indicates that this is an error. Always true. */\n error: boolean = true;\n\n /** Timestamp when the error occurred, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this error instance. */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new error response.\n *\n * @param {string} message - The error message to display or log.\n * @param {number} [status=500] - Optional HTTP status code (defaults to 500).\n */\n constructor(message: string, status: number = 500) {\n super(message);\n this.status = status;\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Response with paginated data extending the standard success response.\n * Useful for APIs that return large collections of data.\n *\n * @typeParam T - The shape of each item in the paginated collection.\n */\nexport class PaginatedResponse<T> extends SuccessResponse<T[]> {\n /** Total number of items across all pages */\n total: number;\n\n /** Current page number (1-based) */\n page: number;\n\n /** Number of items per page */\n pageSize: number;\n\n /** Total number of pages */\n totalPages: number;\n\n /** Whether there's a next page available */\n hasNext: boolean;\n\n /** Whether there's a previous page available */\n hasPrevious: boolean;\n\n /**\n * Constructs a new paginated response.\n *\n * @param {T[]} items - The current page of items.\n * @param {Object} pagination - Pagination information.\n * @param {number} pagination.total - Total number of items across all pages.\n * @param {number} pagination.page - Current page number (1-based).\n * @param {number} pagination.pageSize - Number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n */\n constructor(items: T[], pagination: { total: number; page: number; pageSize: number }, message: string = 'Success') {\n super(message, items);\n\n this.total = pagination.total;\n this.page = pagination.page;\n this.pageSize = pagination.pageSize;\n\n this.totalPages = Math.ceil(this.total / this.pageSize);\n this.hasNext = this.page < this.totalPages;\n this.hasPrevious = this.page > 1;\n }\n}\n\n/**\n * Specialized response for operations that don't return data (HTTP 204).\n */\nexport class NoContentResponse extends SuccessResponse<null> {\n /**\n * Constructs a new no-content response.\n *\n * @param {string} [message=\"Operation completed successfully\"] - Optional custom message.\n */\n constructor(message: string = 'Operation completed successfully') {\n super(message, null);\n }\n}\n\n/**\n * Specialized response for redirects.\n */\nexport class RedirectResponse {\n /** The URL to redirect to */\n redirectUrl: string;\n\n /** HTTP status code for the redirect (301, 302, 303, 307, 308) */\n statusCode: number;\n\n /** Whether the response is a redirect */\n isRedirect: boolean = true;\n\n /** Unique identifier for this response */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new redirect response.\n *\n * @param {string} url - The URL to redirect to.\n * @param {number} [statusCode=302] - HTTP status code for the redirect.\n */\n constructor(url: string, statusCode: number = 302) {\n this.redirectUrl = url;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Creates a standard success response.\n *\n * @typeParam T - The shape of the data returned in the response.\n * @param {T} data - The data to include in the response.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {SuccessResponse<T>} A properly formatted success response.\n */\nexport function createSuccessResponse<T>(data: T, message: string = 'Success'): SuccessResponse<T> {\n return new SuccessResponse<T>(message, data);\n}\n\n/**\n * Creates a standard error response.\n *\n * @param {string} message - The error message.\n * @param {number} [statusCode=500] - HTTP status code for the error.\n * @returns {ErrorResponse} A properly formatted error response.\n */\nexport function createErrorResponse(message: string, statusCode: number = 500): ErrorResponse {\n return new ErrorResponse(message, statusCode);\n}\n\n/**\n * Creates a paginated response from array data.\n *\n * @typeParam T - The shape of each item in the collection.\n * @param {T[]} allItems - The complete array of items to paginate.\n * @param {number} page - The requested page (1-based).\n * @param {number} pageSize - The number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {PaginatedResponse<T>} A properly formatted paginated response.\n */\nexport function createPaginatedResponse<T>(\n allItems: T[],\n page: number,\n pageSize: number,\n message: string = 'Success'\n): PaginatedResponse<T> {\n // Ensure valid pagination parameters\n const validPage = Math.max(1, page);\n const validPageSize = Math.max(1, pageSize);\n\n // Calculate slice indices\n const startIndex = (validPage - 1) * validPageSize;\n const endIndex = startIndex + validPageSize;\n\n // Get current page items\n const pageItems = allItems.slice(startIndex, endIndex);\n\n return new PaginatedResponse<T>(\n pageItems,\n {\n total: allItems.length,\n page: validPage,\n pageSize: validPageSize\n },\n message\n );\n}\n\n/**\n * Adapter to convert API responses to Express.js response format.\n *\n * @param {any} res - Express response object.\n * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.\n */\nexport function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void {\n // Handle redirects\n if ('redirectUrl' in apiResponse) {\n res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);\n return;\n }\n\n // Handle errors\n if ('error' in apiResponse && apiResponse.error) {\n const errorResponse = apiResponse as ErrorResponse;\n res.status(errorResponse.status).json({\n error: true,\n message: errorResponse.message,\n timestamp: errorResponse.timestamp,\n requestId: errorResponse.requestId\n });\n return;\n }\n\n // Handle success responses\n const successResponse = apiResponse as SuccessResponse<any>;\n\n // No content (204) shouldn't return a body\n if (successResponse instanceof NoContentResponse) {\n res.status(204).end();\n return;\n }\n\n res.status(200).json(successResponse);\n}\n"]}
|
package/build/esnext/config.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silen
|
|
|
2
2
|
/**
|
|
3
3
|
* Application runtime configuration loaded from environment variables.
|
|
4
4
|
*/
|
|
5
|
-
export declare
|
|
6
|
-
|
|
5
|
+
export declare let config: {
|
|
6
|
+
logger: {
|
|
7
7
|
/**
|
|
8
8
|
* Logging level (e.g., 'info', 'debug', 'warn', 'error').
|
|
9
9
|
*/
|
|
@@ -11,24 +11,35 @@ export declare const Config: {
|
|
|
11
11
|
/**
|
|
12
12
|
* Name of the logger instance (defaults to npm package name).
|
|
13
13
|
*/
|
|
14
|
-
name: string
|
|
14
|
+
name: string;
|
|
15
15
|
/**
|
|
16
|
-
*
|
|
16
|
+
* Enables pretty-print logging in development.
|
|
17
|
+
* Has no effect in production.
|
|
17
18
|
*/
|
|
18
|
-
|
|
19
|
+
pretty: boolean;
|
|
19
20
|
};
|
|
20
|
-
|
|
21
|
+
http: {
|
|
21
22
|
/**
|
|
22
23
|
* Timeout for HTTP requests in milliseconds
|
|
23
24
|
*/
|
|
24
25
|
timeout: number;
|
|
25
26
|
};
|
|
26
|
-
|
|
27
|
+
cache: {
|
|
27
28
|
/**
|
|
28
29
|
* Default TTL (time to live) for cache entries in seconds
|
|
29
30
|
*/
|
|
30
31
|
defaultTtl: number;
|
|
31
32
|
};
|
|
32
33
|
};
|
|
34
|
+
/**
|
|
35
|
+
* Update the @catbee/utils configuration.
|
|
36
|
+
* @param value Partial configuration object.
|
|
37
|
+
*/
|
|
38
|
+
export declare function setConfig(value: Partial<typeof config>): void;
|
|
39
|
+
/**
|
|
40
|
+
* Get the current @catbee/utils configuration.
|
|
41
|
+
* @returns The current configuration object.
|
|
42
|
+
*/
|
|
43
|
+
export declare function getConfig(): typeof config;
|
|
33
44
|
export {};
|
|
34
45
|
//# sourceMappingURL=config.d.ts.map
|
package/build/esnext/config.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { Env } from './utils/env.utils';
|
|
2
|
+
import { deepObjMerge } from './utils/obj.utils';
|
|
2
3
|
/**
|
|
3
4
|
* Application runtime configuration loaded from environment variables.
|
|
4
5
|
*/
|
|
5
|
-
export
|
|
6
|
-
|
|
6
|
+
export let config = {
|
|
7
|
+
logger: {
|
|
7
8
|
/**
|
|
8
9
|
* Logging level (e.g., 'info', 'debug', 'warn', 'error').
|
|
9
10
|
*/
|
|
@@ -13,21 +14,36 @@ export const Config = {
|
|
|
13
14
|
*/
|
|
14
15
|
name: Env.get('LOGGER_NAME', Env.get('npm_package_name', '@catbee/utils')),
|
|
15
16
|
/**
|
|
16
|
-
*
|
|
17
|
+
* Enables pretty-print logging in development.
|
|
18
|
+
* Has no effect in production.
|
|
17
19
|
*/
|
|
18
|
-
|
|
20
|
+
pretty: Env.getBoolean('LOGGER_PRETTY', true)
|
|
19
21
|
},
|
|
20
|
-
|
|
22
|
+
http: {
|
|
21
23
|
/**
|
|
22
24
|
* Timeout for HTTP requests in milliseconds
|
|
23
25
|
*/
|
|
24
26
|
timeout: Env.getNumber('HTTP_TIMEOUT', 30000)
|
|
25
27
|
},
|
|
26
|
-
|
|
28
|
+
cache: {
|
|
27
29
|
/**
|
|
28
30
|
* Default TTL (time to live) for cache entries in seconds
|
|
29
31
|
*/
|
|
30
|
-
defaultTtl: Env.getNumber('
|
|
32
|
+
defaultTtl: Env.getNumber('CACHE_DEFAULT_TTL_SECONDS', 3600) * 1000
|
|
31
33
|
}
|
|
32
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Update the @catbee/utils configuration.
|
|
37
|
+
* @param value Partial configuration object.
|
|
38
|
+
*/
|
|
39
|
+
export function setConfig(value) {
|
|
40
|
+
deepObjMerge(config, value);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Get the current @catbee/utils configuration.
|
|
44
|
+
* @returns The current configuration object.
|
|
45
|
+
*/
|
|
46
|
+
export function getConfig() {
|
|
47
|
+
return config;
|
|
48
|
+
}
|
|
33
49
|
//# sourceMappingURL=config.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD;;GAEG;AACH,MAAM,CAAC,IAAI,MAAM,GAAG;IAClB,MAAM,EAAE;QACN;;WAEG;QACH,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAa;QAElD;;WAEG;QACH,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,GAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,eAAe,CAAC,CAAC;QAE1E;;;WAGG;QACH,MAAM,EAAE,GAAG,CAAC,UAAU,CAAC,eAAe,EAAE,IAAI,CAAC;KAC9C;IAED,IAAI,EAAE;QACJ;;WAEG;QACH,OAAO,EAAE,GAAG,CAAC,SAAS,CAAC,cAAc,EAAE,KAAK,CAAC;KAC9C;IAED,KAAK,EAAE;QACL;;WAEG;QACH,UAAU,EAAE,GAAG,CAAC,SAAS,CAAC,2BAA2B,EAAE,IAAI,CAAC,GAAG,IAAI;KACpE;CACF,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,KAA6B;IACrD,YAAY,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS;IACvB,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Env } from './utils/env.utils';\nimport { deepObjMerge } from './utils/obj.utils';\n\ntype LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent';\n\n/**\n * Application runtime configuration loaded from environment variables.\n */\nexport let config = {\n logger: {\n /**\n * Logging level (e.g., 'info', 'debug', 'warn', 'error').\n */\n level: Env.get('LOGGER_LEVEL', 'info') as LogLevel,\n\n /**\n * Name of the logger instance (defaults to npm package name).\n */\n name: Env.get('LOGGER_NAME', Env.get('npm_package_name', '@catbee/utils')),\n\n /**\n * Enables pretty-print logging in development.\n * Has no effect in production.\n */\n pretty: Env.getBoolean('LOGGER_PRETTY', true)\n },\n\n http: {\n /**\n * Timeout for HTTP requests in milliseconds\n */\n timeout: Env.getNumber('HTTP_TIMEOUT', 30000)\n },\n\n cache: {\n /**\n * Default TTL (time to live) for cache entries in seconds\n */\n defaultTtl: Env.getNumber('CACHE_DEFAULT_TTL_SECONDS', 3600) * 1000\n }\n};\n\n/**\n * Update the @catbee/utils configuration.\n * @param value Partial configuration object.\n */\nexport function setConfig(value: Partial<typeof config>): void {\n deepObjMerge(config, value);\n}\n\n/**\n * Get the current @catbee/utils configuration.\n * @returns The current configuration object.\n */\nexport function getConfig(): typeof config {\n return config;\n}\n"]}
|
package/build/esnext/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { setConfig, getConfig } from './config';
|
|
1
2
|
export * from './utils/array.utils';
|
|
2
3
|
export * from './utils/async.utils';
|
|
3
4
|
export * from './utils/cache.utils';
|
|
@@ -13,6 +14,7 @@ export * from './utils/id.utils';
|
|
|
13
14
|
export * from './utils/logger.utils';
|
|
14
15
|
export * from './utils/middleware.utils';
|
|
15
16
|
export * from './utils/obj.utils';
|
|
17
|
+
export * from './utils/request.utils';
|
|
16
18
|
export * from './utils/response.utils';
|
|
17
19
|
export * from './utils/string.utils';
|
|
18
20
|
export * from './utils/url.utils';
|
package/build/esnext/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { setConfig, getConfig } from './config';
|
|
1
2
|
export * from './utils/array.utils';
|
|
2
3
|
export * from './utils/async.utils';
|
|
3
4
|
export * from './utils/cache.utils';
|
|
@@ -13,6 +14,7 @@ export * from './utils/id.utils';
|
|
|
13
14
|
export * from './utils/logger.utils';
|
|
14
15
|
export * from './utils/middleware.utils';
|
|
15
16
|
export * from './utils/obj.utils';
|
|
17
|
+
export * from './utils/request.utils';
|
|
16
18
|
export * from './utils/response.utils';
|
|
17
19
|
export * from './utils/string.utils';
|
|
18
20
|
export * from './utils/url.utils';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AAEvC,cAAc,sBAAsB,CAAC","sourcesContent":["export * from './utils/array.utils';\nexport * from './utils/async.utils';\nexport * from './utils/cache.utils';\nexport * from './utils/context-store.utils';\nexport * from './utils/crypto.utils';\nexport * from './utils/decorators.utils';\nexport * from './utils/dir.utils';\nexport * from './utils/env.utils';\nexport * from './utils/exception.utils';\nexport * from './utils/fs.utils';\nexport * from './utils/http-status-codes';\nexport * from './utils/id.utils';\nexport * from './utils/logger.utils';\nexport * from './utils/middleware.utils';\nexport * from './utils/obj.utils';\nexport * from './utils/response.utils';\nexport * from './utils/string.utils';\nexport * from './utils/url.utils';\nexport * from './utils/validate.utils';\n\nexport * from './types/api-response';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAEhD,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AAEvC,cAAc,sBAAsB,CAAC","sourcesContent":["export { setConfig, getConfig } from './config';\n\nexport * from './utils/array.utils';\nexport * from './utils/async.utils';\nexport * from './utils/cache.utils';\nexport * from './utils/context-store.utils';\nexport * from './utils/crypto.utils';\nexport * from './utils/decorators.utils';\nexport * from './utils/dir.utils';\nexport * from './utils/env.utils';\nexport * from './utils/exception.utils';\nexport * from './utils/fs.utils';\nexport * from './utils/http-status-codes';\nexport * from './utils/id.utils';\nexport * from './utils/logger.utils';\nexport * from './utils/middleware.utils';\nexport * from './utils/obj.utils';\nexport * from './utils/request.utils';\nexport * from './utils/response.utils';\nexport * from './utils/string.utils';\nexport * from './utils/url.utils';\nexport * from './utils/validate.utils';\n\nexport * from './types/api-response';\n"]}
|