From 527f955870be678c12ae38885d5f1768a7cfd195 Mon Sep 17 00:00:00 2001 From: Joseph J Helfenbein Date: Sat, 25 Jan 2025 05:01:15 -0500 Subject: [PATCH] include connectDB in route file --- src/app/api/webhook/route.js | 33 +++++++++++++++++++++++++++++ src/app/lib/connectDB.js | 40 ------------------------------------ 2 files changed, 33 insertions(+), 40 deletions(-) delete mode 100644 src/app/lib/connectDB.js diff --git a/src/app/api/webhook/route.js b/src/app/api/webhook/route.js index fdcec08..5af20f4 100644 --- a/src/app/api/webhook/route.js +++ b/src/app/api/webhook/route.js @@ -2,9 +2,42 @@ import { User } from '../../../models/User'; import { NextResponse } from 'next/server'; import { Webhook } from 'svix'; import connectDB from '../../lib/connectDB'; +import mongoose from "mongoose"; const CLERK_WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET; +const DATABASE_URL = process.env.MONGO_URI; + +let cached = global.mongoose; + +if (!cached) { + cached = global.mongoose = { conn: null, promise: null }; +} +async function connectDB() { + if (cached.conn) { + return cached.conn; + } + + if (!cached.promise) { + const opts = { + bufferCommands: false, + }; + + try { + cached.promise = mongoose.connect(DATABASE_URL, opts).then((mongoose) => { + console.log('MongoDB connected successfully'); + return mongoose; + }); + } catch (error) { + console.error('Error connecting to MongoDB:', error.message); + throw new Error('Error connecting to MongoDB'); + } + } + + cached.conn = await cached.promise; + return cached.conn; +} + export async function POST(req) { console.log('Received request:', req); diff --git a/src/app/lib/connectDB.js b/src/app/lib/connectDB.js deleted file mode 100644 index afef214..0000000 --- a/src/app/lib/connectDB.js +++ /dev/null @@ -1,40 +0,0 @@ -import mongoose from "mongoose"; - -const DATABASE_URL = process.env.MONGO_URI; - -if (!DATABASE_URL) { - throw new Error("Please define the DATABASE_URL environment variable inside .env.local"); -} - -let cached = global.mongoose; - -if (!cached) { - cached = global.mongoose = { conn: null, promise: null }; -} - -async function connectDB() { - if (cached.conn) { - return cached.conn; - } - - if (!cached.promise) { - const opts = { - bufferCommands: false, - }; - - try { - cached.promise = mongoose.connect(DATABASE_URL, opts).then((mongoose) => { - console.log('MongoDB connected successfully'); - return mongoose; - }); - } catch (error) { - console.error('Error connecting to MongoDB:', error.message); - throw new Error('Error connecting to MongoDB'); - } - } - - cached.conn = await cached.promise; - return cached.conn; -} - -export default connectDB;