@catbee/utils 0.0.2 → 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.
Files changed (170) hide show
  1. package/README.md +1 -4
  2. package/build/esm/config.d.ts +1 -5
  3. package/build/esm/config.js +6 -10
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/index.d.ts +20 -19
  6. package/build/esm/index.js +20 -19
  7. package/build/esm/index.js.map +1 -1
  8. package/build/esm/types/api-response.d.ts +2 -2
  9. package/build/esm/types/api-response.js.map +1 -1
  10. package/build/esm/utils/array.utils.d.ts +1 -1
  11. package/build/esm/utils/array.utils.js +17 -27
  12. package/build/esm/utils/array.utils.js.map +1 -1
  13. package/build/esm/utils/async.utils.d.ts +1 -5
  14. package/build/esm/utils/async.utils.js +17 -20
  15. package/build/esm/utils/async.utils.js.map +1 -1
  16. package/build/esm/utils/cache.utils.js +2 -2
  17. package/build/esm/utils/cache.utils.js.map +1 -1
  18. package/build/esm/utils/context-store.utils.d.ts +1 -1
  19. package/build/esm/utils/context-store.utils.js +8 -8
  20. package/build/esm/utils/context-store.utils.js.map +1 -1
  21. package/build/esm/utils/crypto.utils.d.ts +2 -2
  22. package/build/esm/utils/crypto.utils.js +37 -45
  23. package/build/esm/utils/crypto.utils.js.map +1 -1
  24. package/build/esm/utils/decorators.utils.d.ts +2 -18
  25. package/build/esm/utils/decorators.utils.js +31 -31
  26. package/build/esm/utils/decorators.utils.js.map +1 -1
  27. package/build/esm/utils/dir.utils.d.ts +4 -4
  28. package/build/esm/utils/dir.utils.js +18 -20
  29. package/build/esm/utils/dir.utils.js.map +1 -1
  30. package/build/esm/utils/env.utils.js +22 -26
  31. package/build/esm/utils/env.utils.js.map +1 -1
  32. package/build/esm/utils/exception.utils.d.ts +1 -1
  33. package/build/esm/utils/exception.utils.js +26 -29
  34. package/build/esm/utils/exception.utils.js.map +1 -1
  35. package/build/esm/utils/fs.utils.d.ts +3 -3
  36. package/build/esm/utils/fs.utils.js +19 -23
  37. package/build/esm/utils/fs.utils.js.map +1 -1
  38. package/build/esm/utils/http-status-codes.js.map +1 -1
  39. package/build/esm/utils/id.utils.js +8 -8
  40. package/build/esm/utils/id.utils.js.map +1 -1
  41. package/build/esm/utils/logger.utils.d.ts +13 -4
  42. package/build/esm/utils/logger.utils.js +16 -18
  43. package/build/esm/utils/logger.utils.js.map +1 -1
  44. package/build/esm/utils/middleware.utils.d.ts +15 -26
  45. package/build/esm/utils/middleware.utils.js +80 -59
  46. package/build/esm/utils/middleware.utils.js.map +1 -1
  47. package/build/esm/utils/obj.utils.js +16 -27
  48. package/build/esm/utils/obj.utils.js.map +1 -1
  49. package/build/esm/utils/response.utils.d.ts +2 -2
  50. package/build/esm/utils/response.utils.js +11 -11
  51. package/build/esm/utils/response.utils.js.map +1 -1
  52. package/build/esm/utils/string.utils.js +17 -17
  53. package/build/esm/utils/string.utils.js.map +1 -1
  54. package/build/esm/utils/url.utils.js +20 -22
  55. package/build/esm/utils/url.utils.js.map +1 -1
  56. package/build/esm/utils/validate.utils.js +11 -15
  57. package/build/esm/utils/validate.utils.js.map +1 -1
  58. package/build/esnext/config.d.ts +1 -5
  59. package/build/esnext/config.js +6 -10
  60. package/build/esnext/config.js.map +1 -1
  61. package/build/esnext/index.d.ts +20 -19
  62. package/build/esnext/index.js +20 -19
  63. package/build/esnext/index.js.map +1 -1
  64. package/build/esnext/types/api-response.d.ts +2 -2
  65. package/build/esnext/types/api-response.js.map +1 -1
  66. package/build/esnext/utils/array.utils.d.ts +1 -1
  67. package/build/esnext/utils/array.utils.js +23 -31
  68. package/build/esnext/utils/array.utils.js.map +1 -1
  69. package/build/esnext/utils/async.utils.d.ts +1 -5
  70. package/build/esnext/utils/async.utils.js +22 -22
  71. package/build/esnext/utils/async.utils.js.map +1 -1
  72. package/build/esnext/utils/cache.utils.js +3 -3
  73. package/build/esnext/utils/cache.utils.js.map +1 -1
  74. package/build/esnext/utils/context-store.utils.d.ts +1 -1
  75. package/build/esnext/utils/context-store.utils.js +10 -10
  76. package/build/esnext/utils/context-store.utils.js.map +1 -1
  77. package/build/esnext/utils/crypto.utils.d.ts +2 -2
  78. package/build/esnext/utils/crypto.utils.js +37 -47
  79. package/build/esnext/utils/crypto.utils.js.map +1 -1
  80. package/build/esnext/utils/decorators.utils.d.ts +2 -18
  81. package/build/esnext/utils/decorators.utils.js +33 -33
  82. package/build/esnext/utils/decorators.utils.js.map +1 -1
  83. package/build/esnext/utils/dir.utils.d.ts +4 -4
  84. package/build/esnext/utils/dir.utils.js +22 -24
  85. package/build/esnext/utils/dir.utils.js.map +1 -1
  86. package/build/esnext/utils/env.utils.js +24 -26
  87. package/build/esnext/utils/env.utils.js.map +1 -1
  88. package/build/esnext/utils/exception.utils.d.ts +1 -1
  89. package/build/esnext/utils/exception.utils.js +26 -29
  90. package/build/esnext/utils/exception.utils.js.map +1 -1
  91. package/build/esnext/utils/fs.utils.d.ts +3 -3
  92. package/build/esnext/utils/fs.utils.js +21 -25
  93. package/build/esnext/utils/fs.utils.js.map +1 -1
  94. package/build/esnext/utils/http-status-codes.js.map +1 -1
  95. package/build/esnext/utils/id.utils.js +8 -8
  96. package/build/esnext/utils/id.utils.js.map +1 -1
  97. package/build/esnext/utils/logger.utils.d.ts +13 -4
  98. package/build/esnext/utils/logger.utils.js +16 -18
  99. package/build/esnext/utils/logger.utils.js.map +1 -1
  100. package/build/esnext/utils/middleware.utils.d.ts +15 -26
  101. package/build/esnext/utils/middleware.utils.js +78 -59
  102. package/build/esnext/utils/middleware.utils.js.map +1 -1
  103. package/build/esnext/utils/obj.utils.js +17 -26
  104. package/build/esnext/utils/obj.utils.js.map +1 -1
  105. package/build/esnext/utils/response.utils.d.ts +2 -2
  106. package/build/esnext/utils/response.utils.js +11 -11
  107. package/build/esnext/utils/response.utils.js.map +1 -1
  108. package/build/esnext/utils/string.utils.js +17 -17
  109. package/build/esnext/utils/string.utils.js.map +1 -1
  110. package/build/esnext/utils/url.utils.js +21 -23
  111. package/build/esnext/utils/url.utils.js.map +1 -1
  112. package/build/esnext/utils/validate.utils.js +14 -16
  113. package/build/esnext/utils/validate.utils.js.map +1 -1
  114. package/build/src/config.d.ts +1 -5
  115. package/build/src/config.js +5 -9
  116. package/build/src/config.js.map +1 -1
  117. package/build/src/index.d.ts +20 -19
  118. package/build/src/index.js +1 -0
  119. package/build/src/index.js.map +1 -1
  120. package/build/src/types/api-response.d.ts +2 -2
  121. package/build/src/types/api-response.js.map +1 -1
  122. package/build/src/utils/array.utils.d.ts +1 -1
  123. package/build/src/utils/array.utils.js +22 -30
  124. package/build/src/utils/array.utils.js.map +1 -1
  125. package/build/src/utils/async.utils.d.ts +1 -5
  126. package/build/src/utils/async.utils.js +22 -22
  127. package/build/src/utils/async.utils.js.map +1 -1
  128. package/build/src/utils/cache.utils.js +2 -2
  129. package/build/src/utils/cache.utils.js.map +1 -1
  130. package/build/src/utils/context-store.utils.d.ts +1 -1
  131. package/build/src/utils/context-store.utils.js +9 -9
  132. package/build/src/utils/context-store.utils.js.map +1 -1
  133. package/build/src/utils/crypto.utils.d.ts +2 -2
  134. package/build/src/utils/crypto.utils.js +35 -45
  135. package/build/src/utils/crypto.utils.js.map +1 -1
  136. package/build/src/utils/decorators.utils.d.ts +2 -18
  137. package/build/src/utils/decorators.utils.js +32 -32
  138. package/build/src/utils/decorators.utils.js.map +1 -1
  139. package/build/src/utils/dir.utils.d.ts +4 -4
  140. package/build/src/utils/dir.utils.js +16 -18
  141. package/build/src/utils/dir.utils.js.map +1 -1
  142. package/build/src/utils/env.utils.js +22 -24
  143. package/build/src/utils/env.utils.js.map +1 -1
  144. package/build/src/utils/exception.utils.d.ts +1 -1
  145. package/build/src/utils/exception.utils.js +23 -26
  146. package/build/src/utils/exception.utils.js.map +1 -1
  147. package/build/src/utils/fs.utils.d.ts +3 -3
  148. package/build/src/utils/fs.utils.js +15 -19
  149. package/build/src/utils/fs.utils.js.map +1 -1
  150. package/build/src/utils/http-status-codes.js.map +1 -1
  151. package/build/src/utils/id.utils.js +7 -7
  152. package/build/src/utils/id.utils.js.map +1 -1
  153. package/build/src/utils/logger.utils.d.ts +13 -4
  154. package/build/src/utils/logger.utils.js +13 -15
  155. package/build/src/utils/logger.utils.js.map +1 -1
  156. package/build/src/utils/middleware.utils.d.ts +15 -26
  157. package/build/src/utils/middleware.utils.js +72 -52
  158. package/build/src/utils/middleware.utils.js.map +1 -1
  159. package/build/src/utils/obj.utils.js +17 -26
  160. package/build/src/utils/obj.utils.js.map +1 -1
  161. package/build/src/utils/response.utils.d.ts +2 -2
  162. package/build/src/utils/response.utils.js +9 -9
  163. package/build/src/utils/response.utils.js.map +1 -1
  164. package/build/src/utils/string.utils.js +17 -17
  165. package/build/src/utils/string.utils.js.map +1 -1
  166. package/build/src/utils/url.utils.js +20 -22
  167. package/build/src/utils/url.utils.js.map +1 -1
  168. package/build/src/utils/validate.utils.js +14 -16
  169. package/build/src/utils/validate.utils.js.map +1 -1
  170. package/package.json +3 -3
