From ef69a6c59891253469e1acb81725a725ff8750bc Mon Sep 17 00:00:00 2001 From: auggie2lbcf Date: Tue, 8 Apr 2025 13:45:31 -0500 Subject: [PATCH] updated handler --- src/pages/api/comments.ts | 58 +++++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 18 deletions(-) diff --git a/src/pages/api/comments.ts b/src/pages/api/comments.ts index 632f17d..4c2f5a8 100644 --- a/src/pages/api/comments.ts +++ b/src/pages/api/comments.ts @@ -1,32 +1,54 @@ import { NextApiRequest, NextApiResponse } from 'next'; import { MongoClient } from 'mongodb'; -const uri = process.env.MONGODB_URI || 'dontstealmyuri'; -const dbName = 'comments'; +const uri = process.env.MONGODB_URI || 'your-mongodb-uri'; +const dbName = 'confessions-of-grace'; const client = new MongoClient(uri); export default async function handler(req: NextApiRequest, res: NextApiResponse) { - if (req.method !== 'POST') { - return res.status(405).json({ message: 'Method not allowed' }); - } + if (req.method === 'POST') { + const { name, email, comment, postId } = req.body; - const { name, email, comment, postId } = req.body; + if (!name || !email || !comment || !postId) { + return res.status(400).json({ message: 'All fields are required' }); + } - if (!name || !email || !comment || !postId) { - return res.status(400).json({ message: 'All fields are required' }); - } + try { + if (!client.db(dbName)) await client.connect(); + const db = client.db(dbName); + const collection = db.collection('comments'); - try { - if (!client.db(dbName)) await client.connect(); - const db = client.db(dbName); - const collection = db.collection('comments'); + await collection.insertOne({ name, email, comment, postId, createdAt: new Date() }); - await collection.insertOne({ name, email, comment, postId, createdAt: new Date() }); + res.status(201).json({ message: 'Comment submitted successfully' }); + } catch (error) { + console.error(error); + res.status(500).json({ message: 'Internal server error' }); + } + } else if (req.method === 'GET') { + const { postId } = req.query; - res.status(201).json({ message: 'Comment submitted successfully' }); - } catch (error) { - console.error(error); - res.status(500).json({ message: 'Internal server error' }); + if (!postId) { + return res.status(400).json({ message: 'Post ID is required' }); + } + + try { + if (!client.db(dbName)) await client.connect(); + const db = client.db(dbName); + const collection = db.collection('comments'); + + const comments = await collection + .find({ postId }) + .sort({ createdAt: -1 }) + .toArray(); + + res.status(200).json(comments); + } catch (error) { + console.error(error); + res.status(500).json({ message: 'Internal server error' }); + } + } else { + res.status(405).json({ message: 'Method not allowed' }); } } \ No newline at end of file