@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":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,8BASC;AASD,8CAGC;AASD,kDAcC;AASD,4BAUC;AAhID,6CAA6D;AAE7D,sCAAmC;AACnC,+DAAgE;AAEhE;;GAEG;AACH,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAY/C;;GAEG;AACU,QAAA,WAAW,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;AAChF,MAAM,OAAO,GAAG,mBAA6D,CAAC;AAE9E;;;;;GAKG;AACH,SAAS,WAAW;IAClB,MAAM,SAAS,GAAkB;QAC/B,IAAI,EAAE,eAAM,CAAC,MAAM,CAAC,IAAI;QACxB,KAAK,EAAE,eAAM,CAAC,MAAM,CAAC,KAAK;QAC1B,MAAM,EAAE;YACN,KAAK,EAAE,CAAC,mBAAmB,EAAE,KAAK,CAAC;YACnC,MAAM,CAAC,KAAK,EAAE,IAAI;gBAChB,IAAI,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AiB,EACpB,CAAC;IAEH,IAAI,CAAC;QACH,kCAAY,CAAC,GAAG,CAAC,+BAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7C,CAAC;IAAC,WAAM,CAAC;QACP,8CAA8C;QAC9C,MAAM,CAAC,KAAK,CAAC,uEAAuE,CAAC,CAAC;IACxF,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,KAAsB,EAAE,OAAgB,EAAE,OAA6B;IAC9F,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,MAAM,UAAU,mCACX,OAAO,KACV,GAAG,EAAE,MAAM,GACZ,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { Config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: Config.Logger.name,\n level: Config.Logger.level,\n redact: {\n paths: ['req.authorization', 'url'],\n censor(value, path) {\n if (path[0] === 'url') {\n return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');\n } else if (path[1] === 'authorization') {\n return value.replace(/\\s+(\\S+)$/, ' ***');\n }\n return '***';\n }\n }\n };\n\n if (Config.Logger.isoTimestamp) {\n logParams.timestamp = stdTimeFunctions.isoTime;\n }\n\n _global[GLOBAL_LOGGER_KEY] = pino(logParams);\n _global[GLOBAL_LOGGER_KEY].debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n err: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6FA,0CAEC;AAsBD,0CAEC;AAmBD,wBAEC;AAgBD,0CAIC;AAgBD,gDAEC;AAgBD,gDAEC;AAsDD,8BASC;AASD,8CAGC;AASD,kDAcC;AASD,4BAUC;AAzTD,6CAA6D;AAE7D,sCAAmC;AACnC,+DAAgE;AAChE,2CAAkC;AAElC;;GAEG;AACH,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAY/C,2BAA2B;AACd,QAAA,sBAAsB,GAAG;IACpC,UAAU;IACV,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,SAAS;IACT,MAAM;IACN,KAAK;IACL,cAAc;IACd,eAAe;IACf,eAAe;IACf,eAAe;CAChB,CAAC;AAEF;;GAEG;AACH,IAAI,kBAAkB,GAA2E,CAC/F,KAAK,EACL,IAAI,EACJ,eAAe,GAAG,8BAAsB,EACxC,EAAE;IACF,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAE5C,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;IACjD,MAAM,oBAAoB,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;IAEvE,IAAI,SAAS,C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C,SAAiB,EAAE,oBAAyC,EAAE;IAChG,MAAM,MAAM,GAAG,iBAAiB,iBAC9B,SAAS,IACN,iBAAiB,EACpB,CAAC;IAEH,IAAI,CAAC;QACH,kCAAY,CAAC,GAAG,CAAC,+BAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7C,CAAC;IAAC,WAAM,CAAC;QACP,8CAA8C;QAC9C,MAAM,CAAC,KAAK,CAAC,uEAAuE,CAAC,CAAC;IACxF,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,KAAsB,EAAE,OAAgB,EAAE,OAA6B;IAC9F,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,MAAM,UAAU,mCACX,OAAO,KACV,KAAK,EAAE,MAAM,GACd,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { Env } from './env.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n// Default sensitive fields\nexport const defaultSensitiveFields = [\n 'password',\n 'secret',\n 'token',\n 'apiKey',\n 'api_key',\n 'auth',\n 'jwt',\n 'access_token',\n 'client_secret',\n 'session_token',\n 'refresh_token'\n];\n\n/**\n * The global censor function used by the logger.\n */\nlet globalRedactCensor: (value: unknown, path: string[], sensitiveFields?: string[]) => string = (\n value,\n path,\n sensitiveFields = defaultSensitiveFields\n) => {\n if (typeof value !== 'string') return '***';\n\n const lowerPath = path.map(p => p.toLowerCase());\n const lowerSensitiveFields = sensitiveFields.map(f => f.toLowerCase());\n\n if (lowerPath.some(p => lowerSensitiveFields.includes(p))) return '***';\n\n // Redact URLs\n if (lowerPath[0] === 'url') {\n return value.replace(new RegExp(`([?&](${lowerSensitiveFields.join('|')})=)[^&#]*`, 'gi'), '$1***');\n }\n\n if (lowerPath.some(p => p.includes('authorization') || p.includes('auth'))) {\n return value.replace(/^(\\S+)\\s+.+$/, '$1 ***') || '***';\n }\n\n // Redact sensitive fields - check each path segment against each sensitive field\n if (lowerPath.some(pathPart => lowerSensitiveFields.some(field => pathPart.includes(field)))) {\n return '***';\n }\n\n if (path.length > 0 && !['req', 'res', 'headers'].includes(lowerPath[0])) {\n return value;\n }\n\n return value;\n};\n\n/**\n * Sets the global redaction censor function used throughout the application for log redaction.\n *\n * Use this function to customize how sensitive data is redacted in logs. The provided function\n * will replace the default censor implementation.\n *\n * @example\n * ```typescript\n * // Custom censor that redacts only specific values\n * setRedactCensor((value, path, sensitiveFields) => {\n * if (path.includes('password')) return '***';\n * return value;\n * });\n * ```\n *\n * @param fn - The redaction censor function to use globally. This function receives:\n * - value: The data value to potentially redact\n * - path: Array of strings representing the path to the value in the object\n * - sensitiveFields: Optional array of field names to consider sensitive\n * @returns void\n */\nexport function setRedactCensor(fn: (value: unknown, path: string[], sensitiveFields?: string[]) => string) {\n globalRedactCensor = fn;\n}\n\n/**\n * Gets the current global redaction censor function used for log redaction.\n *\n * This function is called internally by the logger when determining how to redact\n * sensitive information. It can also be used to access the current censor implementation\n * for composition or extension.\n *\n * @example\n * ```typescript\n * const currentCensor = getRedactCensor();\n * // Create an enhanced censor that extends the current one\n * setRedactCensor((value, path, fields) => {\n * // Add custom logic before delegating to current censor\n * if (someCondition) return customHandling();\n * return currentCensor(value, path, fields);\n * });\n * ```\n *\n * @returns The current redaction censor function\n */\nexport function getRedactCensor() {\n return globalRedactCensor;\n}\n\n/**\n * Convenience function to redact sensitive data using the current global redact censor.\n *\n * This is a direct wrapper around the global censor function that simplifies usage\n * in application code without needing to access the censor function directly.\n *\n * @example\n * ```typescript\n * // Redact a potential sensitive value\n * const safeValue = redact(value, ['user', 'apiKey']);\n * ```\n *\n * @param value - The value to potentially redact\n * @param path - Array of strings representing the path to the value in the object\n * @param sensitiveFields - Optional array of field names to consider sensitive\n * @returns The redacted string value or \"***\" for redacted content\n */\nexport function redact(value: unknown, path: string[], sensitiveFields?: string[]) {\n return globalRedactCensor(value, path, sensitiveFields);\n}\n\n/**\n * Extends the current redaction function with additional fields to redact.\n *\n * This function wraps the existing censor while adding more fields to be considered\n * sensitive without replacing the entire redaction logic.\n *\n * @example\n * ```typescript\n * // Add custom fields to be redacted in all future redaction operations\n * addRedactFields(['customerId', 'accountNumber']);\n * ```\n *\n * @param fields - Array of additional field names to redact\n */\nexport function addRedactFields(fields: string[]) {\n const prev = globalRedactCensor;\n globalRedactCensor = (value, path, sensitiveFields = defaultSensitiveFields) =>\n prev(value, path, [...(sensitiveFields || []), ...fields]);\n}\n\n/**\n * Replaces the default list of sensitive fields with a new list.\n *\n * This is useful when you want complete control over what fields are considered\n * sensitive by default, rather than using the library's built-in list.\n *\n * @example\n * ```typescript\n * // Replace default sensitive fields with a custom list\n * setSensitiveFields(['password', 'ssn', 'creditCard']);\n * ```\n *\n * @param fields - Array of field names to set as the new default sensitive fields\n */\nexport function setSensitiveFields(fields: string[]) {\n defaultSensitiveFields.splice(0, defaultSensitiveFields.length, ...fields);\n}\n\n/**\n * Adds additional field names to the default sensitive fields list.\n *\n * This preserves the existing sensitive fields while adding new ones for\n * application-specific sensitive data.\n *\n * @example\n * ```typescript\n * // Add domain-specific sensitive fields to the default list\n * addSensitiveFields(['socialSecurityNumber', 'medicalRecordNumber']);\n * ```\n *\n * @param fields - Array of additional field names to add to the sensitive fields list\n */\nexport function addSensitiveFields(fields: string[]) {\n defaultSensitiveFields.push(...fields);\n}\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: config.logger.name || '@catbee/utils',\n level: config.logger.level || 'info',\n redact: {\n paths: ['req.authorization', 'res.authorization', 'url', 'headers.authorization'],\n censor: (value, path) => redact(value, path)\n },\n timestamp: stdTimeFunctions.isoTime\n };\n\n const logger =\n config.logger.pretty && Env.isDev()\n ? pino(\n logParams,\n pino.transport({\n target: 'pino-pretty',\n options: {\n colorize: true,\n translateTime: 'SYS:standard',\n ignore: 'pid,hostname',\n singleLine: false, // multi-line errors\n levelFirst: true\n }\n })\n )\n : pino(logParams);\n\n _global[GLOBAL_LOGGER_KEY] = logger;\n _global[GLOBAL_LOGGER_KEY].debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n error: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
|
|
@@ -1,27 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*/
|
|
4
|
-
type Request = {
|
|
5
|
-
headers: Record<string, string | string[] | undefined>;
|
|
6
|
-
method: string;
|
|
7
|
-
url: string;
|
|
8
|
-
ip?: string;
|
|
9
|
-
body?: any;
|
|
10
|
-
query?: Record<string, any>;
|
|
11
|
-
params?: Record<string, any>;
|
|
12
|
-
[key: string]: any;
|
|
13
|
-
};
|
|
14
|
-
type Response = {
|
|
15
|
-
status: (code: number) => Response;
|
|
16
|
-
json: (data: any) => void;
|
|
17
|
-
send: (data: any) => void;
|
|
18
|
-
setHeader: (name: string, value: string | string[]) => void;
|
|
19
|
-
end: (data?: any) => void;
|
|
20
|
-
on: (event: string, callback: (...args: any[]) => void) => void;
|
|
21
|
-
[key: string]: any;
|
|
22
|
-
};
|
|
23
|
-
type NextFunction = (err?: Error | any) => void;
|
|
24
|
-
type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
|
|
1
|
+
import type { Request, Response, NextFunction } from 'express';
|
|
2
|
+
export type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
|
|
25
3
|
/**
|
|
26
4
|
* Attaches a unique request ID to each request.
|
|
27
5
|
* Useful for request tracing and correlation between logs.
|
|
@@ -46,7 +24,7 @@ export declare function requestId(options?: {
|
|
|
46
24
|
export declare function responseTime(options?: {
|
|
47
25
|
addHeader?: boolean;
|
|
48
26
|
logOnComplete?: boolean;
|
|
49
|
-
}):
|
|
27
|
+
}): (req: Request, res: Response, next: NextFunction) => void;
|
|
50
28
|
/**
|
|
51
29
|
* Request timeout middleware.
|
|
52
30
|
* Aborts requests that take too long to process.
|
|
@@ -55,19 +33,49 @@ export declare function responseTime(options?: {
|
|
|
55
33
|
* @returns {Middleware} Express-compatible middleware
|
|
56
34
|
*/
|
|
57
35
|
export declare function timeout(timeoutMs?: number): Middleware;
|
|
36
|
+
/**
|
|
37
|
+
* Creates an Express middleware that initializes a per-request context.
|
|
38
|
+
*
|
|
39
|
+
* @param {object} [options] - Optional configuration
|
|
40
|
+
* @param {string} [options.headerName='x-request-id'] - Header to look for request ID
|
|
41
|
+
* @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
|
|
42
|
+
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
|
|
43
|
+
*/
|
|
44
|
+
export declare function setupRequestContext(options?: {
|
|
45
|
+
headerName?: string;
|
|
46
|
+
autoLog?: boolean;
|
|
47
|
+
}): Middleware;
|
|
48
|
+
export interface ErrorHandlerOptions {
|
|
49
|
+
/** Whether to log errors (default: true) */
|
|
50
|
+
logErrors?: boolean;
|
|
51
|
+
/** Whether to include error details in non-production (default: false) */
|
|
52
|
+
includeDetails?: boolean;
|
|
53
|
+
}
|
|
58
54
|
/**
|
|
59
55
|
* Global error handling middleware with enhanced features.
|
|
60
56
|
*
|
|
61
|
-
* @param {
|
|
57
|
+
* @param {ErrorHandlerOptions} options - Error handler options
|
|
62
58
|
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
63
59
|
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
64
|
-
* @
|
|
65
|
-
*
|
|
60
|
+
* @returns Error middleware
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* import express from 'express';
|
|
64
|
+
* import { errorHandler } from '@catbee/utils';
|
|
65
|
+
*
|
|
66
|
+
* const app = express();
|
|
67
|
+
*
|
|
68
|
+
* // Your routes
|
|
69
|
+
* app.get('/ping', (req, res) => {
|
|
70
|
+
* throw new Error('Something went wrong');
|
|
71
|
+
* });
|
|
72
|
+
*
|
|
73
|
+
* // Error handler (must be last middleware)
|
|
74
|
+
* app.use(errorHandler({ includeDetails: true }));
|
|
75
|
+
*
|
|
76
|
+
* app.listen(3000, () => {
|
|
77
|
+
* console.log('Server running on port 3000');
|
|
78
|
+
* });
|
|
66
79
|
*/
|
|
67
|
-
export declare function errorHandler(options?:
|
|
68
|
-
logErrors?: boolean;
|
|
69
|
-
includeDetails?: boolean;
|
|
70
|
-
logger?: (message: string, error: any) => void;
|
|
71
|
-
}): (err: any, req: Request, res: Response, _next: NextFunction) => void;
|
|
72
|
-
export {};
|
|
80
|
+
export declare function errorHandler(options?: ErrorHandlerOptions): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
|
|
73
81
|
//# sourceMappingURL=middleware.utils.d.ts.map
|
|
@@ -3,14 +3,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.requestId = requestId;
|
|
4
4
|
exports.responseTime = responseTime;
|
|
5
5
|
exports.timeout = timeout;
|
|
6
|
+
exports.setupRequestContext = setupRequestContext;
|
|
6
7
|
exports.errorHandler = errorHandler;
|
|
7
|
-
const crypto_1 = require("crypto");
|
|
8
8
|
const config_1 = require("../config");
|
|
9
9
|
const id_utils_1 = require("./id.utils");
|
|
10
10
|
const http_status_codes_1 = require("./http-status-codes");
|
|
11
11
|
const response_utils_1 = require("./response.utils");
|
|
12
12
|
const env_utils_1 = require("./env.utils");
|
|
13
13
|
const logger_utils_1 = require("./logger.utils");
|
|
14
|
+
const context_store_utils_1 = require("./context-store.utils");
|
|
14
15
|
/**
|
|
15
16
|
* Attaches a unique request ID to each request.
|
|
16
17
|
* Useful for request tracing and correlation between logs.
|
|
@@ -26,7 +27,7 @@ function requestId(options) {
|
|
|
26
27
|
return (req, res, next) => {
|
|
27
28
|
// Use existing request ID from header or generate a new one
|
|
28
29
|
const existingId = req.headers[headerName.toLowerCase()];
|
|
29
|
-
const id = existingId || (0,
|
|
30
|
+
const id = existingId || (0, id_utils_1.uuid)();
|
|
30
31
|
// Attach ID to request object
|
|
31
32
|
req.id = id;
|
|
32
33
|
// Add ID to response headers
|
|
@@ -49,22 +50,23 @@ function responseTime(options) {
|
|
|
49
50
|
const logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
|
|
50
51
|
return (req, res, next) => {
|
|
51
52
|
const start = process.hrtime();
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
res.on('finish', () => {
|
|
59
|
-
const duration = calculateDuration();
|
|
60
|
-
if (addHeader) {
|
|
53
|
+
if (addHeader) {
|
|
54
|
+
// Wrap res.end to set header just before sending response
|
|
55
|
+
const originalEnd = res.end;
|
|
56
|
+
res.end = function (chunk, encoding, cb) {
|
|
57
|
+
const diff = process.hrtime(start);
|
|
58
|
+
const duration = diff[0] * 1e3 + diff[1] * 1e-6;
|
|
61
59
|
res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
60
|
+
return originalEnd.call(this, chunk, encoding, cb);
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (logOnComplete) {
|
|
64
|
+
res.on('finish', () => {
|
|
65
|
+
const diff = process.hrtime(start);
|
|
66
|
+
const duration = diff[0] * 1e3 + diff[1] * 1e-6;
|
|
67
|
+
(0, logger_utils_1.getLogger)().info(`${req.method} ${req.url} - ${duration.toFixed(2)}ms`);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
68
70
|
next();
|
|
69
71
|
};
|
|
70
72
|
}
|
|
@@ -75,7 +77,7 @@ function responseTime(options) {
|
|
|
75
77
|
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
|
|
76
78
|
* @returns {Middleware} Express-compatible middleware
|
|
77
79
|
*/
|
|
78
|
-
function timeout(timeoutMs = config_1.
|
|
80
|
+
function timeout(timeoutMs = config_1.config.http.timeout) {
|
|
79
81
|
return (req, res, next) => {
|
|
80
82
|
// Set timeout for the request
|
|
81
83
|
const timer = setTimeout(() => {
|
|
@@ -94,55 +96,69 @@ function timeout(timeoutMs = config_1.Config.Http.timeout) {
|
|
|
94
96
|
};
|
|
95
97
|
}
|
|
96
98
|
/**
|
|
97
|
-
* Creates
|
|
99
|
+
* Creates an Express middleware that initializes a per-request context.
|
|
98
100
|
*
|
|
99
|
-
* @param {
|
|
100
|
-
* @param {
|
|
101
|
-
* @param {
|
|
102
|
-
* @
|
|
103
|
-
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
104
|
-
* @returns {object} Formatted error response
|
|
101
|
+
* @param {object} [options] - Optional configuration
|
|
102
|
+
* @param {string} [options.headerName='x-request-id'] - Header to look for request ID
|
|
103
|
+
* @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
|
|
104
|
+
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
|
|
105
105
|
*/
|
|
106
|
-
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
106
|
+
function setupRequestContext(options = {}) {
|
|
107
|
+
const { headerName = 'x-request-id', autoLog = true } = options;
|
|
108
|
+
return (req, _res, next) => {
|
|
109
|
+
// Generate or use existing request ID
|
|
110
|
+
const requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || (0, id_utils_1.uuid)();
|
|
111
|
+
context_store_utils_1.ContextStore.run({ [context_store_utils_1.StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
112
|
+
// Create a child logger for this request
|
|
113
|
+
const childLogger = (0, logger_utils_1.getLogger)().child({
|
|
114
|
+
requestId,
|
|
115
|
+
method: req.method,
|
|
116
|
+
url: req.originalUrl || req.url
|
|
117
|
+
});
|
|
118
|
+
// Store logger in context
|
|
119
|
+
context_store_utils_1.ContextStore.set(context_store_utils_1.StoreKeys.LOGGER, childLogger);
|
|
120
|
+
if (autoLog) {
|
|
121
|
+
childLogger.info('Request context initialized');
|
|
122
|
+
}
|
|
123
|
+
next();
|
|
124
|
+
});
|
|
115
125
|
};
|
|
116
|
-
|
|
117
|
-
if (error === null || error === void 0 ? void 0 : error.code) {
|
|
118
|
-
response.code = error.code;
|
|
119
|
-
}
|
|
120
|
-
// Include stack trace in development mode if requested
|
|
121
|
-
if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
|
|
122
|
-
response.stack = error.stack.split('\n').map((line) => line.trim());
|
|
123
|
-
}
|
|
124
|
-
return response;
|
|
125
|
-
};
|
|
126
|
+
}
|
|
126
127
|
/**
|
|
127
128
|
* Global error handling middleware with enhanced features.
|
|
128
129
|
*
|
|
129
|
-
* @param {
|
|
130
|
+
* @param {ErrorHandlerOptions} options - Error handler options
|
|
130
131
|
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
131
132
|
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
132
|
-
* @
|
|
133
|
-
*
|
|
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
|
+
* });
|
|
134
152
|
*/
|
|
135
153
|
function errorHandler(options) {
|
|
136
154
|
const logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
|
|
137
155
|
const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
|
|
138
|
-
const logger = (options === null || options === void 0 ? void 0 : options.logger) || (0, logger_utils_1.getLogger)().error;
|
|
139
156
|
return (err, req, res, _next) => {
|
|
140
157
|
// Determine status code
|
|
141
158
|
const status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || http_status_codes_1.HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
142
159
|
// Log error if enabled
|
|
143
160
|
if (logErrors) {
|
|
144
|
-
|
|
145
|
-
logger(logMessage, err);
|
|
161
|
+
(0, logger_utils_1.getLogger)().error({ error: err }, `${err.message || 'Unknown error'}`);
|
|
146
162
|
}
|
|
147
163
|
// Handle ErrorResponse instances (our custom error class)
|
|
148
164
|
if (err instanceof response_utils_1.ErrorResponse) {
|
|
@@ -154,6 +170,26 @@ function errorHandler(options) {
|
|
|
154
170
|
path: req.originalUrl || req.url
|
|
155
171
|
});
|
|
156
172
|
}
|
|
173
|
+
const createErrorResponse = (message, req, error, options) => {
|
|
174
|
+
const isDev = env_utils_1.Env.isDev();
|
|
175
|
+
const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
|
|
176
|
+
const response = {
|
|
177
|
+
error: true,
|
|
178
|
+
message,
|
|
179
|
+
timestamp: new Date().toISOString(),
|
|
180
|
+
requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || (0, id_utils_1.uuid)(),
|
|
181
|
+
path: req.originalUrl || req.url
|
|
182
|
+
};
|
|
183
|
+
// Include error code if present
|
|
184
|
+
if (error === null || error === void 0 ? void 0 : error.code) {
|
|
185
|
+
response.code = error.code;
|
|
186
|
+
}
|
|
187
|
+
// Include stack trace in development mode if requested
|
|
188
|
+
if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
|
|
189
|
+
response.stack = error.stack.split('\n').map((line) => line.trim());
|
|
190
|
+
}
|
|
191
|
+
return response;
|
|
192
|
+
};
|
|
157
193
|
// Handle any other errors
|
|
158
194
|
return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', req, err, {
|
|
159
195
|
includeDetails
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":";;AA6CA,8BAmBC;AAUD,oCA6BC;AASD,0BAmBC;AA8CD,oCAqCC;AAtND,mCAAoC;AACpC,sCAAmC;AACnC,yCAAkC;AAClC,2DAAsD;AACtD,qDAAiD;AACjD,2CAAkC;AAClC,iDAA2C;AA8B3C;;;;;;;;GAQG;AACH,SAAgB,SAAS,CAAC,OAAyD;IACjF,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,MAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IAErD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,4DAA4D;QAC5D,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;QACzD,MAAM,EAAE,GAAI,UAAqB,IAAI,IAAA,mBAAU,GAAE,CAAC;QAElD,8BAA8B;QAC9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AM,UAAU,GAAG,WAAW,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,OAAO,IAAI,eAAe,EAAE,CAAC;YAC5G,MAAM,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAC1B,CAAC;QAED,0DAA0D;QAC1D,IAAI,GAAG,YAAY,8BAAa,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,IAAA,eAAI,GAAE;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;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":";;AAoBA,8BAmBC;AAUD,oCA4BC;AASD,0BAmBC;AAUD,kDAwBC;AAmCD,oCAwDC;AAtOD,sCAAmC;AACnC,yCAAkC;AAClC,2DAAsD;AACtD,qDAAiD;AACjD,2CAAkC;AAClC,iDAA2C;AAE3C,+DAAgE;AAIhE;;;;;;;;GAQG;AACH,SAAgB,SAAS,CAAC,OAAyD;IACjF,MAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,MAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IAErD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACxB,4DAA4D;QAC5D,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;QACzD,MAAM,EAAE,GAAI,UAAqB,IAAI,IAAA,eAAI,GAAE,CAAC;QAE5C,8BAA8B;QAC7B,GAAW,CAAC,EAAE,GAAG,EAAE,CAAC;QAErB,6BAA6B;QAC7B,IAAI,YAAY,EAAE,CAAC;YACjB,GA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uD;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,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,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;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,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
|