Skip to content

Commit

Permalink
Merge pull request #1411 from AyushSharma72/comment
Browse files Browse the repository at this point in the history
save comment to database
  • Loading branch information
ANSHIKA-26 authored Oct 25, 2024
2 parents eb31832 + c279d9c commit 7afb4a6
Show file tree
Hide file tree
Showing 9 changed files with 125 additions and 2 deletions.
1 change: 1 addition & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# MONGO_URI=mongodb://localhost:27017/bloggingdb
MONGO_URI=mongodb://localhost:27017/bloggingdb
JWT_SECRET=scijyasfy7dsvegdffvbfbfgg435tgrsnbgfgn
PORT=5000
Expand Down
4 changes: 4 additions & 0 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ import dotenv from "dotenv";
import connectDB from "./utils/db.js";
import blogRoutes from "./routes/blogRoutes.js";
import userRoutes from "./routes/userRoutes.js";
import cors from "cors";

dotenv.config();
const app = express();
connectDB();

app.use(express.json());

// to avoid cross origin errror
app.use(cors());

app.use("/api/users", userRoutes);
app.use("/api/blogs", blogRoutes);

Expand Down
36 changes: 36 additions & 0 deletions backend/controllers/blogController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Blog from "../models/blog.js";
import Comment from "../models/comment.js";

export const createBlog = async (req, res) => {
try {
Expand Down Expand Up @@ -52,3 +53,38 @@ export const getSingleBlog = async (req, res) => {
res.status(500).json({ message: error.message });
}
};

export const saveComment = async (req, resp) => {
try {
const { name, comment } = req.body;

if (!name || !comment) {
return resp.status(400).send({
message: "all fields are required",
success: false,
});
}

const newcomment = await new Comment({
name: name,
comment: comment,
});

newcomment.save();

if (newcomment) {
return resp.status(200).send({
success: true,
message: "new comment added",
newcomment,
});
}
} catch (error) {
console.log(error);
return resp.status(500).send({
success: false,
message: "internal server error",
error,
});
}
};
21 changes: 21 additions & 0 deletions backend/models/comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { mongoose } from "mongoose";

const commentSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
},
comment: {
type: String,
required: true,
trim: true,
},
},
{ timestamps: true }
);

const Comment = mongoose.model("Comment", commentSchema);

export default Comment;
14 changes: 14 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"description": "",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"express-validator": "^7.2.0",
Expand Down
4 changes: 4 additions & 0 deletions backend/routes/blogRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
deleteBlog,
getAllBlogs,
getSingleBlog,
saveComment,
} from "../controllers/blogController.js";
import authMiddleware from "../middlewares/authMiddleware.js";
import adminMiddleware from "../middlewares/adminMiddleware.js";
Expand All @@ -23,4 +24,7 @@ router.put("/:id", authMiddleware, blogValidation, updateBlog);
// Admin-only routes
router.delete("/:id", authMiddleware, adminMiddleware, deleteBlog);

// save user comments
router.post("/savecomment", saveComment);

export default router;
44 changes: 43 additions & 1 deletion blog-comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ function showToast(message, type) {
toast.style.transition = "opacity 0.5s, transform 0.5s";
toast.style.boxShadow = "0 4px 20px rgba(0, 0, 0, 0.2)";

// Apply different styles based on the type of toast
// Apply different styles based on the type of toast
if (type === "success") {
toast.style.backgroundColor = "rgba(40, 167, 69, 0.75)"; // Slightly transparent green
} else if (type === "error") {
Expand All @@ -165,3 +165,45 @@ function showToast(message, type) {
}, 500);
}, 3000);
}
async function saveComment(event) {
event.preventDefault(); // Prevent the default form submission

// Get values from the form inputs
const name = document.getElementById("commenterName").value.trim();
const comment = document.getElementById("commentText").value.trim();

// Check if both name and comment fields are filled
if (!name || !comment) {
alert("All fields are required.");
return;
}

// Prepare data to send to the server
const data = { name, comment };

try {
// Make the API request to save the comment
const response = await fetch(
"http://localhost:5000/api/blogs/savecomment",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}
);

// Handle the response
const result = await response.json();
if (result.success) {
alert(result.message); // Show success message
document.getElementById("commentForm").reset(); // Clear the form
} else {
alert(result.message); // Show error message from server
}
} catch (error) {
console.error("Error:", error);
alert("An error occurred. Please try again later.");
}
}
2 changes: 1 addition & 1 deletion blog.html
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ <h3 class="form-title">Share Your Thoughts</h3>
<label for="commentText" class="input-label">Your Comment</label>
</div>
<input type="hidden" id="parentCommentId" value="">
<button type="submit" class="submit-button">
<button type="submit" class="submit-button" onclick="saveComment(event)">
Post Comment
</button>
</form>
Expand Down

1 comment on commit 7afb4a6

@vercel
Copy link

@vercel vercel bot commented on 7afb4a6 Oct 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.