import { MongoClient } from 'mongodb'

const { MONGODB_URI, MONGODB_DB } = process.env

if (!MONGODB_URI) {
  throw new Error(
    'Please define the MONGODB_URI environment variable inside .env.local'
  )
}

if (!MONGODB_DB) {
  throw new Error(
    'Please define the MONGODB_DB environment variable inside .env.local'
  )
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
let cached = global.mongo

if (!cached) {
  cached = global.mongo = {}
}

export async function connectToDatabase() {
  if (cached.conn) {
    return cached.conn
  }

  if (!cached.promise) {
    const conn = {}

    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }

    cached.promise = MongoClient.connect(MONGODB_URI, opts)
      .then((client) => {
        conn.client = client

        return client.db(MONGODB_DB)
      })
      .then((db) => {
        conn.db = db

        cached.conn = conn
      })
  }

  await cached.promise

  return cached.conn
}

@@ -566,16 +566,43 @@
 ongo = %7B
+ conn: null, promise: null 
 %7D%0A%7D%0A%0Aexp
@@ -720,29 +720,8 @@
 ) %7B%0A
-    const conn = %7B%7D%0A%0A
     
@@ -862,23 +862,16 @@
 I, opts)
-%0A      
 .then((c
@@ -892,31 +892,32 @@
     
-  conn.client =
+return %7B%0A       
  client
-%0A
+,
 %0A   
@@ -921,22 +921,19 @@
         
-return
+db:
  client.
@@ -946,24 +946,25 @@
 GODB_DB)
+,
 %0A      %7D
 )%0A      
@@ -959,96 +959,35 @@
    %7D
-)%0A 
+%0A
     
- .then((db) =%3E %7B%0A        conn.db = db%0A%0A        cached.conn = conn%0A      %7D)%0A  %7D%0A%0A 
+%7D)%0A  %7D%0A  cached.conn =
  awa
@@ -1004,17 +1004,16 @@
 promise%0A
-%0A
   return

Update with-mongodb to be TypeScript-friendly (#19383)