mirror of
https://gitlab.com/foxixus/neomovies.git
synced 2025-10-27 17:38:50 +05:00
31 lines
807 B
TypeScript
31 lines
807 B
TypeScript
|
|
import { MongoClient } from 'mongodb';
|
||
|
|
|
||
|
|
if (!process.env.MONGODB_URI) {
|
||
|
|
throw new Error('Please add your Mongo URI to .env');
|
||
|
|
}
|
||
|
|
|
||
|
|
const uri = process.env.MONGODB_URI;
|
||
|
|
let client: MongoClient;
|
||
|
|
let clientPromise: Promise<MongoClient>;
|
||
|
|
|
||
|
|
if (process.env.NODE_ENV === 'development') {
|
||
|
|
let globalWithMongo = global as typeof globalThis & {
|
||
|
|
_mongoClientPromise?: Promise<MongoClient>;
|
||
|
|
};
|
||
|
|
|
||
|
|
if (!globalWithMongo._mongoClientPromise) {
|
||
|
|
client = new MongoClient(uri);
|
||
|
|
globalWithMongo._mongoClientPromise = client.connect();
|
||
|
|
}
|
||
|
|
clientPromise = globalWithMongo._mongoClientPromise;
|
||
|
|
} else {
|
||
|
|
client = new MongoClient(uri);
|
||
|
|
clientPromise = client.connect();
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function connectToDatabase() {
|
||
|
|
const client = await clientPromise;
|
||
|
|
const db = client.db();
|
||
|
|
return { db, client };
|
||
|
|
}
|