{"size": 960, "ext": "js", "max_stars_repo_path": "server/database/index.js", "max_stars_repo_name": "haskamp/nf-capstone", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/database/index.js", "max_issues_repo_name": "haskamp/nf-capstone", "max_issues_repo_issues_event_min_datetime": "2022-01-31T09:03:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T14:01:31.000Z", "max_forks_repo_path": "server/database/index.js", "max_forks_repo_name": "haskamp/nf-capstone", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 50, "max_forks_count": null, "avg_line_length": 22.3255813953, "max_line_length": 89, "alphanum_fraction": 0.7145833333}
import mongoose from "mongoose";

const MONGODB_URI = process.env.MONGODB_URI;
console.log(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 = { connection: null, promise: null };
	global.mongoose = cached;
}

async function dbConnect() {
	if (cached.connection) {
		console.log("connected to DB by cache");
		return cached.connection;
	}

	if (!cached.promise) {
		cached.promise = mongoose
			.connect(MONGODB_URI, {
				bufferCommands: false,
			})
			.then(mongoose => {
				console.log("connected to DB by connect");
				return mongoose;
			});
	}
	cached.connection = await cached.promise;
	return cached.connection;
}

export default dbConnect;
