@catbee/utils 0.0.3 → 0.0.4
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 +1 -4
- package/build/esm/config.d.ts +0 -4
- package/build/esm/config.js +1 -5
- package/build/esm/config.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +1 -17
- package/build/esm/utils/decorators.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.js +3 -5
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +16 -28
- package/build/esm/utils/middleware.utils.js +65 -44
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esnext/config.d.ts +0 -4
- package/build/esnext/config.js +1 -5
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +1 -17
- package/build/esnext/utils/decorators.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.js +3 -5
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +16 -28
- package/build/esnext/utils/middleware.utils.js +63 -44
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/src/config.d.ts +0 -4
- package/build/src/config.js +1 -5
- package/build/src/config.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +1 -17
- package/build/src/utils/decorators.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.js +3 -5
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +16 -28
- package/build/src/utils/middleware.utils.js +64 -44
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/package.json +3 -3
package/build/esnext/config.js
CHANGED
|
@@ -11,11 +11,7 @@ export const Config = {
|
|
|
11
11
|
/**
|
|
12
12
|
* Name of the logger instance (defaults to npm package name).
|
|
13
13
|
*/
|
|
14
|
-
name: Env.get('LOGGER_NAME', Env.get('npm_package_name', '@catbee/utils'))
|
|
15
|
-
/**
|
|
16
|
-
* Whether to use ISO 8601 timestamps in logs.
|
|
17
|
-
*/
|
|
18
|
-
isoTimestamp: Env.getBoolean('LOGGER_ISO_TIMESTAMP', false)
|
|
14
|
+
name: Env.get('LOGGER_NAME', Env.get('npm_package_name', '@catbee/utils'))
|
|
19
15
|
},
|
|
20
16
|
Http: {
|
|
21
17
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAIxC;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB,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;
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAIxC;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB,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;KAC3E;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,mBAAmB,EAAE,GAAG,CAAC;KACpD;CACF,CAAC","sourcesContent":["import { Env } from './utils/env.utils';\n\ntype LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent';\n\n/**\n * Application runtime configuration loaded from environment variables.\n */\nexport const 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 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', 300)\n }\n};\n"]}
|
|
@@ -1,20 +1,5 @@
|
|
|
1
|
+
import type { RequestHandler, Router } from 'express';
|
|
1
2
|
import 'reflect-metadata';
|
|
2
|
-
interface Request {
|
|
3
|
-
query: any;
|
|
4
|
-
params: any;
|
|
5
|
-
body?: any;
|
|
6
|
-
[key: string]: any;
|
|
7
|
-
}
|
|
8
|
-
interface Response {
|
|
9
|
-
json: (body: any) => void;
|
|
10
|
-
headersSent: boolean;
|
|
11
|
-
[key: string]: any;
|
|
12
|
-
}
|
|
13
|
-
type NextFunction = (err?: any) => void;
|
|
14
|
-
type RequestHandler = (req: Request, res: Response, next: NextFunction) => any;
|
|
15
|
-
interface Router {
|
|
16
|
-
[method: string]: (path: string, ...handlers: RequestHandler[]) => void;
|
|
17
|
-
}
|
|
18
3
|
export declare const Get: (path: string) => MethodDecorator;
|
|
19
4
|
export declare const Post: (path: string) => MethodDecorator;
|
|
20
5
|
export declare const Put: (path: string) => MethodDecorator;
|
|
@@ -36,5 +21,4 @@ export declare function Header(name: string, value: string): MethodDecorator;
|
|
|
36
21
|
export declare function Before(fn: Function): MethodDecorator;
|
|
37
22
|
export declare function After(fn: Function): MethodDecorator;
|
|
38
23
|
export declare function registerControllers(router: Router, controllers: any[]): void;
|
|
39
|
-
export {};
|
|
40
24
|
//# sourceMappingURL=decorators.utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAEtD,OAAO,kBAAkB,CAAC;AAmB1B,wCAAwC;AAExC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AAgBpC,6BAA6B;AAC7B,SAAS,oBAAoB,CAAC,MAAkB;IAC9C,OAAO,CAAC,IAAY,EAAmB,EAAE;QACvC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE;YACzC,MAAM,MAAM,GAAsB,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;YAC5F,MAAM,CAAC,IAAI,CAAC;gBACV,IAAI;gBACJ,MAAM;gBACN,WAAW,EAAE,WAAqB;aACnC,CAAC,CAAC;YACH,OAAO,CAAC,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;QACjE,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,GAAG,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,IAAI,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC;AACjD,MAAM,CAAC,MAAM,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M,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;4BAAE,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport 'reflect-metadata';\n\n// --- Sample Express interfaces for type safety ---\ninterface Request {\n query: any;\n params: any;\n body?: any;\n [key: string]: any;\n}\ninterface Response {\n json: (body: any) => void;\n headersSent: boolean;\n [key: string]: any;\n}\ntype NextFunction = (err?: any) => void;\ntype RequestHandler = (req: Request, res: Response, next: NextFunction) => any;\ninterface Router {\n [method: string]: (path: string, ...handlers: RequestHandler[]) => void;\n}\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator('get');\nexport const Post = createRouteDecorator('post');\nexport const Put = createRouteDecorator('put');\nexport const Patch = createRouteDecorator('patch');\nexport const Delete = createRouteDecorator('delete');\nexport const Options = createRouteDecorator('options');\nexport const Head = createRouteDecorator('head');\nexport const Trace = createRouteDecorator('trace');\nexport const Connect = createRouteDecorator('connect');\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator('query');\nexport const Param = createParamDecorator('param');\nexport const Body = createParamDecorator('body');\nexport const Req = createParamDecorator('req');\nexport const Res = createParamDecorator('res');\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol('httpCode');\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol('headers');\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAGtD,OAAO,kBAAkB,CAAC;AAE1B,wCAAwC;AAExC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AAgBpC,6BAA6B;AAC7B,SAAS,oBAAoB,CAAC,MAAkB;IAC9C,OAAO,CAAC,IAAY,EAAmB,EAAE;QACvC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE;YACzC,MAAM,MAAM,GAAsB,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;YAC5F,MAAM,CAAC,IAAI,CAAC;gBACV,IAAI;gBACJ,MAAM;gBACN,WAAW,EAAE,WAAqB;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AAI,CAAC,CAAC;oBACvD,uCAAuC;oBACvC,MAAM,OAAO,GAAG,MAAM,YAAY,OAAO,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC;oBAClE,IAAI,CAAC,GAAG,CAAC,WAAW,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;wBACvD,IAAI,QAAQ;4BAAE,MAAA,GAAG,CAAC,MAAM,oDAAG,QAAQ,CAAC,CAAC;wBACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;4BAAE,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type { RequestHandler, Router } from 'express';\nimport 'reflect-metadata';\n\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator('get');\nexport const Post = createRouteDecorator('post');\nexport const Put = createRouteDecorator('put');\nexport const Patch = createRouteDecorator('patch');\nexport const Delete = createRouteDecorator('delete');\nexport const Options = createRouteDecorator('options');\nexport const Head = createRouteDecorator('head');\nexport const Trace = createRouteDecorator('trace');\nexport const Connect = createRouteDecorator('connect');\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator('query');\nexport const Param = createParamDecorator('param');\nexport const Body = createParamDecorator('body');\nexport const Req = createParamDecorator('req');\nexport const Res = createParamDecorator('res');\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol('httpCode');\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol('headers');\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
@@ -344,7 +344,7 @@ export function withErrorHandling(handler) {
|
|
|
344
344
|
throw error;
|
|
345
345
|
}
|
|
346
346
|
// Log the original error (consider using a proper logger)
|
|
347
|
-
getLogger().error('Caught error in handler
|
|
347
|
+
getLogger().error({ error }, 'Caught error in handler');
|
|
348
348
|
// Extract status code if it exists, otherwise use 500
|
|
349
349
|
let status = HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
350
350
|
if (hasErrorShape(error) && typeof error.status === 'number') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exception.utils.js","sourceRoot":"","sources":["../../../src/utils/exception.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM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K,EAAE,GAAG,IAAmB,EAAE,EAAE;QACtC,IAAI,CAAC;YACH,OAAO,MAAM,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;QAChC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvB,MAAM,KAAK,CAAC;YACd,CAAC;YAED,0DAA0D;YAC1D,SAAS,EAAE,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;YAErD,sDAAsD;YACtD,IAAI,MAAM,GAAG,eAAe,CAAC,qBAAqB,CAAC;YACnD,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;gBAC7D,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;YACxB,CAAC;YAED,gCAAgC;YAChC,MAAM,eAAe,CAAC,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACxD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { HttpStatusCodes } from './http-status-codes';\nimport { getLogger } from './logger.utils';\nimport { ErrorResponse } from './response.utils';\n\n/**\n * Generic HTTP error class used for custom exceptions with any status code.\n * Inherit this when you need to throw errors dynamically at runtime.\n */\nexport class HttpError extends ErrorResponse {\n /**\n * Creates a new HTTP error instance.\n * @param status - A valid HTTP status code (e.g., 400, 500).\n * @param message - The error message to return to the client.\n */\n constructor(status: number, message: string) {\n super(message);\n this.status = status;\n }\n}\n\n/**\n * Represents a 500 Internal Server Error.\n * Use this for unexpected backend errors that are not caused by the client.\n */\nexport class InternalServerErrorException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Internal server error\".\n */\n constructor(message: string = 'Internal server error') {\n super(message);\n this.status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n }\n}\n\n/**\n * Represents a 401 Unauthorized Error.\n * Indicates that authentication is required and has failed or not been provided.\n */\nexport class UnauthorizedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unauthorized\".\n */\n constructor(message: string = 'Unauthorized') {\n super(message);\n this.status = HttpStatusCodes.UNAUTHORIZED;\n }\n}\n\n/**\n * Represents a 400 Bad Request Error.\n * Indicates that the client has sent invalid data (e.g., malformed request body).\n */\nexport class BadRequestException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad request\".\n */\n constructor(message: string = 'Bad request') {\n super(message);\n this.status = HttpStatusCodes.BAD_REQUEST;\n }\n}\n\n/**\n * Represents a 404 Not Found Error.\n * Used when a requested resource (e.g., user, file) could not be located.\n */\nexport class NotFoundException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Resource not found\".\n */\n constructor(message: string = 'Resource not found') {\n super(message);\n this.status = HttpStatusCodes.NOT_FOUND;\n }\n}\n\n/**\n * Represents a 403 Forbidden Error.\n * Indicates that the client is authenticated but not allowed to access the resource.\n */\nexport class ForbiddenException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Forbidden\".\n */\n constructor(message: string = 'Forbidden') {\n super(message);\n this.status = HttpStatusCodes.FORBIDDEN;\n }\n}\n\n/**\n * Represents a 409 Conflict Error.\n * Commonly used when a resource already exists or a versioning conflict occurs.\n */\nexport class ConflictException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Conflict\".\n */\n constructor(message: string = 'Conflict') {\n super(message);\n this.status = HttpStatusCodes.CONFLICT;\n }\n}\n\n/**\n * Represents a 502 Bad Gateway Error.\n * Used when the server receives an invalid response from an upstream server.\n */\nexport class BadGatewayException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad Gateway\".\n */\n constructor(message: string = 'Bad Gateway') {\n super(message);\n this.status = HttpStatusCodes.BAD_GATEWAY;\n }\n}\n\n/**\n * Represents a 429 Too Many Requests Error.\n * Returned when the client has hit a rate limit.\n */\nexport class TooManyRequestsException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Too many requests\".\n */\n constructor(message: string = 'Too many requests') {\n super(message);\n this.status = HttpStatusCodes.TOO_MANY_REQUESTS;\n }\n}\n\n/**\n * Represents a 503 Service Unavailable Error.\n * Indicates that the server is temporarily unavailable (e.g., for maintenance).\n */\nexport class ServiceUnavailableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Service Unavailable\".\n */\n constructor(message: string = 'Service Unavailable') {\n super(message);\n this.status = HttpStatusCodes.SERVICE_UNAVAILABLE;\n }\n}\n\n/**\n * Represents a 504 Gateway Timeout Error.\n * Returned when the server acting as a gateway times out waiting for a response.\n */\nexport class GatewayTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Gateway Timeout\".\n */\n constructor(message: string = 'Gateway Timeout') {\n super(message);\n this.status = HttpStatusCodes.GATEWAY_TIMEOUT;\n }\n}\n\n/**\n * Represents a 422 Unprocessable Entity Error.\n * Used when the server understands the content type but cannot process the contained instructions.\n */\nexport class UnprocessableEntityException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unprocessable Entity\".\n * @param details - Optional validation details or additional error context.\n */\n constructor(\n message: string = 'Unprocessable Entity',\n public details?: Record<string, any>\n ) {\n super(message);\n this.status = HttpStatusCodes.UNPROCESSABLE_ENTITY;\n }\n}\n\n/**\n * Represents a 405 Method Not Allowed Error.\n * Used when the request method is not supported for the requested resource.\n */\nexport class MethodNotAllowedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Method Not Allowed\".\n * @param allowedMethods - Optional array of allowed HTTP methods.\n */\n constructor(\n message: string = 'Method Not Allowed',\n public allowedMethods?: string[]\n ) {\n super(message);\n this.status = HttpStatusCodes.METHOD_NOT_ALLOWED;\n }\n}\n\n/**\n * Represents a 406 Not Acceptable Error.\n * Used when the server cannot produce a response matching the client's accepted content types.\n */\nexport class NotAcceptableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Not Acceptable\".\n */\n constructor(message: string = 'Not Acceptable') {\n super(message);\n this.status = HttpStatusCodes.NOT_ACCEPTABLE;\n }\n}\n\n/**\n * Represents a 408 Request Timeout Error.\n * Used when the server times out waiting for the client to send a request.\n */\nexport class RequestTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Request Timeout\".\n */\n constructor(message: string = 'Request Timeout') {\n super(message);\n this.status = HttpStatusCodes.REQUEST_TIMEOUT;\n }\n}\n\n/**\n * Represents a 415 Unsupported Media Type Error.\n * Used when the request's Content-Type is not supported.\n */\nexport class UnsupportedMediaTypeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unsupported Media Type\".\n */\n constructor(message: string = 'Unsupported Media Type') {\n super(message);\n this.status = HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE;\n }\n}\n\n/**\n * Represents a 413 Payload Too Large Error.\n * Used when the request body exceeds server limits.\n */\nexport class PayloadTooLargeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Payload Too Large\".\n */\n constructor(message: string = 'Payload Too Large') {\n super(message);\n this.status = HttpStatusCodes.PAYLOAD_TOO_LARGE;\n }\n}\n\n/**\n * Represents a 507 Insufficient Storage Error.\n * Used when the server has insufficient storage to complete the request.\n */\nexport class InsufficientStorageException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Insufficient Storage\".\n */\n constructor(message: string = 'Insufficient Storage') {\n super(message);\n this.status = HttpStatusCodes.INSUFFICIENT_STORAGE;\n }\n}\n\n/**\n * Checks if an error is an instance of HttpError or its subclasses.\n *\n * @param error - The error to check.\n * @returns True if the error is an HttpError, false otherwise.\n */\nexport function isHttpError(error: unknown): error is ErrorResponse {\n return error instanceof ErrorResponse;\n}\n\n/**\n * Creates an HTTP error with the specified status code and message.\n * Factory function for creating appropriate HTTP error instances.\n *\n * @param status - HTTP status code.\n * @param message - Optional custom error message.\n * @returns An instance of the appropriate HTTP error class.\n */\nexport function createHttpError(status: number, message?: string): ErrorResponse {\n switch (status) {\n case HttpStatusCodes.BAD_REQUEST:\n return new BadRequestException(message);\n case HttpStatusCodes.UNAUTHORIZED:\n return new UnauthorizedException(message);\n case HttpStatusCodes.FORBIDDEN:\n return new ForbiddenException(message);\n case HttpStatusCodes.NOT_FOUND:\n return new NotFoundException(message);\n case HttpStatusCodes.METHOD_NOT_ALLOWED:\n return new MethodNotAllowedException(message);\n case HttpStatusCodes.NOT_ACCEPTABLE:\n return new NotAcceptableException(message);\n case HttpStatusCodes.REQUEST_TIMEOUT:\n return new RequestTimeoutException(message);\n case HttpStatusCodes.CONFLICT:\n return new ConflictException(message);\n case HttpStatusCodes.GONE:\n return new HttpError(HttpStatusCodes.GONE, message || 'Gone');\n case HttpStatusCodes.PAYLOAD_TOO_LARGE:\n return new PayloadTooLargeException(message);\n case HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE:\n return new UnsupportedMediaTypeException(message);\n case HttpStatusCodes.UNPROCESSABLE_ENTITY:\n return new UnprocessableEntityException(message);\n case HttpStatusCodes.TOO_MANY_REQUESTS:\n return new TooManyRequestsException(message);\n case HttpStatusCodes.INTERNAL_SERVER_ERROR:\n return new InternalServerErrorException(message);\n case HttpStatusCodes.BAD_GATEWAY:\n return new BadGatewayException(message);\n case HttpStatusCodes.SERVICE_UNAVAILABLE:\n return new ServiceUnavailableException(message);\n case HttpStatusCodes.GATEWAY_TIMEOUT:\n return new GatewayTimeoutException(message);\n case HttpStatusCodes.INSUFFICIENT_STORAGE:\n return new InsufficientStorageException(message);\n default:\n return new HttpError(status, message || `HTTP Error ${status}`);\n }\n}\n\n/**\n * Type guard to check if an object has specific error properties.\n *\n * @param error - The object to check.\n * @returns True if object has error-like structure.\n */\nexport function hasErrorShape(error: unknown): error is { message: string; status?: number; code?: string } {\n return (\n typeof error === 'object' && error !== null && 'message' in error && typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Safely extracts message from any error type.\n *\n * @param error - Any error object or value.\n * @returns A string error message.\n */\nexport function getErrorMessage(error: unknown): string {\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n if (hasErrorShape(error)) {\n return error.message;\n }\n\n return 'Unknown error occurred';\n}\n\n/**\n * Wraps a function and transforms any errors into HTTP errors.\n * Useful for API handlers to ensure consistent error responses.\n *\n * @param handler - The async function to wrap.\n * @returns A function that always returns or throws an HTTP error.\n */\nexport function withErrorHandling<T extends (...args: any[]) => Promise<any>>(\n handler: T\n): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> {\n return async (...args: Parameters<T>) => {\n try {\n return await handler(...args);\n } catch (error) {\n if (isHttpError(error)) {\n throw error;\n }\n\n // Log the original error (consider using a proper logger)\n getLogger().error('Caught error in handler:', error);\n\n // Extract status code if it exists, otherwise use 500\n let status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n if (hasErrorShape(error) && typeof error.status === 'number') {\n status = error.status;\n }\n\n // Create appropriate HTTP error\n throw createHttpError(status, getErrorMessage(error));\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"exception.utils.js","sourceRoot":"","sources":["../../../src/utils/exception.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD;;;GAGG;AACH,MAAM,OAAO,SAAU,SAAQ,aAAa;IAC1C;;;;OAIG;IACH,YAAY,MAAc,EAAE,OAAe;QACzC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,4BAA6B,SAAQ,aAAa;IAC7D;;OAEG;IACH,YAAY,UAAkB,uBAAuB;QACnD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,eAAe,CAAC,qBAAqB,CAAC;IACt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,IAAI,aAAa,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;gBAC7D,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;YACxB,CAAC;YAED,gCAAgC;YAChC,MAAM,eAAe,CAAC,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC;QACxD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { HttpStatusCodes } from './http-status-codes';\nimport { getLogger } from './logger.utils';\nimport { ErrorResponse } from './response.utils';\n\n/**\n * Generic HTTP error class used for custom exceptions with any status code.\n * Inherit this when you need to throw errors dynamically at runtime.\n */\nexport class HttpError extends ErrorResponse {\n /**\n * Creates a new HTTP error instance.\n * @param status - A valid HTTP status code (e.g., 400, 500).\n * @param message - The error message to return to the client.\n */\n constructor(status: number, message: string) {\n super(message);\n this.status = status;\n }\n}\n\n/**\n * Represents a 500 Internal Server Error.\n * Use this for unexpected backend errors that are not caused by the client.\n */\nexport class InternalServerErrorException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Internal server error\".\n */\n constructor(message: string = 'Internal server error') {\n super(message);\n this.status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n }\n}\n\n/**\n * Represents a 401 Unauthorized Error.\n * Indicates that authentication is required and has failed or not been provided.\n */\nexport class UnauthorizedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unauthorized\".\n */\n constructor(message: string = 'Unauthorized') {\n super(message);\n this.status = HttpStatusCodes.UNAUTHORIZED;\n }\n}\n\n/**\n * Represents a 400 Bad Request Error.\n * Indicates that the client has sent invalid data (e.g., malformed request body).\n */\nexport class BadRequestException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad request\".\n */\n constructor(message: string = 'Bad request') {\n super(message);\n this.status = HttpStatusCodes.BAD_REQUEST;\n }\n}\n\n/**\n * Represents a 404 Not Found Error.\n * Used when a requested resource (e.g., user, file) could not be located.\n */\nexport class NotFoundException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Resource not found\".\n */\n constructor(message: string = 'Resource not found') {\n super(message);\n this.status = HttpStatusCodes.NOT_FOUND;\n }\n}\n\n/**\n * Represents a 403 Forbidden Error.\n * Indicates that the client is authenticated but not allowed to access the resource.\n */\nexport class ForbiddenException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Forbidden\".\n */\n constructor(message: string = 'Forbidden') {\n super(message);\n this.status = HttpStatusCodes.FORBIDDEN;\n }\n}\n\n/**\n * Represents a 409 Conflict Error.\n * Commonly used when a resource already exists or a versioning conflict occurs.\n */\nexport class ConflictException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Conflict\".\n */\n constructor(message: string = 'Conflict') {\n super(message);\n this.status = HttpStatusCodes.CONFLICT;\n }\n}\n\n/**\n * Represents a 502 Bad Gateway Error.\n * Used when the server receives an invalid response from an upstream server.\n */\nexport class BadGatewayException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Bad Gateway\".\n */\n constructor(message: string = 'Bad Gateway') {\n super(message);\n this.status = HttpStatusCodes.BAD_GATEWAY;\n }\n}\n\n/**\n * Represents a 429 Too Many Requests Error.\n * Returned when the client has hit a rate limit.\n */\nexport class TooManyRequestsException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Too many requests\".\n */\n constructor(message: string = 'Too many requests') {\n super(message);\n this.status = HttpStatusCodes.TOO_MANY_REQUESTS;\n }\n}\n\n/**\n * Represents a 503 Service Unavailable Error.\n * Indicates that the server is temporarily unavailable (e.g., for maintenance).\n */\nexport class ServiceUnavailableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Service Unavailable\".\n */\n constructor(message: string = 'Service Unavailable') {\n super(message);\n this.status = HttpStatusCodes.SERVICE_UNAVAILABLE;\n }\n}\n\n/**\n * Represents a 504 Gateway Timeout Error.\n * Returned when the server acting as a gateway times out waiting for a response.\n */\nexport class GatewayTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Gateway Timeout\".\n */\n constructor(message: string = 'Gateway Timeout') {\n super(message);\n this.status = HttpStatusCodes.GATEWAY_TIMEOUT;\n }\n}\n\n/**\n * Represents a 422 Unprocessable Entity Error.\n * Used when the server understands the content type but cannot process the contained instructions.\n */\nexport class UnprocessableEntityException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unprocessable Entity\".\n * @param details - Optional validation details or additional error context.\n */\n constructor(\n message: string = 'Unprocessable Entity',\n public details?: Record<string, any>\n ) {\n super(message);\n this.status = HttpStatusCodes.UNPROCESSABLE_ENTITY;\n }\n}\n\n/**\n * Represents a 405 Method Not Allowed Error.\n * Used when the request method is not supported for the requested resource.\n */\nexport class MethodNotAllowedException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Method Not Allowed\".\n * @param allowedMethods - Optional array of allowed HTTP methods.\n */\n constructor(\n message: string = 'Method Not Allowed',\n public allowedMethods?: string[]\n ) {\n super(message);\n this.status = HttpStatusCodes.METHOD_NOT_ALLOWED;\n }\n}\n\n/**\n * Represents a 406 Not Acceptable Error.\n * Used when the server cannot produce a response matching the client's accepted content types.\n */\nexport class NotAcceptableException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Not Acceptable\".\n */\n constructor(message: string = 'Not Acceptable') {\n super(message);\n this.status = HttpStatusCodes.NOT_ACCEPTABLE;\n }\n}\n\n/**\n * Represents a 408 Request Timeout Error.\n * Used when the server times out waiting for the client to send a request.\n */\nexport class RequestTimeoutException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Request Timeout\".\n */\n constructor(message: string = 'Request Timeout') {\n super(message);\n this.status = HttpStatusCodes.REQUEST_TIMEOUT;\n }\n}\n\n/**\n * Represents a 415 Unsupported Media Type Error.\n * Used when the request's Content-Type is not supported.\n */\nexport class UnsupportedMediaTypeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Unsupported Media Type\".\n */\n constructor(message: string = 'Unsupported Media Type') {\n super(message);\n this.status = HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE;\n }\n}\n\n/**\n * Represents a 413 Payload Too Large Error.\n * Used when the request body exceeds server limits.\n */\nexport class PayloadTooLargeException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Payload Too Large\".\n */\n constructor(message: string = 'Payload Too Large') {\n super(message);\n this.status = HttpStatusCodes.PAYLOAD_TOO_LARGE;\n }\n}\n\n/**\n * Represents a 507 Insufficient Storage Error.\n * Used when the server has insufficient storage to complete the request.\n */\nexport class InsufficientStorageException extends ErrorResponse {\n /**\n * @param message - Optional custom message. Defaults to \"Insufficient Storage\".\n */\n constructor(message: string = 'Insufficient Storage') {\n super(message);\n this.status = HttpStatusCodes.INSUFFICIENT_STORAGE;\n }\n}\n\n/**\n * Checks if an error is an instance of HttpError or its subclasses.\n *\n * @param error - The error to check.\n * @returns True if the error is an HttpError, false otherwise.\n */\nexport function isHttpError(error: unknown): error is ErrorResponse {\n return error instanceof ErrorResponse;\n}\n\n/**\n * Creates an HTTP error with the specified status code and message.\n * Factory function for creating appropriate HTTP error instances.\n *\n * @param status - HTTP status code.\n * @param message - Optional custom error message.\n * @returns An instance of the appropriate HTTP error class.\n */\nexport function createHttpError(status: number, message?: string): ErrorResponse {\n switch (status) {\n case HttpStatusCodes.BAD_REQUEST:\n return new BadRequestException(message);\n case HttpStatusCodes.UNAUTHORIZED:\n return new UnauthorizedException(message);\n case HttpStatusCodes.FORBIDDEN:\n return new ForbiddenException(message);\n case HttpStatusCodes.NOT_FOUND:\n return new NotFoundException(message);\n case HttpStatusCodes.METHOD_NOT_ALLOWED:\n return new MethodNotAllowedException(message);\n case HttpStatusCodes.NOT_ACCEPTABLE:\n return new NotAcceptableException(message);\n case HttpStatusCodes.REQUEST_TIMEOUT:\n return new RequestTimeoutException(message);\n case HttpStatusCodes.CONFLICT:\n return new ConflictException(message);\n case HttpStatusCodes.GONE:\n return new HttpError(HttpStatusCodes.GONE, message || 'Gone');\n case HttpStatusCodes.PAYLOAD_TOO_LARGE:\n return new PayloadTooLargeException(message);\n case HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE:\n return new UnsupportedMediaTypeException(message);\n case HttpStatusCodes.UNPROCESSABLE_ENTITY:\n return new UnprocessableEntityException(message);\n case HttpStatusCodes.TOO_MANY_REQUESTS:\n return new TooManyRequestsException(message);\n case HttpStatusCodes.INTERNAL_SERVER_ERROR:\n return new InternalServerErrorException(message);\n case HttpStatusCodes.BAD_GATEWAY:\n return new BadGatewayException(message);\n case HttpStatusCodes.SERVICE_UNAVAILABLE:\n return new ServiceUnavailableException(message);\n case HttpStatusCodes.GATEWAY_TIMEOUT:\n return new GatewayTimeoutException(message);\n case HttpStatusCodes.INSUFFICIENT_STORAGE:\n return new InsufficientStorageException(message);\n default:\n return new HttpError(status, message || `HTTP Error ${status}`);\n }\n}\n\n/**\n * Type guard to check if an object has specific error properties.\n *\n * @param error - The object to check.\n * @returns True if object has error-like structure.\n */\nexport function hasErrorShape(error: unknown): error is { message: string; status?: number; code?: string } {\n return (\n typeof error === 'object' && error !== null && 'message' in error && typeof (error as any).message === 'string'\n );\n}\n\n/**\n * Safely extracts message from any error type.\n *\n * @param error - Any error object or value.\n * @returns A string error message.\n */\nexport function getErrorMessage(error: unknown): string {\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n if (hasErrorShape(error)) {\n return error.message;\n }\n\n return 'Unknown error occurred';\n}\n\n/**\n * Wraps a function and transforms any errors into HTTP errors.\n * Useful for API handlers to ensure consistent error responses.\n *\n * @param handler - The async function to wrap.\n * @returns A function that always returns or throws an HTTP error.\n */\nexport function withErrorHandling<T extends (...args: any[]) => Promise<any>>(\n handler: T\n): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> {\n return async (...args: Parameters<T>) => {\n try {\n return await handler(...args);\n } catch (error) {\n if (isHttpError(error)) {\n throw error;\n }\n\n // Log the original error (consider using a proper logger)\n getLogger().error({ error }, 'Caught error in handler');\n\n // Extract status code if it exists, otherwise use 500\n let status = HttpStatusCodes.INTERNAL_SERVER_ERROR;\n if (hasErrorShape(error) && typeof error.status === 'number') {\n status = error.status;\n }\n\n // Create appropriate HTTP error\n throw createHttpError(status, getErrorMessage(error));\n }\n };\n}\n"]}
|
|
@@ -31,11 +31,9 @@ function setupLogger() {
|
|
|
31
31
|
}
|
|
32
32
|
return '***';
|
|
33
33
|
}
|
|
34
|
-
}
|
|
34
|
+
},
|
|
35
|
+
timestamp: stdTimeFunctions.isoTime
|
|
35
36
|
};
|
|
36
|
-
if (Config.Logger.isoTimestamp) {
|
|
37
|
-
logParams.timestamp = stdTimeFunctions.isoTime;
|
|
38
|
-
}
|
|
39
37
|
_global[GLOBAL_LOGGER_KEY] = pino(logParams);
|
|
40
38
|
_global[GLOBAL_LOGGER_KEY].debug('Logger initialized');
|
|
41
39
|
}
|
|
@@ -95,7 +93,7 @@ export function createRequestLogger(requestId, additionalContext = {}) {
|
|
|
95
93
|
export function logError(error, message, context) {
|
|
96
94
|
const logger = getLogger();
|
|
97
95
|
const errObj = error instanceof Error ? error : new Error(String(error));
|
|
98
|
-
const logContext = Object.assign(Object.assign({}, context), {
|
|
96
|
+
const logContext = Object.assign(Object.assign({}, context), { error: errObj });
|
|
99
97
|
logger.error(logContext, message || errObj.message);
|
|
100
98
|
}
|
|
101
99
|
//# sourceMappingURL=logger.utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEhE;;GAEG;AACH,MAAM,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AU,iBAAiB,CAAC,QAA6B,EAAE,YAAyB;IACxF,MAAM,MAAM,GAAG,YAAY,IAAI,SAAS,EAAE,CAAC;IAC3C,OAAO,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;AAChC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,SAAiB,EAAE,oBAAyC,EAAE;IAChG,MAAM,MAAM,GAAG,iBAAiB,iBAC9B,SAAS,IACN,iBAAiB,EACpB,CAAC;IAEH,IAAI,CAAC;QACH,YAAY,CAAC,GAAG,CAAC,SAAS,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,MAAM,UAAU,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';\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 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 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,6 +33,18 @@ 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;
|
|
58
48
|
/**
|
|
59
49
|
* Global error handling middleware with enhanced features.
|
|
60
50
|
*
|
|
@@ -67,7 +57,5 @@ export declare function timeout(timeoutMs?: number): Middleware;
|
|
|
67
57
|
export declare function errorHandler(options?: {
|
|
68
58
|
logErrors?: boolean;
|
|
69
59
|
includeDetails?: boolean;
|
|
70
|
-
|
|
71
|
-
}): (err: any, req: Request, res: Response, _next: NextFunction) => void;
|
|
72
|
-
export {};
|
|
60
|
+
}): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
|
|
73
61
|
//# sourceMappingURL=middleware.utils.d.ts.map
|
|
@@ -5,6 +5,7 @@ import { HttpStatusCodes } from './http-status-codes';
|
|
|
5
5
|
import { ErrorResponse } from './response.utils';
|
|
6
6
|
import { Env } from './env.utils';
|
|
7
7
|
import { getLogger } from './logger.utils';
|
|
8
|
+
import { ContextStore, StoreKeys } from './context-store.utils';
|
|
8
9
|
/**
|
|
9
10
|
* Attaches a unique request ID to each request.
|
|
10
11
|
* Useful for request tracing and correlation between logs.
|
|
@@ -43,22 +44,23 @@ export function responseTime(options) {
|
|
|
43
44
|
const logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
|
|
44
45
|
return (req, res, next) => {
|
|
45
46
|
const start = process.hrtime();
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
res.on('finish', () => {
|
|
53
|
-
const duration = calculateDuration();
|
|
54
|
-
if (addHeader) {
|
|
47
|
+
if (addHeader) {
|
|
48
|
+
// Wrap res.end to set header just before sending response
|
|
49
|
+
const originalEnd = res.end;
|
|
50
|
+
res.end = function (chunk, encoding, cb) {
|
|
51
|
+
const diff = process.hrtime(start);
|
|
52
|
+
const duration = diff[0] * 1e3 + diff[1] * 1e-6;
|
|
55
53
|
res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
54
|
+
return originalEnd.call(this, chunk, encoding, cb);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
if (logOnComplete) {
|
|
58
|
+
res.on('finish', () => {
|
|
59
|
+
const diff = process.hrtime(start);
|
|
60
|
+
const duration = diff[0] * 1e3 + diff[1] * 1e-6;
|
|
61
|
+
getLogger().info(`${req.method} ${req.url} - ${duration.toFixed(2)}ms`);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
62
64
|
next();
|
|
63
65
|
};
|
|
64
66
|
}
|
|
@@ -88,35 +90,34 @@ export function timeout(timeoutMs = Config.Http.timeout) {
|
|
|
88
90
|
};
|
|
89
91
|
}
|
|
90
92
|
/**
|
|
91
|
-
* Creates
|
|
93
|
+
* Creates an Express middleware that initializes a per-request context.
|
|
92
94
|
*
|
|
93
|
-
* @param {
|
|
94
|
-
* @param {
|
|
95
|
-
* @param {
|
|
96
|
-
* @
|
|
97
|
-
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
98
|
-
* @returns {object} Formatted error response
|
|
95
|
+
* @param {object} [options] - Optional configuration
|
|
96
|
+
* @param {string} [options.headerName='x-request-id'] - Header to look for request ID
|
|
97
|
+
* @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
|
|
98
|
+
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
|
|
99
99
|
*/
|
|
100
|
-
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
100
|
+
export function setupRequestContext(options = {}) {
|
|
101
|
+
const { headerName = 'x-request-id', autoLog = true } = options;
|
|
102
|
+
return (req, _res, next) => {
|
|
103
|
+
// Generate or use existing request ID
|
|
104
|
+
const requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || crypto.randomUUID();
|
|
105
|
+
ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
106
|
+
// Create a child logger for this request
|
|
107
|
+
const childLogger = getLogger().child({
|
|
108
|
+
reqId: requestId,
|
|
109
|
+
method: req.method,
|
|
110
|
+
url: req.originalUrl || req.url
|
|
111
|
+
});
|
|
112
|
+
// Store logger in context
|
|
113
|
+
ContextStore.set(StoreKeys.LOGGER, childLogger);
|
|
114
|
+
if (autoLog) {
|
|
115
|
+
childLogger.info('Request context initialized');
|
|
116
|
+
}
|
|
117
|
+
next();
|
|
118
|
+
});
|
|
109
119
|
};
|
|
110
|
-
|
|
111
|
-
if (error === null || error === void 0 ? void 0 : error.code) {
|
|
112
|
-
response.code = error.code;
|
|
113
|
-
}
|
|
114
|
-
// Include stack trace in development mode if requested
|
|
115
|
-
if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
|
|
116
|
-
response.stack = error.stack.split('\n').map((line) => line.trim());
|
|
117
|
-
}
|
|
118
|
-
return response;
|
|
119
|
-
};
|
|
120
|
+
}
|
|
120
121
|
/**
|
|
121
122
|
* Global error handling middleware with enhanced features.
|
|
122
123
|
*
|
|
@@ -129,14 +130,12 @@ const createErrorResponse = (message, req, error, options) => {
|
|
|
129
130
|
export function errorHandler(options) {
|
|
130
131
|
const logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
|
|
131
132
|
const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
|
|
132
|
-
const logger = (options === null || options === void 0 ? void 0 : options.logger) || getLogger().error;
|
|
133
133
|
return (err, req, res, _next) => {
|
|
134
134
|
// Determine status code
|
|
135
135
|
const status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
136
136
|
// Log error if enabled
|
|
137
137
|
if (logErrors) {
|
|
138
|
-
|
|
139
|
-
logger(logMessage, err);
|
|
138
|
+
getLogger().error({ error: err }, `${err.message || 'Unknown error'}`);
|
|
140
139
|
}
|
|
141
140
|
// Handle ErrorResponse instances (our custom error class)
|
|
142
141
|
if (err instanceof ErrorResponse) {
|
|
@@ -148,6 +147,26 @@ export function errorHandler(options) {
|
|
|
148
147
|
path: req.originalUrl || req.url
|
|
149
148
|
});
|
|
150
149
|
}
|
|
150
|
+
const createErrorResponse = (message, req, error, options) => {
|
|
151
|
+
const isDev = Env.isDev();
|
|
152
|
+
const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
|
|
153
|
+
const response = {
|
|
154
|
+
error: true,
|
|
155
|
+
message,
|
|
156
|
+
timestamp: new Date().toISOString(),
|
|
157
|
+
requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || uuid(),
|
|
158
|
+
path: req.originalUrl || req.url
|
|
159
|
+
};
|
|
160
|
+
// Include error code if present
|
|
161
|
+
if (error === null || error === void 0 ? void 0 : error.code) {
|
|
162
|
+
response.code = error.code;
|
|
163
|
+
}
|
|
164
|
+
// Include stack trace in development mode if requested
|
|
165
|
+
if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
|
|
166
|
+
response.stack = error.stack.split('\n').map((line) => line.trim());
|
|
167
|
+
}
|
|
168
|
+
return response;
|
|
169
|
+
};
|
|
151
170
|
// Handle any other errors
|
|
152
171
|
return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', req, err, {
|
|
153
172
|
includeDetails
|
|
@@ -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,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;QAC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E,MAAM,MAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,UAAU,CAAA,IAAI,eAAe,CAAC,qBAAqB,CAAC;QAEvF,uBAAuB;QACvB,IAAI,SAAS,EAAE,CAAC;YACd,MAAM,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,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;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,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;AAE3C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAIhE;;;;;;;;GAQG;AACH,MAAM,UAAU,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,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;gBACnC,SAAS,EAAE,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,SAAS,KAAK,GAAW,CAAC,EAAE,IAAI,IAAI,EAAE;gBACxD,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,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 { randomUUID } from 'crypto';\nimport { Config } from '../config';\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ErrorResponse } from './response.utils';\nimport { Env } from './env.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: { headerName?: string; exposeHeader?: boolean }): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n (req as any).id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n if (addHeader) {\n // Wrap res.end to set header just before sending response\n const originalEnd = res.end;\n res.end = function (chunk?: any, encoding?: any, cb?: any) {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n return originalEnd.call(this, chunk, encoding, cb);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n const diff = process.hrtime(start);\n const duration = diff[0] * 1e3 + diff[1] * 1e-6;\n getLogger().info(`${req.method} ${req.url} - ${duration.toFixed(2)}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: 'Request timeout',\n status: 408,\n timestamp: new Date().toISOString()\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || crypto.randomUUID();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n reqId: requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n childLogger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: { logErrors?: boolean; includeDetails?: boolean }) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ error: err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n });\n }\n\n const createErrorResponse = (message: string, req: Request, error: any, options?: { includeDetails?: boolean }) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || (req as any).id || uuid(),\n path: req.originalUrl || req.url\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n };\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || 'Internal Server Error', req, err, {\n includeDetails\n })\n );\n };\n}\n"]}
|
package/build/src/config.d.ts
CHANGED
package/build/src/config.js
CHANGED
|
@@ -14,11 +14,7 @@ exports.Config = {
|
|
|
14
14
|
/**
|
|
15
15
|
* Name of the logger instance (defaults to npm package name).
|
|
16
16
|
*/
|
|
17
|
-
name: env_utils_1.Env.get('LOGGER_NAME', env_utils_1.Env.get('npm_package_name', '@catbee/utils'))
|
|
18
|
-
/**
|
|
19
|
-
* Whether to use ISO 8601 timestamps in logs.
|
|
20
|
-
*/
|
|
21
|
-
isoTimestamp: env_utils_1.Env.getBoolean('LOGGER_ISO_TIMESTAMP', false)
|
|
17
|
+
name: env_utils_1.Env.get('LOGGER_NAME', env_utils_1.Env.get('npm_package_name', '@catbee/utils'))
|
|
22
18
|
},
|
|
23
19
|
Http: {
|
|
24
20
|
/**
|
package/build/src/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";;;AAAA,iDAAwC;AAIxC;;GAEG;AACU,QAAA,MAAM,GAAG;IACpB,MAAM,EAAE;QACN;;WAEG;QACH,KAAK,EAAE,eAAG,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAa;QAElD;;WAEG;QACH,IAAI,EAAE,eAAG,CAAC,GAAG,CAAC,aAAa,EAAE,eAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,eAAe,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";;;AAAA,iDAAwC;AAIxC;;GAEG;AACU,QAAA,MAAM,GAAG;IACpB,MAAM,EAAE;QACN;;WAEG;QACH,KAAK,EAAE,eAAG,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAa;QAElD;;WAEG;QACH,IAAI,EAAE,eAAG,CAAC,GAAG,CAAC,aAAa,EAAE,eAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,eAAe,CAAC,CAAC;KAC3E;IAED,IAAI,EAAE;QACJ;;WAEG;QACH,OAAO,EAAE,eAAG,CAAC,SAAS,CAAC,cAAc,EAAE,KAAK,CAAC;KAC9C;IAED,KAAK,EAAE;QACL;;WAEG;QACH,UAAU,EAAE,eAAG,CAAC,SAAS,CAAC,mBAAmB,EAAE,GAAG,CAAC;KACpD;CACF,CAAC","sourcesContent":["import { Env } from './utils/env.utils';\n\ntype LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent';\n\n/**\n * Application runtime configuration loaded from environment variables.\n */\nexport const 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 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', 300)\n }\n};\n"]}
|