svrjs-nextjs-website/lib/db.ts

25 lines
638 B
TypeScript
Raw Normal View History

2024-06-20 19:46:48 +02:00
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: Promise<MongoClient>;
if (process.env.NODE_ENV === "development") {
if (!(global as any)._mongoClientPromise) {
client = new MongoClient(uri!, options);
(global as any)._mongoClientPromise = client.connect();
}
clientPromise = (global as any)._mongoClientPromise;
} else {
client = new MongoClient(uri!, options);
clientPromise = client.connect();
}
export default clientPromise;