Repository: kalviumcommunity/s84_what_if
Pull request #14: Update-delete
Author: login: mannat-07
Labels: name: Review effort 3/5
Created: 2025-04-03T05:06:49Z | Merged: 2025-04-03T05:08:44Z

### **PR Type**
Enhancement, Bug fix


___

### **Description**
- Added `DELETE` and `PUT` endpoints for managing posts in `postRoutes.js`.

- Created a new Mongoose schema `postSchema` for posts.

- Updated frontend components (`Explore`, `Home`, `Card`) to handle post updates and deletions.

- Changed port configurations in `.env` files for both backend and frontend.


___



### **Changes walkthrough** 📝
<table><thead><tr><th></th><th align="left">Relevant files</th></tr></thead><tbody><tr><td><strong>Enhancement</strong></td><td><details><summary>6 files</summary><table>
<tr>
  <td><strong>postSchema.js</strong><dd><code>Added Mongoose schema for posts</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td>
  <td><a href="https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-4d3d885dbb140ec78be4994585d9b6d90e9174a14b30748c76b7125a30100612">+9/-0</a>&nbsp; &nbsp; &nbsp; </td>

</tr>

<tr>
  <td><strong>postRoutes.js</strong><dd><code>Added `DELETE` and `PUT` endpoints for posts</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td>
  <td><a href="https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-55af02ba3d5fd23e63cf4a91dcad13905e86042c2f110d3a5d5ae9c236e80b70">+46/-0</a>&nbsp; &nbsp; </td>

</tr>

<tr>
  <td><strong>routes.js</strong><dd><code>Integrated post schema into main routes</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td>
  <td><a href="https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-ceaf33dac5fa3b693cdd5f31f6f06b5fedd96041d652b1973eb64378a17c5930">+29/-23</a>&nbsp; </td>

</tr>

<tr>
  <td><strong>Explore.jsx</strong><dd><code>Added post update and delete handlers</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td>
  <td><a href="https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-441c1c1866b946bfecad7cabb26f044585afcd14f3969b625f4f97c41444062c">+13/-3</a>&nbsp; &nbsp; </td>

</tr>

<tr>
  <td><strong>Home.jsx</strong><dd><code>Enhanced post update and delete functionality</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td>
  <td><a href="https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-22f85429a85a72952f19eb6837f16c387120f80530ae9128853dc6773ee0fb0f">+33/-32</a>&nbsp; </td>

</tr>

<tr>
  <td><strong>Card.jsx</strong><dd><code>Added delete and update logic for posts</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td>
  <td><a href="https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-b48e4321d55fe4e1241583f838cfb9690dda5cae64d4f6c41297a81ee55081a1">+43/-9</a>&nbsp; &nbsp; </td>

</tr>
</table></details></td></tr><tr><td><strong>Configuration changes</strong></td><td><details><summary>2 files</summary><table>
<tr>
  <td><strong>.env</strong><dd><code>Updated backend port configuration</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td>
  <td><a href="https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-705192abd89a5a515fe35eaf13ed6161aee15f3aa22dbd128a0747d9122deef9">+1/-1</a>&nbsp; &nbsp; &nbsp; </td>

</tr>

<tr>
  <td><strong>.env</strong><dd><code>Updated frontend port configuration</code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </dd></td>
  <td><a href="https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-20aafeb3e2b2e5f6cfbb826223060a4b226c57f4f5f6a693321cb8cda382ef83">+1/-1</a>&nbsp; &nbsp; &nbsp; </td>

</tr>
</table></details></td></tr></tr></tbody></table>

___

> <details> <summary>  Need help?</summary><li>Type <code>/help how to ...</code> in the comments thread for any questions about Qodo Merge usage.</li><li>Check out the <a href="https://qodo-merge-docs.qodo.ai/usage-guide/">documentation</a> for more information.</li></details>


Diff:
diff --git a/Backend/.env b/Backend/.env
index 7208b13..9241ea6 100644
--- a/Backend/.env
+++ b/Backend/.env
@@ -1,3 +1,3 @@
-Port = 4000
+Port = 8000
 
 MONGO_URI = mongodb+srv://mannatgarg2006:gargi167@cluster0.je1dn.mongodb.net/ASAP?retryWrites=true&w=majority&appName=Cluster0
