From afddf08d3ef6052b6dc5707f19a657ecc02b8f9d Mon Sep 17 00:00:00 2001 From: BGV <26331505+bgv2@users.noreply.github.com> Date: Sun, 30 Mar 2025 01:46:31 -0400 Subject: [PATCH] db progress --- React/src/pages/api/databaseStorage.ts | 40 +++++++++++++++++++++----- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/React/src/pages/api/databaseStorage.ts b/React/src/pages/api/databaseStorage.ts index a751f86..226625e 100644 --- a/React/src/pages/api/databaseStorage.ts +++ b/React/src/pages/api/databaseStorage.ts @@ -1,11 +1,37 @@ import { NextApiRequest, NextApiResponse } from "next"; -import { MongoClient } from "mongodb"; +import mongoose from "mongoose"; -export default function handler(req: NextApiRequest, res: NextApiResponse){ - if(req.method === 'POST') - const { codeword, contacts } = req.body; +const uri = process.env.MONGODB_URI || "mongodb://localhost:27017/mydatabase"; +const clientOptions = { serverApi: { version: "1" as const, strict: true, deprecationErrors: true } }; - try{ - - } +// Create a reusable connection function +async function connectToDatabase() { + if (mongoose.connection.readyState === 0) { + // Only connect if not already connected + await mongoose.connect(uri, clientOptions); + console.log("Connected to MongoDB!"); + } +} + +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + try { + // Ensure the database is connected + await connectToDatabase(); + + if (req.method === 'POST') { + const { codeword, contacts } = req.body; + + // Perform database operations here + console.log("Codeword:", codeword); + console.log("Contacts:", contacts); + + res.status(200).json({ success: true, message: "Data saved successfully!" }); + } else { + res.setHeader('Allow', ['POST']); + res.status(405).end(`Method ${req.method} Not Allowed`); + } + } catch (error) { + console.error("Error:", error); + res.status(500).json({ success: false, error: "Internal Server Error" }); + } } \ No newline at end of file