Skip to content

Commit

Permalink
Fix with-mongodb hot-reload issue and race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
ashconnell committed Oct 7, 2020
1 parent 4c38e3e commit f95f1a1
Showing 1 changed file with 18 additions and 17 deletions.
35 changes: 18 additions & 17 deletions examples/with-mongodb/util/mongodb.js
Expand Up @@ -3,9 +3,6 @@ import { MongoClient } from 'mongodb'
let uri = process.env.MONGODB_URI
let dbName = process.env.MONGODB_DB

let cachedClient = null
let cachedDb = null

if (!uri) {
throw new Error(
'Please define the MONGODB_URI environment variable inside .env.local'
Expand All @@ -18,20 +15,24 @@ if (!dbName) {
)
}

// global is used here to ensure the connection is cached across
// hot-reloads during development.
let cached = global.mongo
if (!cached) cached = global.mongo = {}

export async function connectToDatabase() {
if (cachedClient && cachedDb) {
return { client: cachedClient, db: cachedDb }
if (cached.connection) return cached.connection
if (!cached.promise) {
cached.promise = new Promise(async (resolve) => {
const client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
const db = await client.db(dbName)
cached.connection = { client, db }
resolve()
})
}

const client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})

const db = await client.db(dbName)

cachedClient = client
cachedDb = db

return { client, db }
await cached.promise
return cached.connection
}

0 comments on commit f95f1a1

Please sign in to comment.