\ No newline at end of file
diff --git a/Backend/Models/postSchema.js b/Backend/Models/postSchema.js
new file mode 100644
index 0000000..51f6d6e
--- /dev/null
+++ b/Backend/Models/postSchema.js
@@ -0,0 +1,9 @@
+const mongoose = require('mongoose');
+
+const postSchema = new mongoose.Schema({
+    question: { type: String, required: true },
+    answer: { type: String, required: true },
+    category: { type: String, required: true },
+});
+
+module.exports = mongoose.model('Post', postSchema);
\ No newline at end of file
diff --git a/Backend/Routes/postRoutes.js b/Backend/Routes/postRoutes.js
index 8c55962..d45bc9b 100644
--- a/Backend/Routes/postRoutes.js
+++ b/Backend/Routes/postRoutes.js
@@ -34,4 +34,50 @@ router.get("/", async (req, res) => {
   }
 });
 
+// DELETE /posts/:id - Delete a post by ID
+router.delete("/:id", async (req, res) => {
+  try {
+    const { id } = req.params;
+    if (!id) {
+      return res.status(400).json({ message: "Post ID is required", success: false });
+    }
+
+    const deletedPost = await Post.findByIdAndDelete(id);
+    if (!deletedPost) {
+      return res.status(404).json({ message: "Post not found", success: false });
+    }
+    res.status(200).json({ message: "Post deleted successfully", success: true });
+  } catch (err) {
+    console.error("Error deleting post:", err);
+    res.status(500).json({ error: "Server error", success: false });
+  }
+});
+
+// PUT /posts/:id - Update a post by ID
+router.put("/:id", async (req, res) => {
+  try {
+    const { question, answer, category } = req.body;
+
+    // Validate input
+    if (!question || !answer || !category) {
+      return res.status(400).json({ error: "Missing required fields", success: false });
+    }
+
+    const updatedPost = await Post.findByIdAndUpdate(
+      req.params.id,
+      { question, answer, category },
+      { new: true, runValidators: true }
+    );
+
+    if (!updatedPost) {
+      return res.status(404).json({ message: "Post not found", success: false });
+    }
+
+    res.status(200).json({ message: "Post updated successfully", post: updatedPost, success: true });
+  } catch (err) {
+    console.error("Error updating post:", err);
+    res.status(500).json({ error: "Server error", success: false });
+  }
+});
+
 module.exports = router;
\ No newline at end of file
diff --git a/Backend/Routes/routes.js b/Backend/Routes/routes.js
index 3657cf3..16d69dd 100644
--- a/Backend/Routes/routes.js
+++ b/Backend/Routes/routes.js
@@ -1,8 +1,9 @@
-const express = require('express')
-const router = express.Router()
-router.use(express.json())
+const express = require('express');
+const router = express.Router();
+router.use(express.json());
 
 const User = require('../Models/schema');
