Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added comment feature #765

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions controllers/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const Comment = require('../models/Comment')

module.exports = {
createComment: async (req, res) => {
try {
await Comment.create({
comment: req.body.comment,
user: req.user.id,
post: req.params.id
});
console.log("Comment has been added!");
res.redirect("/post/"+req.params.id);
} catch (err) {
console.log(err);
}
},
}
8 changes: 5 additions & 3 deletions controllers/posts.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const cloudinary = require("../middleware/cloudinary");
const Post = require("../models/Post");
const Comment = require("../models/Comment");

module.exports = {
getProfile: async (req, res) => {
Expand All @@ -12,7 +13,7 @@ module.exports = {
},
getFeed: async (req, res) => {
try {
const posts = await Post.find().sort({ createdAt: "desc" }).lean();
const posts = await Post.find().sort({ createdAt: "desc" }).lean(); //sorts posts in feed from newest to oldest
res.render("feed.ejs", { posts: posts });
} catch (err) {
console.log(err);
Expand All @@ -21,7 +22,8 @@ module.exports = {
getPost: async (req, res) => {
try {
const post = await Post.findById(req.params.id);
res.render("post.ejs", { post: post, user: req.user });
const comments = await Comment.find({post: req.params.id}).sort({ createdAt: "desc" }).lean(); //sorts comments on posts from newest to oldest
res.render("post.ejs", { post: post, comments: comments, user: req.user });
} catch (err) {
console.log(err);
}
Expand Down Expand Up @@ -50,7 +52,7 @@ module.exports = {
await Post.findOneAndUpdate(
{ _id: req.params.id },
{
$inc: { likes: 1 },
$inc: { likes: 1 },//increases like count by one
}
);
console.log("Likes +1");
Expand Down
2 changes: 1 addition & 1 deletion middleware/cloudinary.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const cloudinary = require("cloudinary").v2;

require("dotenv").config({ path: "./config/.env" });

//Config for cloudinary account
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
Expand Down
3 changes: 2 additions & 1 deletion middleware/multer.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const multer = require("multer");
const path = require("path");

//code for image upload using multer
module.exports = multer({
storage: multer.diskStorage({}),
fileFilter: (req, file, cb) => {
let ext = path.extname(file.originalname);
if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") {
if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") { //prevents use of image filetypes other than .jpg, .jpeg, and .png
cb(new Error("File type is not supported"), false);
return;
}
Expand Down
22 changes: 22 additions & 0 deletions models/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require("mongoose")

const CommentSchema = new mongoose.Schema({
comment: {
type: String,
required: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
createdAt: {
type: Date,
default: Date.now,
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
}
})

module.exports = mongoose.model("Comment", CommentSchema);
7 changes: 7 additions & 0 deletions routes/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const express = require("express");
const router = express.Router();
const commentController = require("../controllers/comments")

router.post("/createComment/:id", commentController.createComment); //route for creating comments on a post; :id parameter tells DB which post the comment is being added to

module.exports = router;
2 changes: 1 addition & 1 deletion routes/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const router = express.Router();
const authController = require("../controllers/auth");
const homeController = require("../controllers/home");
const postsController = require("../controllers/posts");
const { ensureAuth, ensureGuest } = require("../middleware/auth");
const { ensureAuth, ensureGuest } = require("../middleware/auth"); //brings in authentication modules

//Main Routes - simplified for now
router.get("/", homeController.getIndex);
Expand Down
10 changes: 5 additions & 5 deletions routes/posts.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
const express = require("express");
const router = express.Router();
const upload = require("../middleware/multer");
const upload = require("../middleware/multer"); //brings in multer middleware for uploading multipart/form data
const postsController = require("../controllers/posts");
const { ensureAuth, ensureGuest } = require("../middleware/auth");

//Post Routes - simplified for now
router.get("/:id", ensureAuth, postsController.getPost);
router.get("/:id", ensureAuth, postsController.getPost); //gets post that is specified in query parameters

router.post("/createPost", upload.single("file"), postsController.createPost);
router.post("/createPost", upload.single("file"), postsController.createPost); //uses multer middleware to upload img with request

router.put("/likePost/:id", postsController.likePost);
router.put("/likePost/:id", postsController.likePost); //adds like to post specified in query parameter

router.delete("/deletePost/:id", postsController.deletePost);
router.delete("/deletePost/:id", postsController.deletePost); //deletes post specified in query parameter

module.exports = router;
22 changes: 12 additions & 10 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo")(session);
const methodOverride = require("method-override");
const flash = require("express-flash");
const logger = require("morgan");
const connectDB = require("./config/database");
const mainRoutes = require("./routes/main");
const postRoutes = require("./routes/posts");
const mongoose = require("mongoose"); //used for creating Models and managing Mongo data
const passport = require("passport"); //requires passport middleware for handling authentication
const session = require("express-session"); //requires sessions
const MongoStore = require("connect-mongo")(session); //handles sessions and cookies
const methodOverride = require("method-override"); //use forms for put / delete requests
const flash = require("express-flash"); // sends error flash messages to client (e.g. when username is entered incorrectly)
const logger = require("morgan"); //logs http requests
const connectDB = require("./config/database"); // for connecting to DB
const mainRoutes = require("./routes/main"); //connects to main routes file
const postRoutes = require("./routes/posts"); //connects to post routes file
const commentRoutes = require("./routes/comments") //connects to comments routes file

//Use .env file in config folder
require("dotenv").config({ path: "./config/.env" });
Expand Down Expand Up @@ -56,6 +57,7 @@ app.use(flash());
//Setup Routes For Which The Server Is Listening
app.use("/", mainRoutes);
app.use("/post", postRoutes);
app.use("/comment", commentRoutes);

//Server Running
app.listen(process.env.PORT, () => {
Expand Down
3 changes: 2 additions & 1 deletion views/partials/footer.ejs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
</body>
</html>
</html>
<!-- Full footer that can be added as a single line of code to each EJS file -->
1 change: 1 addition & 0 deletions views/partials/header.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@
</header>
</body>
</html>
<!-- Full header that can be added as a single line of code to each EJS file -->
22 changes: 22 additions & 0 deletions views/post.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,28 @@
<div class="col-3 mt-5">
<p><%= post.caption %></p>
</div>
<div class="col-6">
<ul>
<% for(var i=0; i<comments.length; i++) {%>
<li class="col-6 justify-content-between mt-5">
<span><%= comments[i].comment %></span>
</li>
<% } %>
</ul>
<div class="row justify-content-center mt-5">
<a class="btn btn-primary" href="/feed">Return to Feed</a>
</div>
</div>
<div class="mt-5">
<h2>Add a comment</h2>
<form action="/comments/createComment/<%= post._id %>" method="POST">
<div class="mb-3">
<label for="comment" class="form-label">Comment </label>
<input type="text" class="form-control" id="comment" name="comment">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="col-6 mt-5">
<a class="btn btn-primary" href="/profile">Return to Profile</a>
<a class="btn btn-primary" href="/feed">Return to Feed</a>
Expand Down