-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.ts
More file actions
52 lines (40 loc) · 1.3 KB
/
Copy pathdb.ts
File metadata and controls
52 lines (40 loc) · 1.3 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
import mongoose from "mongoose";
import { MongoClient } from "mongodb";
const url = process.env.MONGO_URI;
const fallbackUrl = "mongodb://127.0.0.1:27017/operation-surf-build";
let connection: typeof mongoose;
let mongooseConnectionPromise: Promise<typeof mongoose> | null = null;
let mongoClientConnectionPromise: Promise<MongoClient> | null = null;
// Avoid crashing during Next.js build analysis when envs are not loaded yet.
export const client = new MongoClient(url ?? fallbackUrl);
function getMongoUri(): string {
if (!url) {
throw new Error("MONGO_URI is not set.");
}
return url;
}
const connectMongoClient = async () => {
getMongoUri();
if (!mongoClientConnectionPromise) {
mongoClientConnectionPromise = client.connect();
}
return mongoClientConnectionPromise;
};
/**
* Makes a connection to a MongoDB database. If a connection already exists, does nothing
* Call this function before all api routes
* @returns {Promise<typeof mongoose>}
*/
const connectDB = async () => {
const mongoUri = getMongoUri();
await connectMongoClient();
if (connection) {
return connection;
}
if (!mongooseConnectionPromise) {
mongooseConnectionPromise = mongoose.connect(mongoUri);
}
connection = await mongooseConnectionPromise;
return connection;
};
export default connectDB;