forked from niharika-mente/DevEvent_Tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongodb.ts
More file actions
80 lines (68 loc) · 2.18 KB
/
Copy pathmongodb.ts
File metadata and controls
80 lines (68 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import mongoose, { Mongoose } from "mongoose";
/**
* MongoDB connection string from environment variables.
* Ensure MONGODB_URI is set in your .env.local file.
*/
const MONGODB_URI = process.env.MONGODB_URI;
/**
* Interface for the cached connection object.
* - conn: The active Mongoose connection instance (or null if not connected).
* - promise: The pending connection promise (or null if no connection is in progress).
*/
interface MongooseCache {
conn: Mongoose | null;
promise: Promise<Mongoose> | null;
}
/**
* Extend the global namespace to include our mongoose cache.
* This prevents TypeScript errors when accessing globalThis.mongoose.
*/
declare global {
var mongoose: MongooseCache | undefined;
}
/**
* Cached connection object.
* In development, we store this on globalThis to persist across hot reloads.
* This prevents creating multiple connections during development.
*/
const cached: MongooseCache = globalThis.mongoose ?? {
conn: null,
promise: null,
};
// Persist the cache on globalThis for development hot reloads
globalThis.mongoose = cached;
/**
* Connects to MongoDB and returns the Mongoose instance.
* Uses a cached connection to prevent multiple connections in development.
*
* @returns Promise<Mongoose> - The connected Mongoose instance.
*/
async function connectToDatabase(): Promise<Mongoose> {
if (!MONGODB_URI) {
throw new Error(
"Please define the MONGODB_URI environment variable inside .env.local"
);
}
// Return cached connection if available
if (cached.conn) {
return cached.conn;
}
// If no pending connection, create one
if (!cached.promise) {
const options = {
bufferCommands: false, // Disable command buffering for better error handling
serverSelectionTimeoutMS: 5000,
};
cached.promise = mongoose.connect(MONGODB_URI, options);
}
try {
// Await the connection and cache it
cached.conn = await cached.promise;
} catch (error) {
// Reset the promise on error so we can retry
cached.promise = null;
throw error;
}
return cached.conn;
}
export default connectToDatabase;