aboutsummaryrefslogtreecommitdiff
path: root/lib/mongodb.js
diff options
context:
space:
mode:
authorFactiven <[email protected]>2023-04-11 23:23:29 +0700
committerFactiven <[email protected]>2023-04-11 23:23:29 +0700
commit1fcdd9f7d859b925bf92265f441655d5522e351c (patch)
tree86391522f6fcc70d105f7e796a9f91d132ee4a29 /lib/mongodb.js
parentInitial commit (diff)
downloadmoopa-1fcdd9f7d859b925bf92265f441655d5522e351c.tar.xz
moopa-1fcdd9f7d859b925bf92265f441655d5522e351c.zip
initial commit
Diffstat (limited to 'lib/mongodb.js')
-rw-r--r--lib/mongodb.js30
1 files changed, 30 insertions, 0 deletions
diff --git a/lib/mongodb.js b/lib/mongodb.js
new file mode 100644
index 0000000..dbbf0dc
--- /dev/null
+++ b/lib/mongodb.js
@@ -0,0 +1,30 @@
+// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
+import { MongoClient } from "mongodb";
+
+if (!process.env.MONGODB_URI) {
+ throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
+}
+
+const uri = process.env.MONGODB_URI;
+const options = {};
+
+let client;
+let clientPromise;
+
+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;