File tree Expand file tree Collapse file tree 1 file changed +31
-17
lines changed Expand file tree Collapse file tree 1 file changed +31
-17
lines changed Original file line number Diff line number Diff line change 1
1
import mongoose from "mongoose" ;
2
-
3
- if ( ! process . env . MONGODB_URI ) {
4
- throw new Error ( "Please add your Mongo URI to .env.local" ) ;
2
+ declare global {
3
+ // eslint-disable-next-line no-var
4
+ var mongoose : { conn : mongoose . Mongoose | null ; promise : Promise < mongoose . Mongoose > | null } | undefined ; // This must be a `var` and not a `let / const`
5
5
}
6
6
7
- const uri = process . env . MONGODB_URI ;
7
+ let cached = global . mongoose ;
8
8
9
- let isConnected = false ;
9
+ cached ??= global . mongoose = { conn : null , promise : null } ;
10
10
11
- export const connectToDatabase = async ( ) => {
12
- if ( isConnected ) {
13
- return ;
14
- }
11
+ export async function connectToDatabase ( ) {
12
+ const MONGODB_URI = process . env . MONGODB_URI ! ;
15
13
16
- if ( mongoose . connection . readyState === mongoose . ConnectionStates . connected ) {
17
- isConnected = true ;
18
- return ;
14
+ if ( ! MONGODB_URI ) {
15
+ throw new Error (
16
+ "Please define the MONGODB_URI environment variable inside .env.local" ,
17
+ ) ;
19
18
}
20
19
20
+ if ( cached ?. conn ) {
21
+ return cached . conn ;
22
+ }
23
+ if ( cached && ! cached . promise ) {
24
+ const opts = {
25
+ bufferCommands : false ,
26
+ } ;
27
+ cached . promise = mongoose . connect ( MONGODB_URI , opts ) . then ( ( mongoose ) => {
28
+ return mongoose ;
29
+ } ) ;
30
+ }
21
31
try {
22
- await mongoose . connect ( uri ) ;
23
- isConnected = true ;
24
- } catch ( error ) {
25
- throw new Error ( "Failed to connect to MongoDB" ) ;
32
+ cached ! . conn = await cached ! . promise ;
33
+ } catch ( e ) {
34
+ if ( cached ) {
35
+ cached . promise = null ;
36
+ }
37
+ throw e ;
26
38
}
27
- } ;
39
+
40
+ return cached ?. conn ;
41
+ }
You can’t perform that action at this time.
0 commit comments