npm workspace integration
This commit is contained in:
45
app/lib/dbConnect.js
Normal file
45
app/lib/dbConnect.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI
|
||||
|
||||
if (!MONGODB_URI) {
|
||||
throw new Error(
|
||||
'Please define the MONGODB_URI 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.mongoose
|
||||
|
||||
if (!cached) {
|
||||
cached = global.mongoose = { conn: null, promise: null }
|
||||
}
|
||||
|
||||
async function dbConnect () {
|
||||
if (cached.conn) {
|
||||
return cached.conn
|
||||
}
|
||||
|
||||
if (!cached.promise) {
|
||||
const opts = {
|
||||
// useNewUrlParser: true,
|
||||
// useUnifiedTopology: true,
|
||||
// bufferCommands: false,
|
||||
// bufferMaxEntries: 0,
|
||||
// useFindAndModify: true,
|
||||
// useCreateIndex: true
|
||||
}
|
||||
|
||||
cached.promise = mongoose.connect(MONGODB_URI, opts).then(mongoose => {
|
||||
return mongoose
|
||||
})
|
||||
}
|
||||
cached.conn = await cached.promise
|
||||
return cached.conn
|
||||
}
|
||||
|
||||
export default dbConnect
|
||||
@@ -1,29 +0,0 @@
|
||||
import { MongoClient } from 'mongodb'
|
||||
|
||||
const uri = process.env.MONGODB_URI
|
||||
const options = {}
|
||||
|
||||
let client
|
||||
let clientPromise
|
||||
|
||||
if (!process.env.MONGODB_URI) {
|
||||
throw new Error('Please add your Mongo URI to .env.local')
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
// In development mode, use a global variable so that the value
|
||||
// is preserved across module reloads caused by HMR (Hot Module Replacement).
|
||||
if (!global._mongoClientPromise) {
|
||||
client = new MongoClient(uri, options)
|
||||
global._mongoClientPromise = client.connect()
|
||||
}
|
||||
clientPromise = global._mongoClientPromise
|
||||
} else {
|
||||
// In production mode, it's best to not use a global variable.
|
||||
client = new MongoClient(uri, options)
|
||||
clientPromise = client.connect()
|
||||
}
|
||||
|
||||
// Export a module-scoped MongoClient promise. By doing this in a
|
||||
// separate module, the client can be shared across functions.
|
||||
export default clientPromise
|
||||
Reference in New Issue
Block a user