devdad-express-utils 1.8.0 → 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.
@@ -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";
27
+ /**
28
+ * Response formatting utilities with callback-based method chaining
29
+ */
5
30
  export { sendSuccess, sendError } from "./responseFormatter.js";
6
- export { default as connectDB, getDBStatus, DatabaseConnection, } from "./DatabaseConnection.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";
27
+ /**
28
+ * Response formatting utilities with callback-based method chaining
29
+ */
5
30
  export { sendSuccess, sendError } from "./responseFormatter.js";
6
- export { default as connectDB, getDBStatus, DatabaseConnection, } from "./DatabaseConnection.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,34 +4,34 @@ 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
36
  export declare const sendSuccess: (res: Response, data: any, message?: string, statusCode?: number, callbacks?: ((res: Response) => Response)[]) => Response;
37
37
  /**
@@ -3,34 +3,34 @@
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
35
  export const sendSuccess = (res, data, message = "Success", statusCode = 200, callbacks) => {
36
36
  const response = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "devdad-express-utils",
3
- "version": "1.8.0",
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",