-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathposts.js
More file actions
78 lines (76 loc) · 2.14 KB
/
posts.js
File metadata and controls
78 lines (76 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const cloudinary = require("../middleware/cloudinary");
const Post = require("../models/Post");
const Comment = require("../models/Comment")
module.exports = {
getProfile: async (req, res) => {
try {
const posts = await Post.find({ user: req.user.id });
res.render("profile.ejs", { posts: posts, user: req.user });
} catch (err) {
console.log(err);
}
},
getFeed: async (req, res) => {
try {
const posts = await Post.find().sort({ createdAt: "desc" }).lean();
res.render("feed.ejs", { posts: posts });
} catch (err) {
console.log(err);
}
},
getPost: async (req, res) => {
try {
const post = await Post.findById(req.params.id);
const comment = await Comment.find({postId: req.params.id}).sort({ createdAt: "desc" }).lean();
res.render("post.ejs", { post: post, user: req.user, comment: comment });
} catch (err) {
console.log(err);
}
},
createPost: async (req, res) => {
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);
await Post.create({
title: req.body.title,
image: result.secure_url,
cloudinaryId: result.public_id,
caption: req.body.caption,
likes: 0,
user: req.user.id,
});
console.log("Post has been added!");
res.redirect("/profile");
} catch (err) {
console.log(err);
}
},
likePost: async (req, res) => {
try {
await Post.findOneAndUpdate(
{ _id: req.params.id },
{
$inc: { likes: 1 },
}
);
console.log("Likes +1");
res.redirect(`/post/${req.params.id}`);
} catch (err) {
console.log(err);
}
},
deletePost: async (req, res) => {
try {
// Find post by id
let post = await Post.findById({ _id: req.params.id });
// Delete image from cloudinary
await cloudinary.uploader.destroy(post.cloudinaryId);
// Delete post from db
await Post.remove({ _id: req.params.id });
console.log("Deleted Post");
res.redirect("/profile");
} catch (err) {
res.redirect("/profile");
}
},
};