devdad-express-utils 1.1.1 → 1.2.0

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
@@ -1,6 +1,6 @@
1
1
  # Express Utils
2
2
 
3
- A collection of reusable utilities for Express.js applications, including error handling, async route wrapping, and custom error classes.
3
+ A collection of reusable utilities for Express.js applications, including error handling, async route wrapping, custom error classes, and MongoDB connection management.
4
4
 
5
5
  ## Installation
6
6
 
@@ -52,6 +52,52 @@ import { AppError } from "devdad-express-utils";
52
52
  throw new AppError("Validation failed", 400, ["Email is required"]);
53
53
  ```
54
54
 
55
+ ### Response Formatting
56
+
57
+ Standardize API responses with consistent JSON structure.
58
+
59
+ ```typescript
60
+ import { sendSuccess, sendError, sendPaginated } from "devdad-express-utils";
61
+
62
+ // Success response
63
+ sendSuccess(res, { id: 1, name: 'John' }, 'User fetched', 200);
64
+
65
+ // Error response
66
+ sendError(res, 'User not found', 404);
67
+
68
+
69
+ ```
70
+
71
+ ### Authentication Middleware
72
+
73
+ JWT-based authentication wrapper.
74
+
75
+ ```typescript
76
+ import { requireAuth } from "devdad-express-utils";
77
+
78
+ const authMiddleware = requireAuth({ secret: process.env.JWT_SECRET });
79
+
80
+ app.get('/profile', authMiddleware, (req, res) => {
81
+ // req.user contains decoded JWT
82
+ res.json(req.user);
83
+ });
84
+ ```
85
+
86
+ ### Database Connection
87
+
88
+ MongoDB connection utility with automatic reconnection and retry logic.
89
+
90
+ ```typescript
91
+ import { connectDB, getDBStatus } from "devdad-express-utils";
92
+
93
+ // Connect to MongoDB (ensure MONGO_URI is set in environment)
94
+ await connectDB();
95
+
96
+ // Check connection status
97
+ const status = getDBStatus();
98
+ console.log(status); // { isConnected: true, readyState: 1, host: '...', name: '...' }
99
+ ```
100
+
55
101
  ## Error Handling Patterns
56
102
 
57
103
  ### Using AppError
@@ -133,6 +179,48 @@ Express error handling middleware with detailed logging in development.
133
179
  errorHandler(err: any, req: Request, res: Response, next: NextFunction) => void
134
180
  ```
135
181
 
182
+ ### sendSuccess
183
+
184
+ Sends a standardized success response.
185
+
186
+ ```typescript
187
+ sendSuccess(res: Response, data: any, message?: string, statusCode?: number) => void
188
+ ```
189
+
190
+ ### sendError
191
+
192
+ Sends a standardized error response.
193
+
194
+ ```typescript
195
+ sendError(res: Response, message: string, statusCode?: number, data?: any) => void
196
+ ```
197
+
198
+
199
+
200
+ ### requireAuth
201
+
202
+ Middleware for JWT authentication.
203
+
204
+ ```typescript
205
+ requireAuth(options: { secret: string, algorithms?: Algorithm[] }) => (req, res, next) => void
206
+ ```
207
+
208
+ ### connectDB
209
+
210
+ Connects to MongoDB with retry logic and automatic reconnection.
211
+
212
+ ```typescript
213
+ connectDB() => Promise<void>
214
+ ```
215
+
216
+ ### getDBStatus
217
+
218
+ Gets the current MongoDB connection status.
219
+
220
+ ```typescript
221
+ getDBStatus() => { isConnected: boolean; readyState: number; host: string; name: string; }
222
+ ```
223
+
136
224
  ## Development
137
225
 