@@ -1,26 +1,4 @@
1
- /**
2
- * Type definitions for Express-compatible middleware
3
- */
4
- export 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
- export 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
- export type NextFunction = (err?: Error | any) => void;
1
+ import type { Request, Response, NextFunction } from 'express';
24
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.
@@ -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
- }): Middleware;
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,6 +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
- logger?: (message: string, error: any) => void;
71
- }): (err: any, req: Request, res: Response, _next: NextFunction) => void;
60
+ }): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
72
61
  //# sourceMappingURL=middleware.utils.d.ts.map
@@ -1,10 +1,11 @@
1
- import { randomUUID } from "crypto";
2
- import { Config } from "../config";
3
- import { uuid } from "./id.utils";
4
- import { HttpStatusCodes } from "./http-status-codes";
5
- import { ErrorResponse } from "./response.utils";
6
- import { Env } from "./env.utils";
7
- import { getLogger } from "./logger.utils";
1
+ import { randomUUID } from 'crypto';
2
+ import { Config } from '../config';
3
+ import { uuid } from './id.utils';
4
+ import { HttpStatusCodes } from './http-status-codes';
5
+ import { ErrorResponse } from './response.utils';
6
+ import { Env } from './env.utils';
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.
@@ -15,7 +16,7 @@ import { getLogger } from "./logger.utils";
15
16
  * @returns {Middleware} Express-compatible middleware
