-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb.ts
52 lines (41 loc) · 1 KB
/
mongodb.ts
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
/* eslint-disable */
import mongoose from "mongoose";
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
throw new Error("Please define the MONGODB_URI environment variable");
}
// Define the type for our cached mongoose connection
declare global {
var mongoose:
| {
conn: typeof mongoose | null;
promise: Promise<typeof mongoose> | null;
}
| undefined;
}
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
export async function connectToDatabase() {
// Now TypeScript knows cached is defined
cached = cached || { conn: null, promise: null };
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose
.connect(MONGODB_URI as string, opts)
.then(() => cached);
}
try {
cached.conn = await cached.promise;
} catch (e) {
cached.promise = null;
throw e;
}
return cached.conn;
}