138
226
  ```bash
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Database connection class for MongoDB using Mongoose.
3
+ * Provides automatic reconnection, retry logic, and connection status monitoring.
4
+ */
5
+ declare class DatabaseConnection {
6
+ private retryCount;
7
+ private isConnected;
8
+ /**
9
+ * Creates a new DatabaseConnection instance.
10
+ * Sets up event listeners for connection events and application termination signals.
11
+ */
12
+ constructor();
13
+ /**
14
+ * Establishes a connection to MongoDB.
15
+ * @throws {Error} If MONGO_URI is not defined in environment variables.
16
+ */
17
+ connect(): Promise<void>;
18
+ /**
19
+ * Handles connection errors by retrying the connection up to MAX_RETRIES times.
20
+ * Exits the process if all retries fail.
21
+ */
22
+ private handleConnectionError;
23
+ /**
24
+ * Handles disconnection events by attempting to reconnect if not already connected.
25
+ */
26
+ private handleDisconnection;
27
+ /**
28
+ * Handles application termination by closing the database connection gracefully.
29
+ */
30
+ private handleAppTermination;
31
+ /**
32
+ * Gets the current connection status.
33
+ * @returns An object containing connection status information.
34
+ */
35
+ getConnectionStatus(): {
36
+ isConnected: boolean;
37
+ readyState: number;
38
+ host: string;
39
+ name: string;
40
+ };
41
+ }
42
+ declare const _default: () => Promise<void>;
43
+ export default _default;
44
+ export declare const getDBStatus: () => {
45
+ isConnected: boolean;
46
+ readyState: number;
47
+ host: string;
48
+ name: string;
49
+ };
50
+ export { DatabaseConnection };
@@ -0,0 +1,127 @@
1
+ import mongoose from "mongoose";
2
+ /**
3
+ * Maximum number of connection retry attempts
4
+ */
5
+ const MAX_RETRIES = 3;
6
+ /**
7
+ * Interval between retry attempts in milliseconds
8
+ */
9
+ const RETRY_INTERVAL = 5000; // 5 seconds
10
+ /**
11
+ * Database connection class for MongoDB using Mongoose.
12
+ * Provides automatic reconnection, retry logic, and connection status monitoring.
13
+ */
14
+ class DatabaseConnection {
15
+ retryCount;
16
+ isConnected;
17
+ /**
18
+ * Creates a new DatabaseConnection instance.
19
+ * Sets up event listeners for connection events and application termination signals.
20
+ */
21
+ constructor() {
22
+ this.retryCount = 0;
23
+ this.isConnected = false;
24
+ // Configure mongoose settings
25
+ mongoose.set("strictQuery", true);
26
+ // Handle connection events
27
+ mongoose.connection.on("connected", () => {
28
+ console.log("✅ MongoDB connected successfully");
29
+ this.isConnected = true;
30
+ });
31
+ mongoose.connection.on("error", (err) => {
32
+ console.error("❌ MongoDB connection error:", err);
33
+ this.isConnected = false;
34
+ });
35
+ mongoose.connection.on("disconnected", () => {
36
+ console.log("⚠️ MongoDB disconnected");
37
+ this.isConnected = false;
38
+ this.handleDisconnection();
39
+ });
40
+ // Handle application termination
41
+ process.on("SIGINT", this.handleAppTermination.bind(this));
42
+ process.on("SIGTERM", this.handleAppTermination.bind(this));
43
+ }
44
+ /**
45
+ * Establishes a connection to MongoDB.
46
+ * @throws {Error} If MONGO_URI is not defined in environment variables.
47
+ */
48
+ async connect() {
49
+ try {
50
+ if (!process.env.MONGO_URI) {
51
+ throw new Error("MongoDB URI is not defined in environment variables");
52
+ }
53
+ const connectionOptions = {
54
+ maxPoolSize: 10,
55
+ serverSelectionTimeoutMS: 5000,
56
+ socketTimeoutMS: 45000,
57
+ family: 4, // Use IPv4
58
+ };
59
+ if (process.env.NODE_ENV === "development") {
60
+ mongoose.set("debug", true);
61
+ }
62
+ await mongoose.connect(process.env.MONGO_URI, connectionOptions);
63
+ this.retryCount = 0; // Reset retry count on successful connection
64
+ }
65
+ catch (error) {
66
+ console.error("Failed to connect to MongoDB:", error.message);
67
+ await this.handleConnectionError();
68
+ }
69
+ }
70
+ /**
71
+ * Handles connection errors by retrying the connection up to MAX_RETRIES times.
72
+ * Exits the process if all retries fail.
73
+ */
74
+ async handleConnectionError() {
75
+ if (this.retryCount < MAX_RETRIES) {
76
+ this.retryCount++;
77
+ console.log(`Retrying connection... Attempt ${this.retryCount} of ${MAX_RETRIES}`);
78
+ await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL));
79
+ return this.connect();
80
+ }
81
+ else {
82
+ console.error(`Failed to connect to MongoDB after ${MAX_RETRIES} attempts`);
83
+ process.exit(1);
84
+ }
85
+ }
86
+ /**
87
+ * Handles disconnection events by attempting to reconnect if not already connected.
88
+ */
89
+ handleDisconnection() {
90
+ if (!this.isConnected) {
91
+ console.log("Attempting to reconnect to MongoDB...");
92
+ this.connect();
93
+ }
94
+ }
95
+ /**
96
+ * Handles application termination by closing the database connection gracefully.
97
+ */
98
+ async handleAppTermination() {
99
+ try {
100
+ await mongoose.connection.close();
101
+ console.log("MongoDB connection closed through app termination");
102
+ process.exit(0);
103
+ }
104
+ catch (err) {
105
+ console.error("Error during database disconnection:", err);
106
+ process.exit(1);
107
+ }
108
+ }
109
+ /**
110
+ * Gets the current connection status.
111
+ * @returns An object containing connection status information.
112
+ */
113
+ getConnectionStatus() {
114
+ return {
115
+ isConnected: this.isConnected,
116
+ readyState: mongoose.connection.readyState,
117
+ host: mongoose.connection.host,
118
+ name: mongoose.connection.name,
119
+ };
120
+ }
121
+ }
122
+ // Create a singleton instance
123
+ const dbConnection = new DatabaseConnection();
124
+ // Export the connect function and the instance
125
+ export default dbConnection.connect.bind(dbConnection);
126
+ export const getDBStatus = dbConnection.getConnectionStatus.bind(dbConnection);
127
+ export { DatabaseConnection };
@@ -0,0 +1,17 @@
1
+ import { JwtPayload, Algorithm } from "jsonwebtoken";
2
+ import { Request, Response, NextFunction } from "express";
3
+ interface AuthOptions {
4
+ secret: string;
5
+ algorithms?: Algorithm[];
6
+ }
7
+ interface AuthenticatedRequest extends Request {
8
+ user?: JwtPayload | string;
9
+ }
10
+ /**
11
+ * Middleware to require JWT authentication.
12
+ * Verifies the JWT token from Authorization header and attaches decoded payload to req.user.
13
+ * @param {AuthOptions} options - JWT verification options.
14
+ * @returns {(req: Request, res: Response, next: NextFunction) => void} - Middleware function.
15
+ */
16
+ export declare const requireAuth: (options: AuthOptions) => (req: AuthenticatedRequest, res: Response, next: NextFunction) => void;
17
+ export {};
@@ -0,0 +1,48 @@
1
+ import jwt, { JsonWebTokenError, TokenExpiredError, } from "jsonwebtoken";
2
+ import { AppError } from "./AppError.js";
3
+ const defaultAlgorithms = ["HS256"];
4
+ /**
5
+ * Middleware to require JWT authentication.
6
+ * Verifies the JWT token from Authorization header and attaches decoded payload to req.user.
7
+ * @param {AuthOptions} options - JWT verification options.
8
+ * @returns {(req: Request, res: Response, next: NextFunction) => void} - Middleware function.
9
+ */
10
+ export const requireAuth = (options) => {
11
+ return (req, res, next) => {
12
+ const authHeader = req.headers.authorization;
13
+ if (!authHeader) {
14
+ throw new AppError("Access denied. No token provided.", 401);
15
+ }
16
+ if (!authHeader.startsWith("Bearer ")) {
17
+ throw new AppError("Malformed authorization header.", 401);
18
+ }
19
+ const token = authHeader.substring(7);
20
+ if (!token) {
21
+ throw new AppError("Access denied. No token provided.", 401);
22
+ }
23
+ try {
24
+ let decoded;
25
+ if (options.algorithms) {
26
+ decoded = jwt.verify(token, options.secret, {
27
+ algorithms: options.algorithms,
28
+ });
29
+ }
30
+ else {
31
+ decoded = jwt.verify(token, options.secret);
32
+ }
33
+ req.user = decoded;
34
+ next();
35
+ }
36
+ catch (error) {
37
+ if (error instanceof JsonWebTokenError) {
38
+ throw new AppError("Invalid token.", 401);
39
+ }
40
+ else if (error instanceof TokenExpiredError) {
41
+ throw new AppError("Token expired.", 401);
42
+ }
43
+ else {
44
+ throw new AppError("Authentication failed.", 401);
45
+ }
46
+ }
47
+ };
48
+ };
@@ -5,6 +5,6 @@
5
5
  * @returns {(req: Request, res: Response, next: NextFunction) => void} - The wrapped handler that catches errors.
6
6
  */
7
7
  export const catchAsync = (fn) => (req, res, next) => {
8
- fn(req, res, next).catch(next);
8
+ Promise.resolve(fn(req, res, next)).catch(next);
9
9
  };
10
10
  //#endregion
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  export { AppError } from "./AppError.js";
2
2
  export { catchAsync } from "./catchAsync.js";
3
3
  export { errorHandler } from "./errorHandler.js";
4
+ export { sendSuccess, sendError } from "./responseFormatter.js";
5
+ export { requireAuth } from "./authWrapper.js";
6
+ export { default as connectDB, getDBStatus, DatabaseConnection } from "./DatabaseConnection.js";
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
1
  export { AppError } from "./AppError.js";
2
2
  export { catchAsync } from "./catchAsync.js";
3
3
  export { errorHandler } from "./errorHandler.js";
4
+ export { sendSuccess, sendError } from "./responseFormatter.js";
5
+ export { requireAuth } from "./authWrapper.js";
6
+ export { default as connectDB, getDBStatus, DatabaseConnection } from "./DatabaseConnection.js";
@@ -0,0 +1,17 @@
1
+ import { Response } from "express";
2
+ /**
3
+ * Sends a success response.
4
+ * @param {Response} res - Express response object.
5
+ * @param {any} data - Response data.
6
+ * @param {string} [message='Success'] - Response message.
7
+ * @param {number} [statusCode=200] - HTTP status code.
8
+ */
9
+ export declare const sendSuccess: (res: Response, data: any, message?: string, statusCode?: number) => void;
10
+ /**
11
+ * Sends an error response.
12
+ * @param {Response} res - Express response object.
13
+ * @param {string} message - Error message.
14
+ * @param {number} [statusCode=400] - HTTP status code.
15
+ * @param {any} [data] - Additional error data.
16
+ */
17
+ export declare const sendError: (res: Response, message: string, statusCode?: number, data?: any) => void;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Sends a success response.
3
+ * @param {Response} res - Express response object.
4
+ * @param {any} data - Response data.
5
+ * @param {string} [message='Success'] - Response message.
6
+ * @param {number} [statusCode=200] - HTTP status code.
7
+ */
8
+ export const sendSuccess = (res, data, message = "Success", statusCode = 200) => {
9
+ const response = {
10
+ status: "success",
11
+ message,
12
+ data,
13
+ };
14
+ res.status(statusCode).json(response);
15
+ };
16
+ /**
17
+ * Sends an error response.
18
+ * @param {Response} res - Express response object.
19
+ * @param {string} message - Error message.
20
+ * @param {number} [statusCode=400] - HTTP status code.
21
+ * @param {any} [data] - Additional error data.
22
+ */
23
+ export const sendError = (res, message, statusCode = 400, data) => {
24
+ const response = {
25
+ status: "error",
26
+ message,
27
+ ...(data && { data }),
28
+ };
29
+ res.status(statusCode).json(response);
30
+ };
@@ -0,0 +1,9 @@
1
+ import { ValidationChain } from 'express-validator';
2
+ import { Request, Response, NextFunction } from 'express';
3
+ /**
4
+ * Middleware wrapper for express-validator validations.
5
+ * Runs the provided validations and throws AppError if any fail.
6
+ * @param {ValidationChain[]} validations - Array of express-validator validation chains.
7
+ * @returns {(req: Request, res: Response, next: NextFunction) => Promise<void>} - Middleware function.
8
+ */
9
+ export declare const validateRequest: (validations: ValidationChain[]) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
@@ -0,0 +1,19 @@
1
+ import { validationResult } from 'express-validator';
2
+ import { AppError } from './AppError.js';
3
+ /**
4
+ * Middleware wrapper for express-validator validations.
5
+ * Runs the provided validations and throws AppError if any fail.
6
+ * @param {ValidationChain[]} validations - Array of express-validator validation chains.
7
+ * @returns {(req: Request, res: Response, next: NextFunction) => Promise<void>} - Middleware function.
8
+ */
9
+ export const validateRequest = (validations) => {
10
+ return async (req, res, next) => {
11
+ await Promise.all(validations.map(validation => validation.run(req)));
12
+ const errors = validationResult(req);
13
+ if (!errors.isEmpty()) {
14
+ const errorMessages = errors.array().map(err => err.msg);
15
+ throw new AppError('Validation failed', 400, errorMessages);
16
+ }
17
+ next();
18
+ };
19
+ };
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "devdad-express-utils",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
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",
7
7
  "type": "module",
8
8
  "scripts": {
9
9
  "build": "tsc",
10
- "test": "echo \"Error: no test specified\" && exit 1",
10
+ "test": "vitest",
11
+ "test:ui": "vitest --ui",
12
+ "test:coverage": "vitest run --coverage",
11
13
  "prepublishOnly": "npm run build"
12
14
  },
13
15
  "keywords": [
@@ -24,11 +26,21 @@
24
26
  },
25
27
  "license": "ISC",
26
28
  "dependencies": {
27
- "express": "^5.1.0"
29
+ "@types/mongoose": "^5.11.96",
30
+ "express": "^5.1.0",
31
+ "jsonwebtoken": "^9.0.2",
32
+ "mongoose": "^9.0.0"
28
33
  },
29
34
  "devDependencies": {
30
35
  "@types/express": "^5.0.5",
31
- "typescript": "^5.9.3"
36
+ "@types/jsonwebtoken": "^9.0.10",
37
+ "@types/mongodb-memory-server": "^1.8.0",
38
+ "@types/supertest": "^6.0.3",
39
+ "@vitest/ui": "^4.0.14",
40
+ "mongodb-memory-server": "^10.3.0",
41
+ "supertest": "^7.1.4",
42
+ "typescript": "^5.9.3",
43
+ "vitest": "^4.0.14"
32
44
  },
33
45
  "files": [
34
46
  "dist"