devdad-express-utils 1.1.2 → 1.3.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 +67 -1
- package/dist/DatabaseConnection.d.ts +50 -0
- package/dist/DatabaseConnection.js +127 -0
- package/dist/errorHandler.js +3 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/logger.d.ts +2 -0
- package/dist/logger.js +15 -0
- package/package.json +7 -2
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,
|
|
3
|
+
A collection of reusable utilities for Express.js applications, including error handling, async route wrapping, custom error classes, MongoDB connection management, and Winston-based logging.
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
@@ -83,6 +83,48 @@ app.get('/profile', authMiddleware, (req, res) => {
|
|
|
83
83
|
});
|
|
84
84
|
```
|
|
85
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
|
+
|
|
101
|
+
### Logging
|
|
102
|
+
|
|
103
|
+
Winston-based logger with configurable service name and environment-aware transports.
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
import { logger } from "devdad-express-utils";
|
|
107
|
+
|
|
108
|
+
// Log messages at different levels
|
|
109
|
+
logger.info("User logged in", { userId: 123 });
|
|
110
|
+
logger.error("Database connection failed", { error: err.message });
|
|
111
|
+
logger.debug("Processing request", { requestId: "abc-123" });
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
#### Configuration
|
|
115
|
+
|
|
116
|
+
- **Service Name**: Set `SERVICE_NAME` environment variable to customize the service name in logs (defaults to "express-utils")
|
|
117
|
+
- **Log Level**: "debug" in development, "info" in production
|
|
118
|
+
- **Transports**:
|
|
119
|
+
- **Development**: Console (colored) + error.log + combined.log files
|
|
120
|
+
- **Production**: Console only (suitable for platforms like Railway)
|
|
121
|
+
|
|
122
|
+
#### Log Files
|
|
123
|
+
|
|
124
|
+
In development, logs are written to:
|
|
125
|
+
- `error.log`: Error level and above
|
|
126
|
+
- `combined.log`: All log levels
|
|
127
|
+
|
|
86
128
|
## Error Handling Patterns
|
|
87
129
|
|
|
88
130
|
### Using AppError
|
|
@@ -190,6 +232,30 @@ Middleware for JWT authentication.
|
|
|
190
232
|
requireAuth(options: { secret: string, algorithms?: Algorithm[] }) => (req, res, next) => void
|
|
191
233
|
```
|
|
192
234
|
|
|
235
|
+
### connectDB
|
|
236
|
+
|
|
237
|
+
Connects to MongoDB with retry logic and automatic reconnection.
|
|
238
|
+
|
|
239
|
+
```typescript
|
|
240
|
+
connectDB() => Promise<void>
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
### getDBStatus
|
|
244
|
+
|
|
245
|
+
Gets the current MongoDB connection status.
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
getDBStatus() => { isConnected: boolean; readyState: number; host: string; name: string; }
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### logger
|
|
252
|
+
|
|
253
|
+
Winston logger instance with JSON formatting, timestamps, and error stack traces.
|
|
254
|
+
|
|
255
|
+
```typescript
|
|
256
|
+
logger: winston.Logger
|
|
257
|
+
```
|
|
258
|
+
|
|
193
259
|
## Development
|
|
194
260
|
|
|
195
261
|
```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 };
|
package/dist/errorHandler.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AppError } from "./AppError.js";
|
|
2
|
+
import { logger } from "./logger.js";
|
|
2
3
|
/**
|
|
3
4
|
* Sends detailed error information in development mode.
|
|
4
5
|
* @param {any} err - The error object.
|
|
@@ -29,7 +30,7 @@ const sendErrorProd = (err, res) => {
|
|
|
29
30
|
}
|
|
30
31
|
else {
|
|
31
32
|
// Unknown error → hide details
|
|
32
|
-
|
|
33
|
+
logger.error("Unknown error occurred", err);
|
|
33
34
|
res.status(500).json({
|
|
34
35
|
status: "error",
|
|
35
36
|
message: "Something went wrong!",
|
|
@@ -47,7 +48,7 @@ const errorHandler = (err, req, res, next) => {
|
|
|
47
48
|
err.statusCode = err.statusCode || 500;
|
|
48
49
|
err.status = err.status || "error";
|
|
49
50
|
// Add this for Extra In-Depth Error Logging
|
|
50
|
-
|
|
51
|
+
logger.error("Error details", {
|
|
51
52
|
message: err.message,
|
|
52
53
|
statusCode: err.statusCode,
|
|
53
54
|
errors: err.errors,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { AppError } from "./AppError.js";
|
|
2
2
|
export { catchAsync } from "./catchAsync.js";
|
|
3
3
|
export { errorHandler } from "./errorHandler.js";
|
|
4
|
+
export { logger } from "./logger.js";
|
|
4
5
|
export { sendSuccess, sendError } from "./responseFormatter.js";
|
|
5
6
|
export { requireAuth } from "./authWrapper.js";
|
|
7
|
+
export { default as connectDB, getDBStatus, DatabaseConnection } from "./DatabaseConnection.js";
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export { AppError } from "./AppError.js";
|
|
2
2
|
export { catchAsync } from "./catchAsync.js";
|
|
3
3
|
export { errorHandler } from "./errorHandler.js";
|
|
4
|
+
export { logger } from "./logger.js";
|
|
4
5
|
export { sendSuccess, sendError } from "./responseFormatter.js";
|
|
5
6
|
export { requireAuth } from "./authWrapper.js";
|
|
7
|
+
export { default as connectDB, getDBStatus, DatabaseConnection } from "./DatabaseConnection.js";
|
package/dist/logger.d.ts
ADDED
package/dist/logger.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import winston from "winston";
|
|
2
|
+
export const logger = winston.createLogger({
|
|
3
|
+
level: process.env.NODE_ENV === "production" ? "info" : "debug",
|
|
4
|
+
format: winston.format.combine(winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.splat(), winston.format.json()),
|
|
5
|
+
defaultMeta: { service: process.env.SERVICE_NAME || "express-utils" },
|
|
6
|
+
transports: [
|
|
7
|
+
new winston.transports.Console({
|
|
8
|
+
format: winston.format.combine(winston.format.colorize(), winston.format.simple()),
|
|
9
|
+
}),
|
|
10
|
+
...(process.env.NODE_ENV !== "production" ? [
|
|
11
|
+
new winston.transports.File({ filename: "error.log", level: "error" }),
|
|
12
|
+
new winston.transports.File({ filename: "combined.log" }),
|
|
13
|
+
] : []),
|
|
14
|
+
],
|
|
15
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "devdad-express-utils",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.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",
|
|
@@ -26,14 +26,19 @@
|
|
|
26
26
|
},
|
|
27
27
|
"license": "ISC",
|
|
28
28
|
"dependencies": {
|
|
29
|
+
"@types/mongoose": "^5.11.96",
|
|
29
30
|
"express": "^5.1.0",
|
|
30
|
-
"jsonwebtoken": "^9.0.2"
|
|
31
|
+
"jsonwebtoken": "^9.0.2",
|
|
32
|
+
"mongoose": "^9.0.0",
|
|
33
|
+
"winston": "^3.17.0"
|
|
31
34
|
},
|
|
32
35
|
"devDependencies": {
|
|
33
36
|
"@types/express": "^5.0.5",
|
|
34
37
|
"@types/jsonwebtoken": "^9.0.10",
|
|
38
|
+
"@types/mongodb-memory-server": "^1.8.0",
|
|
35
39
|
"@types/supertest": "^6.0.3",
|
|
36
40
|
"@vitest/ui": "^4.0.14",
|
|
41
|
+
"mongodb-memory-server": "^10.3.0",
|
|
37
42
|
"supertest": "^7.1.4",
|
|
38
43
|
"typescript": "^5.9.3",
|
|
39
44
|
"vitest": "^4.0.14"
|