+const Post = require('../Models/postSchema'); 
 
 router.get('/', async (req, res)=>{
     try{
@@ -29,27 +30,32 @@ router.post('/', async (req, res)=>{
     }
 })
 
-router.put('/:id', async (req, res)=>{
-    try{
-        const {id} = req.params;
-        const {username, animalIdentity, password, joinDate,postCount,reputation } = req.body;
-        const updateuser = await User.findByIdAndUpdate(id ,{username, animalIdentity, password, joinDate, postCount, reputation},{new : true});
-        res.status(200).json({ msg : "Data updated successfully", success : true, user: updateuser});
-    }
-    catch(err){
-        res.status(500).json({ error: 'Server error', success: false });
+router.delete('/posts/:id', async (req, res) => {
+    try {
+        const deletedPost = await Post.findByIdAndDelete(req.params.id);
+        if (!deletedPost) {
+            return res.status(404).json({ message: 'Post not found' });
+        }
+        res.json({ message: 'Post deleted successfully' });
+    } catch (error) {
+        res.status(500).json({ message: error.message });
     }
-})
+});
 
-router.delete('/:id', async (req, res)=>{
-    try{
-        const id = req.params.id;
-        const data= await User.findByIdAndDelete(id);
-        res.status(200).json({ msg : "Data deleted", success : true});
-    }
-    catch(err){
-        res.status(500).json({ error: 'Server error', success: false });
+router.put('/posts/:id', async (req, res) => {
+    try {
+        const updatedPost = await Post.findByIdAndUpdate(
+            req.params.id,
+            req.body,
+            { new: true, runValidators: true }
+        );
+        if (!updatedPost) {
+            return res.status(404).json({ message: 'Post not found' });
+        }
+        res.json({ post: updatedPost, message: 'Post updated successfully' });
+    } catch (error) {
+        res.status(400).json({ message: error.message });
     }
-})
+});
 
-module.exports = router
\ No newline at end of file
+module.exports = router;
\ No newline at end of file
diff --git a/Frontend/.env b/Frontend/.env
index da40bea..e65bf76 100644
--- a/Frontend/.env
+++ b/Frontend/.env
@@ -1 +1 @@
-VITE_PORT = 4000
\ No newline at end of file
+VITE_PORT = 8000
\ No newline at end of file
diff --git a/Frontend/src/Pages/Explore.jsx b/Frontend/src/Pages/Explore.jsx
index 6fb15ed..0ee22c1 100644
--- a/Frontend/src/Pages/Explore.jsx
+++ b/Frontend/src/Pages/Explore.jsx
@@ -4,7 +4,6 @@ import "./Explore.css";
 
 const port = import.meta.env.VITE_PORT;
 
-
 export default function Explore() {
   const [posts, setPosts] = useState([]);
 
@@ -26,17 +25,28 @@ export default function Explore() {
     fetchPosts();
   }, []);
 
+  const handleDelete = (id) => {
+    setPosts(posts.filter((post) => post._id !== id));
+  };
+
+  const handleUpdate = (id, updatedPost) => {
+    setPosts(posts.map((post) => (post._id === id ? { ...post, ...updatedPost } : post)));
+  };
+
   return (
     <div className="explore-page">
       <h1>Explore All Ideas</h1>
       <div className="post-list">
         {posts.length > 0 ? (
-          posts.map((post, index) => (
+          posts.map((post) => (
             <Card
-              key={index}
+              key={post._id}
+              id={post._id}
               question={post.question}
               answer={post.answer}
               category={post.category}
+              onDelete={handleDelete}
+              onUpdate={handleUpdate}
             />
           ))
         ) : (
diff --git a/Frontend/src/Pages/Home.jsx b/Frontend/src/Pages/Home.jsx
index 14076ac..5cea089 100644
--- a/Frontend/src/Pages/Home.jsx
+++ b/Frontend/src/Pages/Home.jsx
@@ -38,45 +38,46 @@ const Home = () => {
 
   const handleDeletePost = async (id) => {
     try {
-      const response = await fetch(`http://localhost:${port}/posts/${id}`, {
-        method: 'DELETE',
-      });
-      
-      if (!response.ok) {
-        throw new Error(`HTTP error! status: ${response.status}`);
-      }
-      
-      setPosts(posts.filter(post => post._id !== id));
-      setSuccessMessage("Post deleted successfully!");
-      setTimeout(() => setSuccessMessage(""), 3000);
+        const response = await fetch(`http://localhost:${port}/posts/${id}`, {
+            method: 'DELETE',
+        });
+
+        if (!response.ok) {
+            throw new Error(`HTTP error! status: ${response.status}`);
+        }
+
+        setPosts(posts.filter(post => post._id !== id));
+        setSuccessMessage("Post deleted successfully!");
+        setTimeout(() => setSuccessMessage(""), 3000);
     } catch (error) {
-      console.error("Error deleting post:", error);
+        console.error("Error deleting post:", error);
     }
-  };
+};
 
   const handleUpdatePost = async (id, updatedPost) => {
     try {
-      const response = await fetch(`http://localhost:${port}/posts/${id}`, {
-        method: 'PUT',
-        headers: {
-          'Content-Type': 'application/json',
-        },
-        body: JSON.stringify(updatedPost),
-      });
-      
-      if (!response.ok) {
-        throw new Error(`HTTP error! status: ${response.status}`);
-      }
-      
-      setPosts(posts.map(post => 
-        post._id === id ? { ...post, ...updatedPost } : post
-      ));
-      setSuccessMessage("Post updated successfully!");
-      setTimeout(() => setSuccessMessage(""), 3000);
+        const response = await fetch(`http://localhost:${port}/posts/${id}`, {
+            method: 'PUT',
+            headers: {
+                'Content-Type': 'application/json',
+            },
+            body: JSON.stringify(updatedPost),
+        });
+
+        if (!response.ok) {
+            throw new Error(`HTTP error! status: ${response.status}`);
+        }
+
+        const data = await response.json();
+        setPosts(posts.map(post =>
+            post._id === id ? { ...post, ...data.post } : post
+        ));
+        setSuccessMessage("Post updated successfully!");
+        setTimeout(() => setSuccessMessage(""), 3000);
     } catch (error) {
-      console.error("Error updating post:", error);
+        console.error("Error updating post:", error);
     }
-  };
+};
 
   return (
     <div className="home">
diff --git a/Frontend/src/component/Card.jsx b/Frontend/src/component/Card.jsx
index c56d17c..3a6553e 100644
--- a/Frontend/src/component/Card.jsx
+++ b/Frontend/src/component/Card.jsx
@@ -2,6 +2,8 @@ import React, { useState } from 'react';
 import './Card.css';
 import { FiEdit, FiTrash2 } from 'react-icons/fi';
 
+const port = import.meta.env.VITE_PORT;
+
 export default function Card({ 
   question, 
   answer, 
@@ -15,13 +17,46 @@ export default function Card({
   const [editedAnswer, setEditedAnswer] = useState(answer);
   const [editedCategory, setEditedCategory] = useState(category);
 
-  const handleUpdate = () => {
-    onUpdate(id, {
-      question: editedQuestion,
-      answer: editedAnswer,
-      category: editedCategory
-    });
-    setIsEditing(false);
+  const handleUpdate = async () => {
+    try {
+      const response = await fetch(`http://localhost:${port}/posts/${id}`, {
+        method: 'PUT',
+        headers: {
+          'Content-Type': 'application/json',
+        },
+        body: JSON.stringify({
+          question: editedQuestion,
+          answer: editedAnswer,
+          category: editedCategory,
+        }),
+      });
+
+      if (!response.ok) {
+        throw new Error(`HTTP error! status: ${response.status}`);
+      }
+
+      const data = await response.json();
+      onUpdate(id, data.post);
+      setIsEditing(false);
+    } catch (error) {
+      console.error('Error updating post:', error);
+    }
+  };
+
+  const handleDelete = async () => {
+    try {
+      const response = await fetch(`http://localhost:${port}/posts/${id}`, {
+        method: 'DELETE',
+      });
+
+      if (!response.ok) {
+        throw new Error(`HTTP error! status: ${response.status}`);
+      }
+
+      onDelete(id);
+    } catch (error) {
+      console.error('Error deleting post:', error);
+    }
   };
 
   const handleCancel = () => {
@@ -44,13 +79,12 @@ export default function Card({
             <img src='https://img.icons8.com/ios_filled/512/FFFFFF/edit.png' style={{height : "20px", width : "20px"}}/>
           </button>
           <button 
-            onClick={() => onDelete(id)} 
+            onClick={handleDelete} 
             className="card-action-btn"
             aria-label="Delete card"
           >
             <FiTrash2 className="card-icon" />
             <img src='https://img.icons8.com/ios11/600/FFFFFF/filled-trash.png' style={{height : "20px", width : "20px"}}/>
-            
           </button>
         </div>
       )}


Reviews:
user: login: qodo-code-review[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T05:07:57Z
user: login: qodo-code-review[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T05:08:15Z

Review comments:
diff_hunk: @@ -29,27 +30,32 @@ router.post('/', async (req, res)=>{
     }
 })
 
-router.put('/:id', async (req, res)=>{
-    try{
-        const {id} = req.params;
-        const {username, animalIdentity, password, joinDate,postCount,reputation } = req.body;
-        const updateuser = await User.findByIdAndUpdate(id ,{username, animalIdentity, password, joinDate, postCount, reputation},{new : true});
-        res.status(200).json({ msg : "Data updated successfully", success : true, user: updateuser});
-    }
-    catch(err){
-        res.status(500).json({ error: 'Server error', success: false });
+router.delete('/posts/:id', async (req, res) => {
+    try {
+        const deletedPost = await Post.findByIdAndDelete(req.params.id);
+        if (!deletedPost) {
+            return res.status(404).json({ message: 'Post not found' });
+        }
+        res.json({ message: 'Post deleted successfully' });
+    } catch (error) {
+        res.status(500).json({ message: error.message });
     }
-})
+});
path: Backend/Routes/routes.js
user: login: qodo-code-review[bot]
body: **Suggestion:** Standardize API response format
```suggestion
router.delete('/posts/:id', async (req, res) => {
    try {
        const deletedPost = await Post.findByIdAndDelete(req.params.id);
        if (!deletedPost) {
            return res.status(404).json({ message: 'Post not found', success: false });
        }
        res.json({ message: 'Post deleted successfully', success: true });
    } catch (error) {
        res.status(500).json({ message: error.message, success: false });
    }
});
```

<!-- manually_applied -->
created_at: 2025-04-03T05:07:57Z
author_association: CONTRIBUTOR
diff_hunk: @@ -38,45 +38,46 @@ const Home = () => {
 
   const handleDeletePost = async (id) => {
     try {
-      const response = await fetch(`http://localhost:${port}/posts/${id}`, {
-        method: 'DELETE',
-      });
-      
-      if (!response.ok) {
-        throw new Error(`HTTP error! status: ${response.status}`);
-      }
-      
-      setPosts(posts.filter(post => post._id !== id));
-      setSuccessMessage("Post deleted successfully!");
-      setTimeout(() => setSuccessMessage(""), 3000);
+        const response = await fetch(`http://localhost:${port}/posts/${id}`, {
+            method: 'DELETE',
+        });
+
+        if (!response.ok) {
+            throw new Error(`HTTP error! status: ${response.status}`);
+        }
+
+        setPosts(posts.filter(post => post._id !== id));
+        setSuccessMessage("Post deleted successfully!");
+        setTimeout(() => setSuccessMessage(""), 3000);
     } catch (error) {
-      console.error("Error deleting post:", error);
+        console.error("Error deleting post:", error);
     }
-  };
+};
 
   const handleUpdatePost = async (id, updatedPost) => {
     try {
-      const response = await fetch(`http://localhost:${port}/posts/${id}`, {
-        method: 'PUT',
-        headers: {
-          'Content-Type': 'application/json',
-        },
-        body: JSON.stringify(updatedPost),
-      });
-      
-      if (!response.ok) {
-        throw new Error(`HTTP error! status: ${response.status}`);
-      }
-      
-      setPosts(posts.map(post => 
-        post._id === id ? { ...post, ...updatedPost } : post
-      ));
-      setSuccessMessage("Post updated successfully!");
-      setTimeout(() => setSuccessMessage(""), 3000);
+        const response = await fetch(`http://localhost:${port}/posts/${id}`, {
+            method: 'PUT',
+            headers: {
+                'Content-Type': 'application/json',
+            },
+            body: JSON.stringify(updatedPost),
+        });
+
+        if (!response.ok) {
+            throw new Error(`HTTP error! status: ${response.status}`);
+        }
+
+        const data = await response.json();
+        setPosts(posts.map(post =>
+            post._id === id ? { ...post, ...data.post } : post
+        ));
path: Frontend/src/Pages/Home.jsx
user: login: qodo-code-review[bot]
body: **Suggestion:** Add null check
```suggestion
        const data = await response.json();
        if (data && data.post) {
            setPosts(posts.map(post =>
                post._id === id ? { ...post, ...data.post } : post
            ));
        }
```

<!-- manually_applied -->
created_at: 2025-04-03T05:08:15Z
author_association: CONTRIBUTOR

PR comments:
user: login: mannat-07
created_at: 2025-04-03T05:07:01Z
body: @CodiumAI-Agent /review
author_association: COLLABORATOR
user: login: qodo-code-review[bot]
created_at: 2025-04-03T05:07:10Z
body: _Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account [here](https://app.qodo.ai/qodo-merge)._

## PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

<table>
<tr><td>⏱️&nbsp;<strong>Estimated effort to review</strong>: 3 🔵🔵🔵⚪⚪</td></tr>
<tr><td>🧪&nbsp;<strong>No relevant tests</strong></td></tr>
<tr><td>🔒&nbsp;<strong>No security concerns identified</strong></td></tr>
<tr><td>⚡&nbsp;<strong>Recommended focus areas for review</strong><br><br>

<details><summary><a href='https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-ceaf33dac5fa3b693cdd5f31f6f06b5fedd96041d652b1973eb64378a17c5930R33-R59'><strong>Duplicate Routes</strong></a>

The PR adds duplicate DELETE and PUT routes for posts in both postRoutes.js and routes.js files. This creates confusion and potential conflicts in handling post operations.
</summary>

```javascript
router.delete('/posts/:id', async (req, res) => {
    try {
        const deletedPost = await Post.findByIdAndDelete(req.params.id);
        if (!deletedPost) {
            return res.status(404).json({ message: 'Post not found' });
        }
        res.json({ message: 'Post deleted successfully' });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

router.put('/posts/:id', async (req, res) => {
    try {
        const updatedPost = await Post.findByIdAndUpdate(
            req.params.id,
            req.body,
            { new: true, runValidators: true }
        );
        if (!updatedPost) {
            return res.status(404).json({ message: 'Post not found' });
        }
        res.json({ post: updatedPost, message: 'Post updated successfully' });
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
});
```

</details>

<details><summary><a href='https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-20aafeb3e2b2e5f6cfbb826223060a4b226c57f4f5f6a693321cb8cda382ef83R1-R2'><strong>Conflicting Ports</strong></a>

The .env file contains two conflicting VITE_PORT values (8000 and 4000) on consecutive lines, which will cause unpredictable behavior in the application.
</summary>

```txt
VITE_PORT = 8000
```

</details>

<details><summary><a href='https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-b48e4321d55fe4e1241583f838cfb9690dda5cae64d4f6c41297a81ee55081a1R78-R88'><strong>Duplicate Icons</strong></a>

The Card component renders both React icons (FiEdit, FiTrash2) and img elements for the same actions, creating visual duplication in the UI.
</summary>

```jsx
  <FiEdit className="card-icon" />
  <img src='https://img.icons8.com/ios_filled/512/FFFFFF/edit.png' style={{height : "20px", width : "20px"}}/>
</button>
<button 
  onClick={handleDelete} 
  className="card-action-btn"
  aria-label="Delete card"
>
  <FiTrash2 className="card-icon" />
  <img src='https://img.icons8.com/ios11/600/FFFFFF/filled-trash.png' style={{height : "20px", width : "20px"}}/>
</button>
```

</details>

</td></tr>
</table>

author_association: CONTRIBUTOR
user: login: qodo-code-review[bot]
created_at: 2025-04-03T05:07:29Z
body: _Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account [here](https://app.qodo.ai/qodo-merge)._

## PR Code Suggestions ✨

<!-- 2966b25 -->

Explore these optional code suggestions:

<table><thead><tr><td><strong>Category</strong></td><td align=left><strong>Suggestion&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </strong></td><td align=center><strong>Impact</strong></td></tr><tbody><tr><td rowspan=3>Possible issue</td>
<td>



<details><summary>Remove duplicate environment variable</summary>

___


**There are two conflicting VITE_PORT values defined in the .env file. This will <br>cause confusion as only the last value (4000) will be used, but the PR is trying <br>to update the port to 8000.**

[Frontend/.env [1-2]](https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-20aafeb3e2b2e5f6cfbb826223060a4b226c57f4f5f6a693321cb8cda382ef83R1-R2)

```diff
 VITE_PORT = 8000
-VITE_PORT = 4000
```


`[To ensure code accuracy, apply this suggestion manually]`

<details><summary>Suggestion importance[1-10]: 9</summary>

__

Why: This suggestion fixes a critical configuration issue where two conflicting port values are defined. Only the last value (4000) would be used, contradicting the intended port change to 8000, which could cause connection problems.


</details></details></td><td align=center>High

</td></tr><tr><td>



<details><summary>✅ 
Standardize API response format
</summary>

___


**This route duplicates functionality already implemented in postRoutes.js and <br>uses a different response format. This creates inconsistency in the API <br>responses, as the postRoutes.js version includes a 'success' field while this <br>one doesn't.**

[Backend/Routes/routes.js [33-43]](https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-ceaf33dac5fa3b693cdd5f31f6f06b5fedd96041d652b1973eb64378a17c5930R33-R43)

```diff
 router.delete('/posts/:id', async (req, res) => {
     try {
         const deletedPost = await Post.findByIdAndDelete(req.params.id);
         if (!deletedPost) {
-            return res.status(404).json({ message: 'Post not found' });
+            return res.status(404).json({ message: 'Post not found', success: false });
         }
-        res.json({ message: 'Post deleted successfully' });
+        res.json({ message: 'Post deleted successfully', success: true });
     } catch (error) {
-        res.status(500).json({ message: error.message });
+        res.status(500).json({ message: error.message, success: false });
     }
 });
```

`[Suggestion has been applied]`

<details><summary>Suggestion importance[1-10]: 8</summary>

__

Why: This suggestion addresses an important consistency issue in the API. The duplicate route in routes.js uses a different response format than the one in postRoutes.js, which would make client-side handling more complex and error-prone.


</details></details></td><td align=center>Medium

</td></tr><tr><td>



<details><summary>✅ 
Add null check
</summary>

___


**The code is updating posts based on the response from the server, but it's not <br>checking if data.post exists before using it. If the server response format <br>changes or if data.post is undefined, this could cause a runtime error.**

[Frontend/src/Pages/Home.jsx [71-74]](https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-22f85429a85a72952f19eb6837f16c387120f80530ae9128853dc6773ee0fb0fR71-R74)

```diff
 const data = await response.json();
-setPosts(posts.map(post =>
-    post._id === id ? { ...post, ...data.post } : post
-));
+if (data && data.post) {
+    setPosts(posts.map(post =>
+        post._id === id ? { ...post, ...data.post } : post
+    ));
+}
```

`[Suggestion has been applied]`

<details><summary>Suggestion importance[1-10]: 7</summary>

__

Why: This suggestion addresses a potential runtime error by adding a null check before using data.post. This is a good defensive programming practice that improves code robustness and prevents crashes if the server response format changes.


</details></details></td><td align=center>Medium

</td></tr><tr><td rowspan=1>Possible issue</td>
<td>



<details><summary>Add input validation</summary>

___


**This route duplicates functionality already implemented in postRoutes.js but <br>with different input validation. The postRoutes.js version validates required <br>fields, while this one passes req.body directly to findByIdAndUpdate, which <br>could allow unwanted fields to be updated. Standardize the validation approach.**

[Backend/Routes/routes.js [45-59]](https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-ceaf33dac5fa3b693cdd5f31f6f06b5fedd96041d652b1973eb64378a17c5930R45-R59)

```diff
 router.put('/posts/:id', async (req, res) => {
   try {
+      const { question, answer, category } = req.body;
+      
+      // Validate input
+      if (!question || !answer || !category) {
+          return res.status(400).json({ message: 'Missing required fields', success: false });
+      }
+      
       const updatedPost = await Post.findByIdAndUpdate(
           req.params.id,
-          req.body,
+          { question, answer, category },
           { new: true, runValidators: true }
       );
       if (!updatedPost) {
-          return res.status(404).json({ message: 'Post not found' });
+          return res.status(404).json({ message: 'Post not found', success: false });
       }
-      res.json({ post: updatedPost, message: 'Post updated successfully' });
+      res.json({ post: updatedPost, message: 'Post updated successfully', success: true });
   } catch (error) {
-      res.status(400).json({ message: error.message });
+      res.status(400).json({ message: error.message, success: false });
   }
 });
```

- [ ] **Apply this suggestion** <!-- /improve --apply_suggestion=3 -->

<details><summary>Suggestion importance[1-10]: 9</summary>

__

Why: The suggestion addresses a critical security issue by adding proper input validation to prevent unwanted fields from being updated. This standardizes validation across routes and prevents potential data integrity issues.


</details></details></td><td align=center>High

</td></tr><tr><td rowspan=2>General</td>
<td>



<details><summary>Remove duplicate API logic</summary>

___


**The Card component implements its own update logic that duplicates the <br>functionality in the parent component. This creates inconsistency as both the <br>Card component and its parent handle the same API calls. Consider using only the <br>onUpdate prop passed from the parent component instead of implementing a <br>separate fetch call.**

[Frontend/src/component/Card.jsx [20-44]](https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-b48e4321d55fe4e1241583f838cfb9690dda5cae64d4f6c41297a81ee55081a1R20-R44)

```diff
-const handleUpdate = async () => {
-  try {
-    const response = await fetch(`http://localhost:${port}/posts/${id}`, {
-      method: 'PUT',
-      headers: {
-        'Content-Type': 'application/json',
-      },
-      body: JSON.stringify({
-        question: editedQuestion,
-        answer: editedAnswer,
-        category: editedCategory,
-      }),
-    });
-
-    if (!response.ok) {
-      throw new Error(`HTTP error! status: ${response.status}`);
-    }
-
-    const data = await response.json();
-    onUpdate(id, data.post);
-    setIsEditing(false);
-  } catch (error) {
-    console.error('Error updating post:', error);
-  }
+const handleUpdate = () => {
+  onUpdate(id, {
+    question: editedQuestion,
+    answer: editedAnswer,
+    category: editedCategory,
+  });
+  setIsEditing(false);
 };
```

- [ ] **Apply this suggestion** <!-- /improve --apply_suggestion=4 -->

<details><summary>Suggestion importance[1-10]: 8</summary>

__

Why: The suggestion correctly identifies duplicate API logic between the Card component and parent components. Removing this duplication improves maintainability and prevents potential inconsistencies in state management and error handling.


</details></details></td><td align=center>Medium

</td></tr><tr><td>



<details><summary>Simplify delete operation</summary>

___


**Similar to the update functionality, the Card component implements its own <br>delete logic that duplicates the functionality in the parent component. This <br>creates inconsistency in error handling and state management. Use the onDelete <br>prop passed from the parent component instead.**

[Frontend/src/component/Card.jsx [46-60]](https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-b48e4321d55fe4e1241583f838cfb9690dda5cae64d4f6c41297a81ee55081a1R46-R60)

```diff
-const handleDelete = async () => {
-  try {
-    const response = await fetch(`http://localhost:${port}/posts/${id}`, {
-      method: 'DELETE',
-    });
-
-    if (!response.ok) {
-      throw new Error(`HTTP error! status: ${response.status}`);
-    }
-
-    onDelete(id);
-  } catch (error) {
-    console.error('Error deleting post:', error);
-  }
+const handleDelete = () => {
+  onDelete(id);
 };
```

- [ ] **Apply this suggestion** <!-- /improve --apply_suggestion=5 -->

<details><summary>Suggestion importance[1-10]: 8</summary>

__

Why: This suggestion correctly identifies duplicate delete functionality that should be handled by the parent component. Removing this duplication prevents inconsistencies and simplifies the component's responsibility, improving code maintainability.


</details></details></td><td align=center>Medium

</td></tr>
<tr><td align="center" colspan="2">

- [ ] More <!-- /improve --more_suggestions=true -->

</td><td></td></tr></tbody></table>


author_association: CONTRIBUTOR
user: login: QodoAI-Agent
created_at: 2025-04-03T05:07:34Z
body: ## PR Reviewer Guide 🔍

#### (Review updated until commit https://github.com/kalviumcommunity/s84_what_if/commit/2966b25b6f83cc4f5102067de6f9c0c1d9d6515a)


Here are some key observations to aid the review process:

<table>
<tr><td>⏱️&nbsp;<strong>Estimated effort to review</strong>: 3 🔵🔵🔵⚪⚪</td></tr>
<tr><td>🧪&nbsp;<strong>No relevant tests</strong></td></tr>
<tr><td>🔒&nbsp;<strong>Security concerns</strong><br><br>

<strong>Sensitive Data Exposure:</strong><br> The hardcoded database connection string with credentials may expose sensitive information. It is recommended to use secure secret management.</td></tr>
<tr><td>⚡&nbsp;<strong>Recommended focus areas for review</strong><br><br>

<details><summary><a href='https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-ceaf33dac5fa3b693cdd5f31f6f06b5fedd96041d652b1973eb64378a17c5930R33-R59'><strong>Redundant Endpoints</strong></a>

Similar post deletion and update endpoints are defined in multiple route files. Consider consolidating these endpoints to avoid redundancy and ensure uniform error handling.
</summary>

```javascript
router.delete('/posts/:id', async (req, res) => {
    try {
        const deletedPost = await Post.findByIdAndDelete(req.params.id);
        if (!deletedPost) {
            return res.status(404).json({ message: 'Post not found' });
        }
        res.json({ message: 'Post deleted successfully' });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

router.put('/posts/:id', async (req, res) => {
    try {
        const updatedPost = await Post.findByIdAndUpdate(
            req.params.id,
            req.body,
            { new: true, runValidators: true }
        );
        if (!updatedPost) {
            return res.status(404).json({ message: 'Post not found' });
        }
        res.json({ post: updatedPost, message: 'Post updated successfully' });
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
});
```

</details>

<details><summary><a href='https://github.com/kalviumcommunity/s84_what_if/pull/14/files#diff-705192abd89a5a515fe35eaf13ed6161aee15f3aa22dbd128a0747d9122deef9R1-R3'><strong>Sensitive Data Exposure</strong></a>

The MONGO_URI contains hardcoded credentials. Ensure sensitive information is managed securely using proper secret management strategies.
</summary>

```txt
Port = 8000

MONGO_URI = mongodb+srv://mannatgarg2006:gargi167@cluster0.je1dn.mongodb.net/ASAP?retryWrites=true&w=majority&appName=Cluster0
```

</details>

</td></tr>
</table>

author_association: NONE
user: login: QodoAI-Agent
created_at: 2025-04-03T05:08:17Z
body: **[Persistent review](https://github.com/kalviumcommunity/s84_what_if/pull/14#issuecomment-2774507696)** updated to latest commit https://github.com/kalviumcommunity/s84_what_if/commit/2966b25b6f83cc4f5102067de6f9c0c1d9d6515a
author_association: NONE