devdad-express-utils 1.7.2 → 1.8.1

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 CHANGED
@@ -54,19 +54,19 @@ throw new AppError("Validation failed", 400, ["Email is required"]);
54
54
 
55
55
  ### Response Formatting
56
56
 
57
- Standardize API responses with consistent JSON structure and intelligent auto-sending.
57
+ Standardize API responses with consistent JSON structure and callback-based chaining.
58
58
 
59
59
  ```typescript
60
- import { sendSuccess, sendError, send } from "devdad-express-utils";
60
+ import { sendSuccess, sendError } from "devdad-express-utils";
61
61
 
62
- // Basic success response (auto-sends - no send() needed)
62
+ // Basic success response
63
63
  sendSuccess(res, { id: 1, name: "John" }, "User fetched", 200);
64
64
 
65
- // Chain native Express methods (use send() when done chaining)
66
- sendSuccess(res, { id: 1, name: "John" }, "User fetched", 200)
67
- .cookie("session", "abc123")
68
- .setHeader("X-Custom", "value");
69
- send(res); // Send when ready
65
+ // Chain methods using callbacks
66
+ sendSuccess(res, { id: 1, name: "John" }, "User fetched", 200, [
67
+ (res) => res.cookie("session", "abc123"),
68
+ (res) => res.setHeader("X-Custom", "value")
69
+ ]);
70
70
 
71
71
  // Error response (sends immediately)
72
72
  sendError(res, "User not found", 404);
@@ -257,18 +257,18 @@ errorHandler(err: any, req: Request, res: Response, next: NextFunction) => void
257
257
 
258
258
  ### sendSuccess
259
259
 
260
- Prepares a standardized success response and returns response object for chaining.
260
+ Sends a standardized success response with optional callbacks for chaining response methods.
261
261
 
262
262
  ```typescript