16
17
  */
17
18
  export function requestId(options) {
18
- const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || "X-Request-ID";
19
+ const headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
19
20
  const exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
20
21
  return (req, res, next) => {
21
22
  // Use existing request ID from header or generate a new one
@@ -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
- // Function to calculate elapsed time
47
- const calculateDuration = () => {
48
- const diff = process.hrtime(start);
49
- return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms
50
- };
51
- // Handle response completion
52
- res.on("finish", () => {
53
- const duration = calculateDuration();
54
- if (addHeader) {
55
- res.setHeader("X-Response-Time", `${duration.toFixed(2)}ms`);
56
- }
57
- if (logOnComplete) {
58
- const { method, url } = req;
59
- getLogger().info(`${method} ${url} - ${duration.toFixed(2)}ms`);
60
- }
61
- });
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;
53
+ res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);
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
  }
@@ -75,48 +77,47 @@ export function timeout(timeoutMs = Config.Http.timeout) {
75
77
  const timer = setTimeout(() => {
76
78
  res.status(408).json({
77
79
  error: true,
78
- message: "Request timeout",
80
+ message: 'Request timeout',
79
81
  status: 408,
80
- timestamp: new Date().toISOString(),
82
+ timestamp: new Date().toISOString()
81
83
  });
82
84
  }, timeoutMs);
83
85
  // Clear timeout when response is sent
84
- res.on("finish", () => {
86
+ res.on('finish', () => {
85
87
  clearTimeout(timer);
86
88
  });
87
89
  next();
88
90
  };
89
91
  }
90
92
  /**
91
- * Creates a standardized error response object for API errors.
93
+ * Creates an Express middleware that initializes a per-request context.
92
94
  *
93
- * @param {string} message - Error message
94
- * @param {Request} req - Express request object
95
- * @param {any} error - Original error object
96
- * @param {object} [options] - Additional options
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
- const createErrorResponse = (message, req, error, options) => {
101
- const isDev = Env.isDev();
102
- const includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
103
- const response = {
104
- error: true,
105
- message,
106
- timestamp: new Date().toISOString(),
107
- requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || uuid(),
108
- path: req.originalUrl || req.url,
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
- // Include error code if present
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
- const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || "Unknown error"}`;
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) {
@@ -145,12 +144,32 @@ export function errorHandler(options) {
145
144
  message: err.message,
146
145
  timestamp: err.timestamp,
147
146
  requestId: err.requestId || req.id || uuid(),
148
- path: req.originalUrl || req.url,
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
- return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || "Internal Server Error", req, err, {
153
- includeDetails,
171
+ return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', req, err, {
172
+ includeDetails
154
173
  }));
155
174
  };
156
175
  }
@@ -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;AAkC3C;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,OAGzB;IACC,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,C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BAAH,GAAG,CAAE,UAAU,CAAA,IAAI,eAAe,CAAC,qBAAqB,CAAC;QAE1E,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 */\nexport type 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\nexport type 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\nexport type NextFunction = (err?: Error | any) => void;\n\nexport type Middleware = (\n req: Request,\n res: Response,\n next: NextFunction,\n) => 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?: {\n headerName?: string;\n exposeHeader?: boolean;\n}): 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?: {\n addHeader?: boolean;\n logOnComplete?: boolean;\n}): 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 = (\n message: string,\n req: Request,\n error: any,\n options?: { includeDetails?: boolean },\n) => {\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 =\n 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,C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gBACP,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;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"]}
@@ -5,7 +5,7 @@
5
5
  * @returns {boolean} True if the object is empty, false otherwise.
6
6
  */
7
7
  export function isObjEmpty(obj) {
8
- return !!obj && typeof obj === "object" && Object.keys(obj).length === 0;
8
+ return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;
9
9
  }
10
10
  /**
11
11
  * Returns a new object with only the specified keys picked.
@@ -17,7 +17,7 @@ export function isObjEmpty(obj) {
17
17
  * @returns {Pick<T, K>} New object with picked keys.
18
18
  */
19
19
  export function pick(obj, keys) {
20
- return Object.fromEntries(keys.map((key) => [key, obj[key]]));
20
+ return Object.fromEntries(keys.map(key => [key, obj[key]]));
21
21
  }
22
22
  /**
23
23
  * Returns a new object with the specified keys omitted.
@@ -43,12 +43,8 @@ export function deepObjMerge(target, source) {
43
43
  for (const key in source) {
44
44
  const sourceVal = source[key];
45
45
  const targetVal = target[key];
46
- if (sourceVal &&
47
- typeof sourceVal === "object" &&
48
- !Array.isArray(sourceVal)) {
49
- if (!targetVal ||
50
- typeof targetVal !== "object" ||
51
- Array.isArray(targetVal)) {
46
+ if (sourceVal && typeof sourceVal === 'object' && !Array.isArray(sourceVal)) {
47
+ if (!targetVal || typeof targetVal !== 'object' || Array.isArray(targetVal)) {
52
48
  target[key] = {};
53
49
  }
54
50
  deepObjMerge(target[key], sourceVal);
@@ -67,10 +63,10 @@ export function deepObjMerge(target, source) {
67
63
  * @param {string} [prefix=""] - Optional prefix for nested keys (used internally).
68
64
  * @returns {Record<string, any>} A new object with flattened keys.
69
65
  */
70
- export function flattenObject(obj, prefix = "") {
66
+ export function flattenObject(obj, prefix = '') {
71
67
  return Object.entries(obj).reduce((acc, [key, value]) => {
72
68
  const newKey = prefix ? `${prefix}.${key}` : key;
73
- if (value && typeof value === "object" && !Array.isArray(value)) {
69
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
74
70
  Object.assign(acc, flattenObject(value, newKey));
75
71
  }
76
72
  else {
@@ -88,12 +84,12 @@ export function flattenObject(obj, prefix = "") {
88
84
  * @returns {any} The value at the given path, or undefined if not found.
89
85
  */
90
86
  export function getValueByPath(obj, path) {
91
- if (!obj || typeof obj !== "object")
87
+ if (!obj || typeof obj !== 'object')
92
88
  return undefined;
93
89
  // Convert path like "a.b[0].c" into ["a", "b", "0", "c"]
94
90
  const parts = path
95
- .replace(/\[(\d+)\]/g, ".$1") // convert [0] to .0
96
- .split(".")
91
+ .replace(/\[(\d+)\]/g, '.$1') // convert [0] to .0
92
+ .split('.')
97
93
  .filter(Boolean); // remove empty strings
98
94
  return parts.reduce((acc, key) => acc === null || acc === void 0 ? void 0 : acc[key], obj);
99
95
  }
@@ -108,12 +104,12 @@ export function getValueByPath(obj, path) {
108
104
  * @returns {T} The modified object.
109
105
  */
110
106
  export function setValueByPath(obj, path, value) {
111
- if (!obj || typeof obj !== "object")
107
+ if (!obj || typeof obj !== 'object')
112
108
  return obj;
113
109
  // Convert path like "a.b[0].c" into ["a", "b", "0", "c"]
114
110
  const parts = path
115
- .replace(/\[(\d+)\]/g, ".$1") // convert [0] to .0
116
- .split(".")
111
+ .replace(/\[(\d+)\]/g, '.$1') // convert [0] to .0
112
+ .split('.')
117
113
  .filter(Boolean); // remove empty strings
118
114
  // Handle empty path
119
115
  if (parts.length === 0)
@@ -146,10 +142,7 @@ export function isEqual(a, b) {
146
142
  if (a === b)
147
143
  return true;
148
144
  // Check if either is null/undefined or not an object
149
- if (a == null ||
150
- b == null ||
151
- typeof a !== "object" ||
152
- typeof b !== "object") {
145
+ if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {
153
146
  return false;
154
147
  }
155
148
  // Handle Date objects
@@ -181,7 +174,7 @@ export function isEqual(a, b) {
181
174
  if (keysA.length !== keysB.length)
182
175
  return false;
183
176
  // Check if every key in A exists in B and has the same value
184
- return keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));
177
+ return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));
185
178
  }
186
179
  /**
187
180
  * Filters object properties based on a predicate function.
@@ -220,9 +213,7 @@ export function deepFreeze(obj) {
220
213
  // Recursively freeze nested objects
221
214
  for (const prop of Object.getOwnPropertyNames(obj)) {
222
215
  const value = obj[prop];
223
- if (value !== null &&
224
- typeof value === "object" &&
225
- !Object.isFrozen(value)) {
216
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
226
217
  deepFreeze(value);
227
218
  }
228
219
  }
@@ -235,7 +226,7 @@ export function deepFreeze(obj) {
235
226
  * @returns {boolean} True if value is a non-null, non-array object.
236
227
  */
237
228
  export function isObject(value) {
238
- return value !== null && typeof value === "object" && !Array.isArray(value);
229
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
239
230
  }
240
231
  /**
241
232
  * Gets all paths in an object using dot notation.
@@ -244,7 +235,7 @@ export function isObject(value) {
244
235
  * @param {string} [parentPath=""] - Internal param for recursion.
245
236
  * @returns {string[]} Array of all paths in dot notation.
246
237
  */
247
- export function getAllPaths(obj, parentPath = "") {
238
+ export function getAllPaths(obj, parentPath = '') {
248
239
  if (!isObject(obj))
249
240
  return [];
250
241
  return Object.entries(obj).flatMap(([key, value]) => {
@@ -1 +1 @@
1
- {"version":3,"file":"obj.utils.js","sourceRoot":"","sources":["../../../src/utils/obj.utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,UAAU,UAAU,CAAC,GAAqB;IAC9C,OAAO,CAAC,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;AAC3E,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAClB,GAAM,EACN,IAAS;IAET,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAe,CAAC;AAC9E,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAClB,GAAM,EACN,IAAS;IAET,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAQ,CAAC,CAAC,CAClD,CAAC;AAClB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAS,EACT,MAAkB;IAElB,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;QACzB,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC9B,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAE9B,IACE,SAAS;YACT,OAAO,SAAS,KAAK,QAAQ;YAC7B,CAAC,KAAK,CAAC,OAAO,CAAC,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AAW,CAAC,CAAC,CAAC;QAC3D,CAAC;QAED,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Checks whether the object has no own enumerable properties.\n *\n * @param {Record<any, any>} obj - The object to check.\n * @returns {boolean} True if the object is empty, false otherwise.\n */\nexport function isObjEmpty(obj: Record<any, any>): boolean {\n return !!obj && typeof obj === \"object\" && Object.keys(obj).length === 0;\n}\n\n/**\n * Returns a new object with only the specified keys picked.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to pick from the object.\n * @returns {Pick<T, K>} New object with picked keys.\n */\nexport function pick<T extends object, K extends keyof T>(\n obj: T,\n keys: K[],\n): Pick<T, K> {\n return Object.fromEntries(keys.map((key) => [key, obj[key]])) as Pick<T, K>;\n}\n\n/**\n * Returns a new object with the specified keys omitted.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to omit from the object.\n * @returns {Omit<T, K>} New object without omitted keys.\n */\nexport function omit<T extends object, K extends keyof T>(\n obj: T,\n keys: K[],\n): Omit<T, K> {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key as K)),\n ) as Omit<T, K>;\n}\n\n/**\n * Deeply merges two objects (mutates and returns the target object, not pure).\n *\n * @template T\n * @param {T} target - The object to merge into (will be mutated).\n * @param {Partial<T>} source - The object to merge from.\n * @returns {T} The merged object (same as target).\n */\nexport function deepObjMerge<T extends Record<string, any>>(\n target: T,\n source: Partial<T>,\n): T {\n for (const key in source) {\n const sourceVal = source[key];\n const targetVal = target[key];\n\n if (\n sourceVal &&\n typeof sourceVal === \"object\" &&\n !Array.isArray(sourceVal)\n ) {\n if (\n !targetVal ||\n typeof targetVal !== \"object\" ||\n Array.isArray(targetVal)\n ) {\n target[key] = {} as any;\n }\n deepObjMerge(target[key], sourceVal as any);\n } else {\n target[key] = sourceVal as T[Extract<keyof T, string>];\n }\n }\n return target;\n}\n\n/**\n * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ \"a.b\": 1 }`).\n *\n * @template T\n * @param {T} obj - The object to flatten.\n * @param {string} [prefix=\"\"] - Optional prefix for nested keys (used internally).\n * @returns {Record<string, any>} A new object with flattened keys.\n */\nexport function flattenObject<T extends Record<string, any>>(\n obj: T,\n prefix = \"\",\n): Record<string, any> {\n return Object.entries(obj).reduce(\n (acc: Record<string, any>, [key, value]) => {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n Object.assign(acc, flattenObject(value, newKey));\n } else {\n acc[newKey] = value;\n }\n\n return acc;\n },\n {},\n );\n}\n\n/**\n * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.\n *\n * @template T\n * @param {T} obj - The object to extract from.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @returns {any} The value at the given path, or undefined if not found.\n */\nexport function getValueByPath<T extends object>(obj: T, path: string) {\n if (!obj || typeof obj !== \"object\") return undefined;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, \".$1\") // convert [0] to .0\n .split(\".\")\n .filter(Boolean); // remove empty strings\n\n return parts.reduce((acc: any, key: string) => acc?.[key], obj);\n}\n\n/**\n * Sets a value at a deeply nested key in an object using dot/bracket notation path.\n * Creates intermediate objects and arrays as needed.\n *\n * @template T\n * @param {T} obj - The object to modify.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @param {any} value - The value to set at the path.\n * @returns {T} The modified object.\n */\nexport function setValueByPath<T extends object>(\n obj: T,\n path: string,\n value: any,\n): T {\n if (!obj || typeof obj !== \"object\") return obj;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, \".$1\") // convert [0] to .0\n .split(\".\")\n .filter(Boolean); // remove empty strings\n\n // Handle empty path\n if (parts.length === 0) return obj;\n\n let current: any = obj;\n\n // Navigate to the parent of the target property\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n const isArrayIndex = !isNaN(Number(parts[i + 1]));\n\n if (current[key] === undefined) {\n // Create intermediate object or array based on next key type\n current[key] = isArrayIndex ? [] : {};\n }\n\n current = current[key];\n }\n\n // Set the value at the final key\n const finalKey = parts[parts.length - 1];\n current[finalKey] = value;\n\n return obj;\n}\n\n/**\n * Performs a deep equality check between two objects.\n *\n * @param {any} a - First value to compare.\n * @param {any} b - Second value to compare.\n * @returns {boolean} True if values are deeply equal.\n */\nexport function isEqual(a: any, b: any): boolean {\n // Check if primitives or references to the same object\n if (a === b) return true;\n\n // Check if either is null/undefined or not an object\n if (\n a == null ||\n b == null ||\n typeof a !== \"object\" ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // If one is Date but the other isn't\n if (a instanceof Date || b instanceof Date) {\n return false;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n\n // Check each element\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n\n // If one is Array but the other isn't\n if (Array.isArray(a) || Array.isArray(b)) {\n return false;\n }\n\n // Compare object keys\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n // Check if every key in A exists in B and has the same value\n return keysA.every(\n (key) =>\n Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]),\n );\n}\n\n/**\n * Filters object properties based on a predicate function.\n *\n * @template T\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.\n * @returns {Partial<T>} New object with filtered properties.\n */\nexport function filterObject<T extends object>(\n obj: T,\n predicate: (value: any, key: string, obj: T) => boolean,\n): Partial<T> {\n return Object.fromEntries(\n Object.entries(obj).filter(([key, value]) => predicate(value, key, obj)),\n ) as Partial<T>;\n}\n\n/**\n * Maps object values to new values using a mapping function.\n *\n * @template T\n * @template U\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.\n * @returns {Record<keyof T, U>} New object with mapped values.\n */\nexport function mapObject<T extends object, U>(\n obj: T,\n mapFn: (value: any, key: string, obj: T) => U,\n): Record<keyof T, U> {\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)]),\n ) as Record<keyof T, U>;\n}\n\n/**\n * Recursively freezes an object and all its properties.\n * Makes an object immutable.\n *\n * @template T\n * @param {T} obj - The object to freeze.\n * @returns {Readonly<T>} The frozen object.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze primitive properties\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n for (const prop of Object.getOwnPropertyNames(obj)) {\n const value = (obj as any)[prop];\n if (\n value !== null &&\n typeof value === \"object\" &&\n !Object.isFrozen(value)\n ) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Safely checks if a value is an object (not null, not array).\n *\n * @param {unknown} value - Value to check.\n * @returns {boolean} True if value is a non-null, non-array object.\n */\nexport function isObject(value: unknown): value is Record<string, any> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Gets all paths in an object using dot notation.\n *\n * @param {Record<string, any>} obj - Object to analyze.\n * @param {string} [parentPath=\"\"] - Internal param for recursion.\n * @returns {string[]} Array of all paths in dot notation.\n */\nexport function getAllPaths(\n obj: Record<string, any>,\n parentPath: string = \"\",\n): string[] {\n if (!isObject(obj)) return [];\n\n return Object.entries(obj).flatMap(([key, value]) => {\n const currentPath = parentPath ? `${parentPath}.${key}` : key;\n\n if (isObject(value)) {\n return [currentPath, ...getAllPaths(value, currentPath)];\n }\n\n return [currentPath];\n });\n}\n"]}
1
+ {"version":3,"file":"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ties.\n *\n * @param {Record<any, any>} obj - The object to check.\n * @returns {boolean} True if the object is empty, false otherwise.\n */\nexport function isObjEmpty(obj: Record<any, any>): boolean {\n return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;\n}\n\n/**\n * Returns a new object with only the specified keys picked.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to pick from the object.\n * @returns {Pick<T, K>} New object with picked keys.\n */\nexport function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(keys.map(key => [key, obj[key]])) as Pick<T, K>;\n}\n\n/**\n * Returns a new object with the specified keys omitted.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to omit from the object.\n * @returns {Omit<T, K>} New object without omitted keys.\n */\nexport function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key as K))) as Omit<T, K>;\n}\n\n/**\n * Deeply merges two objects (mutates and returns the target object, not pure).\n *\n * @template T\n * @param {T} target - The object to merge into (will be mutated).\n * @param {Partial<T>} source - The object to merge from.\n * @returns {T} The merged object (same as target).\n */\nexport function deepObjMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T {\n for (const key in source) {\n const sourceVal = source[key];\n const targetVal = target[key];\n\n if (sourceVal && typeof sourceVal === 'object' && !Array.isArray(sourceVal)) {\n if (!targetVal || typeof targetVal !== 'object' || Array.isArray(targetVal)) {\n target[key] = {} as any;\n }\n deepObjMerge(target[key], sourceVal as any);\n } else {\n target[key] = sourceVal as T[Extract<keyof T, string>];\n }\n }\n return target;\n}\n\n/**\n * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ \"a.b\": 1 }`).\n *\n * @template T\n * @param {T} obj - The object to flatten.\n * @param {string} [prefix=\"\"] - Optional prefix for nested keys (used internally).\n * @returns {Record<string, any>} A new object with flattened keys.\n */\nexport function flattenObject<T extends Record<string, any>>(obj: T, prefix = ''): Record<string, any> {\n return Object.entries(obj).reduce((acc: Record<string, any>, [key, value]) => {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(acc, flattenObject(value, newKey));\n } else {\n acc[newKey] = value;\n }\n\n return acc;\n }, {});\n}\n\n/**\n * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.\n *\n * @template T\n * @param {T} obj - The object to extract from.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @returns {any} The value at the given path, or undefined if not found.\n */\nexport function getValueByPath<T extends object>(obj: T, path: string) {\n if (!obj || typeof obj !== 'object') return undefined;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n return parts.reduce((acc: any, key: string) => acc?.[key], obj);\n}\n\n/**\n * Sets a value at a deeply nested key in an object using dot/bracket notation path.\n * Creates intermediate objects and arrays as needed.\n *\n * @template T\n * @param {T} obj - The object to modify.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @param {any} value - The value to set at the path.\n * @returns {T} The modified object.\n */\nexport function setValueByPath<T extends object>(obj: T, path: string, value: any): T {\n if (!obj || typeof obj !== 'object') return obj;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n // Handle empty path\n if (parts.length === 0) return obj;\n\n let current: any = obj;\n\n // Navigate to the parent of the target property\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n const isArrayIndex = !isNaN(Number(parts[i + 1]));\n\n if (current[key] === undefined) {\n // Create intermediate object or array based on next key type\n current[key] = isArrayIndex ? [] : {};\n }\n\n current = current[key];\n }\n\n // Set the value at the final key\n const finalKey = parts[parts.length - 1];\n current[finalKey] = value;\n\n return obj;\n}\n\n/**\n * Performs a deep equality check between two objects.\n *\n * @param {any} a - First value to compare.\n * @param {any} b - Second value to compare.\n * @returns {boolean} True if values are deeply equal.\n */\nexport function isEqual(a: any, b: any): boolean {\n // Check if primitives or references to the same object\n if (a === b) return true;\n\n // Check if either is null/undefined or not an object\n if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // If one is Date but the other isn't\n if (a instanceof Date || b instanceof Date) {\n return false;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n\n // Check each element\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n\n // If one is Array but the other isn't\n if (Array.isArray(a) || Array.isArray(b)) {\n return false;\n }\n\n // Compare object keys\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n // Check if every key in A exists in B and has the same value\n return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));\n}\n\n/**\n * Filters object properties based on a predicate function.\n *\n * @template T\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.\n * @returns {Partial<T>} New object with filtered properties.\n */\nexport function filterObject<T extends object>(\n obj: T,\n predicate: (value: any, key: string, obj: T) => boolean\n): Partial<T> {\n return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key, obj))) as Partial<T>;\n}\n\n/**\n * Maps object values to new values using a mapping function.\n *\n * @template T\n * @template U\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.\n * @returns {Record<keyof T, U>} New object with mapped values.\n */\nexport function mapObject<T extends object, U>(\n obj: T,\n mapFn: (value: any, key: string, obj: T) => U\n): Record<keyof T, U> {\n return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)])) as Record<\n keyof T,\n U\n >;\n}\n\n/**\n * Recursively freezes an object and all its properties.\n * Makes an object immutable.\n *\n * @template T\n * @param {T} obj - The object to freeze.\n * @returns {Readonly<T>} The frozen object.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze primitive properties\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n for (const prop of Object.getOwnPropertyNames(obj)) {\n const value = (obj as any)[prop];\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Safely checks if a value is an object (not null, not array).\n *\n * @param {unknown} value - Value to check.\n * @returns {boolean} True if value is a non-null, non-array object.\n */\nexport function isObject(value: unknown): value is Record<string, any> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Gets all paths in an object using dot notation.\n *\n * @param {Record<string, any>} obj - Object to analyze.\n * @param {string} [parentPath=\"\"] - Internal param for recursion.\n * @returns {string[]} Array of all paths in dot notation.\n */\nexport function getAllPaths(obj: Record<string, any>, parentPath: string = ''): string[] {\n if (!isObject(obj)) return [];\n\n return Object.entries(obj).flatMap(([key, value]) => {\n const currentPath = parentPath ? `${parentPath}.${key}` : key;\n\n if (isObject(value)) {\n return [currentPath, ...getAllPaths(value, currentPath)];\n }\n\n return [currentPath];\n });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ApiResponse } from "../types/api-response";
1
+ import { ApiResponse } from '../types/api-response';
2
2
  /**
3
3
  * Standard HTTP response wrapper for successful responses.
4
4
  * Implements the `ApiResponse<T>` interface and sets default values.
@@ -28,7 +28,7 @@ export declare class SuccessResponse<T> implements ApiResponse<T> {
28
28
  * Wrapper for error responses that extends the native `Error` object.
29
29
  * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).
30
30
  */
31
- export declare class ErrorResponse extends Error implements Omit<ApiResponse<never>, "data"> {
31
+ export declare class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {
32
32
  /** HTTP status code associated with the error (e.g., 404, 500). */
33
33
  status: number;
34
34
  /** Indicates that this is an error. Always true. */
@@ -1,5 +1,5 @@
1
- import { randomUUID } from "crypto";
2
- import { getRequestId } from "./context-store.utils";
1
+ import { randomUUID } from 'crypto';
2
+ import { getRequestId } from './context-store.utils';
3
3
  /**
4
4
  * Standard HTTP response wrapper for successful responses.
5
5
  * Implements the `ApiResponse<T>` interface and sets default values.
@@ -16,7 +16,7 @@ export class SuccessResponse {
16
16
  constructor(message, data) {
17
17
  var _a;
18
18
  /** Message describing the result of the operation. */
19
- this.message = "Success";
19
+ this.message = 'Success';
20
20
  /** Whether the response is an error. Always false in success responses. */
21
21
  this.error = false;
22
22
  /** The payload returned from the API. */
@@ -72,7 +72,7 @@ export class PaginatedResponse extends SuccessResponse {
72
72
  * @param {number} pagination.pageSize - Number of items per page.
73
73
  * @param {string} [message="Success"] - Optional custom message.
74
74
  */
75
- constructor(items, pagination, message = "Success") {
75
+ constructor(items, pagination, message = 'Success') {
76
76
  super(message, items);
77
77
  this.total = pagination.total;
78
78
  this.page = pagination.page;
@@ -91,7 +91,7 @@ export class NoContentResponse extends SuccessResponse {
91
91
  *
92
92
  * @param {string} [message="Operation completed successfully"] - Optional custom message.
93
93
  */
94
- constructor(message = "Operation completed successfully") {
94
+ constructor(message = 'Operation completed successfully') {
95
95
  super(message, null);
96
96
  }
97
97
  }
@@ -123,7 +123,7 @@ export class RedirectResponse {
123
123
  * @param {string} [message="Success"] - Optional custom message.
124
124
  * @returns {SuccessResponse<T>} A properly formatted success response.
125
125
  */
126
- export function createSuccessResponse(data, message = "Success") {
126
+ export function createSuccessResponse(data, message = 'Success') {
127
127
  return new SuccessResponse(message, data);
128
128
  }
129
129
  /**
@@ -146,7 +146,7 @@ export function createErrorResponse(message, statusCode = 500) {
146
146
  * @param {string} [message="Success"] - Optional custom message.
147
147
  * @returns {PaginatedResponse<T>} A properly formatted paginated response.
148
148
  */
149
- export function createPaginatedResponse(allItems, page, pageSize, message = "Success") {
149
+ export function createPaginatedResponse(allItems, page, pageSize, message = 'Success') {
150
150
  // Ensure valid pagination parameters
151
151
  const validPage = Math.max(1, page);
152
152
  const validPageSize = Math.max(1, pageSize);
@@ -158,7 +158,7 @@ export function createPaginatedResponse(allItems, page, pageSize, message = "Suc
158
158
  return new PaginatedResponse(pageItems, {
159
159
  total: allItems.length,
160
160
  page: validPage,
161
- pageSize: validPageSize,
161
+ pageSize: validPageSize
162
162
  }, message);
163
163
  }
164
164
  /**
@@ -169,18 +169,18 @@ export function createPaginatedResponse(allItems, page, pageSize, message = "Suc
169
169
  */
170
170
  export function sendResponse(res, apiResponse) {
171
171
  // Handle redirects
172
- if ("redirectUrl" in apiResponse) {
172
+ if ('redirectUrl' in apiResponse) {
173
173
  res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);
174
174
  return;
175
175
  }
176
176
  // Handle errors
177
- if ("error" in apiResponse && apiResponse.error) {
177
+ if ('error' in apiResponse && apiResponse.error) {
178
178
  const errorResponse = apiResponse;
179
179
  res.status(errorResponse.status).json({
180
180
  error: true,
181
181
  message: errorResponse.message,
182
182
  timestamp: errorResponse.timestamp,
183
- requestId: errorResponse.requestId,
183
+ requestId: errorResponse.requestId
184
184
  });
185
185
  return;
186
186
  }