Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"test": "jest"
},
"dependencies": {
"mongodb": "^3.6.5",
"next": "10.0.9",
"react": "17.0.1",
"react-dom": "17.0.1"
Expand Down
48 changes: 48 additions & 0 deletions util/mongodb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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 = { conn: null, promise: null };
}

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

if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};

cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
return {
client,
db: client.db(MONGODB_DB),
};
});
}
cached.conn = await cached.promise;
return cached.conn;
}