263
- sendSuccess(res: Response, data: any, message?: string, statusCode?: number) => Response
263
+ sendSuccess(res: Response, data: any, message?: string, statusCode?: number, callbacks?: Array<(res: Response) => Response>) => Response
264
264
  ```
265
265
 
266
266
  **Features:**
267
267
  - Includes `success: true` field by default
268
- - **Auto-sends** when no chaining detected (no `send()` needed)
269
- - Returns Express response object for native method chaining
270
- - Use `send()` when chaining methods (explicit control)
271
- - No magic - intelligent and predictable
268
+ - Supports chaining via callbacks array
269
+ - Executes callbacks before sending response
270
+ - No timing issues - predictable order
271
+ - Clean and explicit approach
272
272
 
273
273
  ### sendError
274
274
 
@@ -283,23 +283,7 @@ sendError(res: Response, message: string, statusCode?: number, data?: any) => vo
283
283
  - Sends response immediately (no chaining needed for errors)
284
284
  - Supports optional error data
285
285
 
286
- ### send
287
286
 
288
- Sends the prepared success response from `sendSuccess`. Only needed when chaining methods.
289
-
290
- ```typescript
291
- send(res: Response) => void
292
- ```
293
-
294
- **Features:**
295
- - Sends the response prepared by `sendSuccess`
296
- - **Only needed when chaining** (.cookie(), .header(), etc.)
297
- - Basic usage: sendSuccess() auto-sends, no send() needed
298
- - Explicit control over when response is sent
299
-
300
- **When to Use:**
301
- - ❌ Basic: `sendSuccess(res, data)` → NO send() needed
302
- - ✅ Chaining: `sendSuccess(res, data).cookie(...)` → send() needed
303
287
 
304
288
  ### connectDB
305
289
 
@@ -46,8 +46,31 @@ declare class DatabaseConnection {
46
46
  */
47
47
  resetAndRetry(): Promise<void>;
48
48
  }
49
+ /**
50
+ * Default export function to connect to MongoDB.
51
+ * Establishes a connection with automatic retry logic and reconnection handling.
52
+ *
53
+ * @example
54
+ * import connectDB from './DatabaseConnection';
55
+ * await connectDB(); // Connects using MONGO_URI from environment
56
+ */
49
57
  declare const _default: () => Promise<void>;
50
58
  export default _default;
59
+ /**
60
+ * Gets the current database connection status.
61
+ *
62
+ * @returns {Object} Connection status information including:
63
+ * - isConnected: boolean - whether the database is connected
64
+ * - readyState: number - mongoose connection ready state
65
+ * - host: string - database host
66
+ * - name: string - database name
67
+ * - retryCount: number - current retry attempt count
68
+ *
69
+ * @example
70
+ * import { getDBStatus } from './DatabaseConnection';
71
+ * const status = getDBStatus();
72
+ * console.log('DB connected:', status.isConnected);
73
+ */
51
74
  export declare const getDBStatus: () => {
52
75
  isConnected: boolean;
53
76
  readyState: number;
@@ -55,5 +78,13 @@ export declare const getDBStatus: () => {
55
78
  name: string;
56
79
  retryCount: number;
57
80
  };
81
+ /**
82
+ * Resets the connection state and attempts to reconnect.
83
+ * Useful for recovering from Docker container restarts or network issues.
84
+ *
85
+ * @example
86
+ * import { resetDBConnection } from './DatabaseConnection';
87
+ * await resetDBConnection(); // Reset retry count and reconnect
88
+ */
58
89
  export declare const resetDBConnection: () => Promise<void>;
59
90
  export { DatabaseConnection };
@@ -149,8 +149,38 @@ class DatabaseConnection {
149
149
  }
150
150
  // Create a singleton instance
151
151
  const dbConnection = new DatabaseConnection();
152
- // Export the connect function and the instance
152
+ /**
153
+ * Default export function to connect to MongoDB.
154
+ * Establishes a connection with automatic retry logic and reconnection handling.
155
+ *
156
+ * @example
157
+ * import connectDB from './DatabaseConnection';
158
+ * await connectDB(); // Connects using MONGO_URI from environment
159
+ */
153
160
  export default dbConnection.connect.bind(dbConnection);
161
+ /**
162
+ * Gets the current database connection status.
163
+ *
164
+ * @returns {Object} Connection status information including:
165
+ * - isConnected: boolean - whether the database is connected
166
+ * - readyState: number - mongoose connection ready state
167
+ * - host: string - database host
168
+ * - name: string - database name
169
+ * - retryCount: number - current retry attempt count
170
+ *
171
+ * @example
172
+ * import { getDBStatus } from './DatabaseConnection';
173
+ * const status = getDBStatus();
174
+ * console.log('DB connected:', status.isConnected);
175
+ */
154
176
  export const getDBStatus = dbConnection.getConnectionStatus.bind(dbConnection);
177
+ /**
178
+ * Resets the connection state and attempts to reconnect.
179
+ * Useful for recovering from Docker container restarts or network issues.
180
+ *
181
+ * @example
182
+ * import { resetDBConnection } from './DatabaseConnection';
183
+ * await resetDBConnection(); // Reset retry count and reconnect
184
+ */
155
185
  export const resetDBConnection = dbConnection.resetAndRetry.bind(dbConnection);
156
186
  export { DatabaseConnection };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,34 @@
1
+ /**
2
+ * Express Utils - A comprehensive utility library for Express.js applications
3
+ *
4
+ * This library provides essential utilities for building robust Express applications:
5
+ * - Error handling with custom AppError class and global error handler
6
+ * - Async error catching middleware
7
+ * - Response formatting with callback-based chaining
8
+ * - Database connection management with retry logic
9
+ * - Structured logging with Winston
10
+ */
11
+ /**
12
+ * Custom error class for application errors with status codes and operational flags
13
+ */
1
14
  export { AppError } from "./AppError.js";
15
+ /**
16
+ * Higher-order function to catch asynchronous errors in Express route handlers
17
+ */
2
18
  export { catchAsync } from "./catchAsync.js";
19
+ /**
20
+ * Global error handler middleware for Express applications
21
+ */
3
22
  export { errorHandler } from "./errorHandler.js";
23
+ /**
24
+ * Winston logger instance for structured application logging
25
+ */
4
26
  export { logger } from "./logger.js";
5
- export { sendSuccess, sendError, send } from "./responseFormatter.js";
6
- export { default as connectDB, getDBStatus, DatabaseConnection, } from "./DatabaseConnection.js";
27
+ /**
28
+ * Response formatting utilities with callback-based method chaining
29
+ */
30
+ export { sendSuccess, sendError } from "./responseFormatter.js";
31
+ /**
32
+ * Database connection utilities for MongoDB with automatic retry logic
33
+ */
34
+ export { default as connectDB, getDBStatus, resetDBConnection, DatabaseConnection, } from "./DatabaseConnection.js";
package/dist/index.js CHANGED
@@ -1,6 +1,34 @@
1
+ /**
2
+ * Express Utils - A comprehensive utility library for Express.js applications
3
+ *
4
+ * This library provides essential utilities for building robust Express applications:
5
+ * - Error handling with custom AppError class and global error handler
6
+ * - Async error catching middleware
7
+ * - Response formatting with callback-based chaining
8
+ * - Database connection management with retry logic
9
+ * - Structured logging with Winston
10
+ */
11
+ /**
12
+ * Custom error class for application errors with status codes and operational flags
13
+ */
1
14
  export { AppError } from "./AppError.js";
15
+ /**
16
+ * Higher-order function to catch asynchronous errors in Express route handlers
17
+ */
2
18
  export { catchAsync } from "./catchAsync.js";
19
+ /**
20
+ * Global error handler middleware for Express applications
21
+ */
3
22
  export { errorHandler } from "./errorHandler.js";
23
+ /**
24
+ * Winston logger instance for structured application logging
25
+ */
4
26
  export { logger } from "./logger.js";
5
- export { sendSuccess, sendError, send } from "./responseFormatter.js";
6
- export { default as connectDB, getDBStatus, DatabaseConnection, } from "./DatabaseConnection.js";
27
+ /**
28
+ * Response formatting utilities with callback-based method chaining
29
+ */
30
+ export { sendSuccess, sendError } from "./responseFormatter.js";
31
+ /**
32
+ * Database connection utilities for MongoDB with automatic retry logic
33
+ */
34
+ export { default as connectDB, getDBStatus, resetDBConnection, DatabaseConnection, } from "./DatabaseConnection.js";
package/dist/logger.d.ts CHANGED
@@ -1,2 +1,18 @@
1
1
  import winston from "winston";
2
+ /**
3
+ * Winston logger instance for application logging.
4
+ *
5
+ * Features:
6
+ * - Different log levels for production vs development
7
+ * - Console and file logging (in development)
8
+ * - JSON format for structured logging
9
+ * - Error stack trace capture
10
+ * - Custom service name via SERVICE_NAME environment variable
11
+ *
12
+ * @example
13
+ * // Basic logging
14
+ * logger.info("User logged in", { userId: 123 });
15
+ * logger.error("Database connection failed", { error: err });
16
+ * logger.debug("Processing request", { method: "POST", url: "/api/users" });
17
+ */
2
18
  export declare const logger: winston.Logger;
package/dist/logger.js CHANGED
@@ -1,4 +1,20 @@
1
1
  import winston from "winston";
2
+ /**
3
+ * Winston logger instance for application logging.
4
+ *
5
+ * Features:
6
+ * - Different log levels for production vs development
7
+ * - Console and file logging (in development)
8
+ * - JSON format for structured logging
9
+ * - Error stack trace capture
10
+ * - Custom service name via SERVICE_NAME environment variable
11
+ *
12
+ * @example
13
+ * // Basic logging
14
+ * logger.info("User logged in", { userId: 123 });
15
+ * logger.error("Database connection failed", { error: err });
16
+ * logger.debug("Processing request", { method: "POST", url: "/api/users" });
17
+ */
2
18
  export const logger = winston.createLogger({
3
19
  level: process.env.NODE_ENV === "production" ? "info" : "debug",
4
20
  format: winston.format.combine(winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.splat(), winston.format.json()),
@@ -4,52 +4,36 @@ import { Response } from "express";
4
4
  *
5
5
  * Features:
6
6
  * - Includes success: true field by default
7
- * - **Auto-sends** when no chaining detected (no send() needed)
8
- * - Returns Express response object for native method chaining
9
- * - Use send() only when chaining methods (.cookie(), .header(), etc.)
7
+ * - **Auto-sends** when no callbacks provided
8
+ * - Supports method chaining through callback functions
10
9
  * - Clean and predictable approach
11
10
  *
12
11
  * @param {Response} res - Express response object.
13
12
  * @param {any} data - Response data.
14
13
  * @param {string} [message='Success'] - Response message.
15
14
  * @param {number} [statusCode=200] - HTTP status code.
16
- * @returns {Response} The Express response object for chaining.
15
+ * @param {((res: Response) => Response)[]} [callbacks] - Optional array of callback functions for chaining response methods.
16
+ * @returns {Response} The Express response object.
17
17
  *
18
18
  * @example
19
- * // Basic usage (auto-sends - no send() needed)
19
+ * // Basic usage (auto-sends - no callbacks needed)
20
20
  * sendSuccess(res, { userId: 123 }, "Login successful");
21
21
  *
22
22
  * @example
23
- * // Chain methods and send manually
24
- * sendSuccess(res, { userId: 123 }, "Login successful", 200)
25
- * .cookie("authToken", "xyz789", { httpOnly: true })
26
- * .header("X-Custom", "value");
27
- * send(res); // Send prepared response
23
+ * // Chain methods using callbacks
24
+ * sendSuccess(res, { userId: 123 }, "Login successful", 200, [
25
+ * (res) => res.cookie("authToken", "xyz789", { httpOnly: true }),
26
+ * (res) => res.header("X-Custom", "value")
27
+ * ]);
28
28
  *
29
29
  * @example
30
- * // Example Login Response
31
- * sendSuccess(res, { accesstoken, refreshToken, user }, "Login Successful", 200)
32
- * .cookie("accessToken", accesstoken, HTTP_OPTIONS)
33
- * .cookie("refreshToken", refreshToken, HTTP_OPTIONS);
34
- * send(res); // Send when ready
30
+ * // Example Login Response with multiple callbacks
31
+ * sendSuccess(res, { accesstoken, refreshToken, user }, "Login Successful", 200, [
32
+ * (res) => res.cookie("accessToken", accesstoken, HTTP_OPTIONS),
33
+ * (res) => res.cookie("refreshToken", refreshToken, HTTP_OPTIONS)
34
+ * ]);
35
35
  */
36
- export declare const sendSuccess: (res: Response, data: any, message?: string, statusCode?: number) => Response;
37
- /**
38
- * Sends the prepared success response.
39
- * Use this only when chaining methods (.cookie(), .header(), etc.).
40
- * For basic usage, sendSuccess() auto-sends and you don't need this.
41
- *
42
- * @param {Response} res - Express response object.
43
- * @returns {void}
44
- *
45
- * @example
46
- * // Only needed when chaining methods
47
- * sendSuccess(res, data, "Success", 200)
48
- * .cookie("session", "abc123")
49
- * .header("X-Custom", "value");
50
- * send(res); // Send when ready
51
- */
52
- export declare const send: (res: Response) => void;
36
+ export declare const sendSuccess: (res: Response, data: any, message?: string, statusCode?: number, callbacks?: ((res: Response) => Response)[]) => Response;
53
37
  /**
54
38
  * Sends an error response immediately.
55
39
  *
@@ -3,71 +3,54 @@
3
3
  *
4
4
  * Features:
5
5
  * - Includes success: true field by default
6
- * - **Auto-sends** when no chaining detected (no send() needed)
7
- * - Returns Express response object for native method chaining
8
- * - Use send() only when chaining methods (.cookie(), .header(), etc.)
6
+ * - **Auto-sends** when no callbacks provided
7
+ * - Supports method chaining through callback functions
9
8
  * - Clean and predictable approach
10
9
  *
11
10
  * @param {Response} res - Express response object.
12
11
  * @param {any} data - Response data.
13
12
  * @param {string} [message='Success'] - Response message.
14
13
  * @param {number} [statusCode=200] - HTTP status code.
15
- * @returns {Response} The Express response object for chaining.
14
+ * @param {((res: Response) => Response)[]} [callbacks] - Optional array of callback functions for chaining response methods.
15
+ * @returns {Response} The Express response object.
16
16
  *
17
17
  * @example
18
- * // Basic usage (auto-sends - no send() needed)
18
+ * // Basic usage (auto-sends - no callbacks needed)
19
19
  * sendSuccess(res, { userId: 123 }, "Login successful");
20
20
  *
21
21
  * @example
22
- * // Chain methods and send manually
23
- * sendSuccess(res, { userId: 123 }, "Login successful", 200)
24
- * .cookie("authToken", "xyz789", { httpOnly: true })
25
- * .header("X-Custom", "value");
26
- * send(res); // Send prepared response
22
+ * // Chain methods using callbacks
23
+ * sendSuccess(res, { userId: 123 }, "Login successful", 200, [
24
+ * (res) => res.cookie("authToken", "xyz789", { httpOnly: true }),
25
+ * (res) => res.header("X-Custom", "value")
26
+ * ]);
27
27
  *
28
28
  * @example
29
- * // Example Login Response
30
- * sendSuccess(res, { accesstoken, refreshToken, user }, "Login Successful", 200)
31
- * .cookie("accessToken", accesstoken, HTTP_OPTIONS)
32
- * .cookie("refreshToken", refreshToken, HTTP_OPTIONS);
33
- * send(res); // Send when ready
29
+ * // Example Login Response with multiple callbacks
30
+ * sendSuccess(res, { accesstoken, refreshToken, user }, "Login Successful", 200, [
31
+ * (res) => res.cookie("accessToken", accesstoken, HTTP_OPTIONS),
32
+ * (res) => res.cookie("refreshToken", refreshToken, HTTP_OPTIONS)
33
+ * ]);
34
34
  */
35
- export const sendSuccess = (res, data, message = "Success", statusCode = 200) => {
35
+ export const sendSuccess = (res, data, message = "Success", statusCode = 200, callbacks) => {
36
36
  const response = {
37
37
  status: "success",
38
38
  success: true,
39
39
  message,
40
40
  data,
41
41
  };
42
- // Set status and store response for later sending
43
42
  res.status(statusCode);
44
- res._responseData = response;
45
- // Auto-send unless chaining is detected (using setImmediate to check)
46
- setImmediate(() => {
47
- if (!res._responseSent && res._responseData) {
48
- res._responseSent = true;
49
- res.json(res._responseData);
43
+ // Execute callbacks for chaining if provided
44
+ if (callbacks && callbacks.length > 0) {
45
+ let currentRes = res;
46
+ for (const callback of callbacks) {
47
+ if (typeof callback === 'function') {
48
+ currentRes = callback(currentRes);
49
+ }
50
50
  }
51
- });
52
- return res;
53
- };
54
- /**
55
- * Sends the prepared success response.
56
- * Use this only when chaining methods (.cookie(), .header(), etc.).
57
- * For basic usage, sendSuccess() auto-sends and you don't need this.
58
- *
59
- * @param {Response} res - Express response object.
60
- * @returns {void}
61
- *
62
- * @example
63
- * // Only needed when chaining methods
64
- * sendSuccess(res, data, "Success", 200)
65
- * .cookie("session", "abc123")
66
- * .header("X-Custom", "value");
67
- * send(res); // Send when ready
68
- */
69
- export const send = (res) => {
70
- res.json(res._responseData);
51
+ }
52
+ // Send response
53
+ return res.json(response);
71
54
  };
72
55
  /**
73
56
  * Sends an error response immediately.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devdad-express-utils",
3
- "version": "1.7.2",
3
+ "version": "1.8.1",
4
4
  "description": "Reusable Express.js utilities for error handling, async wrapping, and more",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",