Skip to content

Commit ffad03b

Browse files
CRUD Blog
1 parent 2279901 commit ffad03b

File tree

6 files changed

+1422
-35
lines changed

6 files changed

+1422
-35
lines changed

controller/blogCtrl.js

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ const Blog = require("../models/blogModel");
22
const User = require("../models/userModel");
33
const asyncHandler = require("express-async-handler");
44
const validateMongoDBID = require("../utils/validateMongoDB");
5+
const cloudinaryUploadImg = require("../utils/cloudinary");
6+
const fs = require("fs");
57

68
const createBlog = asyncHandler(async (req, res) => {
79
try {
@@ -25,7 +27,177 @@ const updateBlog = asyncHandler(async (req, res) => {
2527
}
2628
});
2729

30+
const getBlog = asyncHandler(async (req, res) => {
31+
const { id } = req.params;
32+
validateMongoDBID(id);
33+
try {
34+
const getBlog = await Blog.findById(id)
35+
.populate("likes")
36+
.populate("dislikes");
37+
const updateViews = await Blog.findByIdAndUpdate(
38+
id,
39+
{
40+
$inc: { numViews: 1 },
41+
},
42+
{ new: true }
43+
);
44+
res.json(getBlog);
45+
} catch (error) {
46+
throw new Error(error);
47+
}
48+
});
49+
50+
const getAllBlogs = asyncHandler(async (req, res) => {
51+
try {
52+
const getBlogs = await Blog.find();
53+
res.json(getBlogs);
54+
} catch (error) {
55+
throw new Error(error);
56+
}
57+
});
58+
59+
const deleteBlog = asyncHandler(async (req, res) => {
60+
const { id } = req.params;
61+
validateMongoDBID(id);
62+
try {
63+
const deletedBlog = await Blog.findByIdAndDelete(id);
64+
res.json(deletedBlog);
65+
} catch (error) {
66+
throw new Error(error);
67+
}
68+
});
69+
70+
const liketheBlog = asyncHandler(async (req, res) => {
71+
const { blogId } = req.body;
72+
validateMongoDBID(blogId);
73+
// Find the blog which you want to be liked
74+
const blog = await Blog.findById(blogId);
75+
// find the login user
76+
const loginUserId = req?.user?._id;
77+
// find if the user has liked the blog
78+
const isLiked = blog?.isLiked;
79+
// find if the user has disliked the blog
80+
const alreadyDisliked = blog?.dislikes?.find(
81+
(userId) => userId?.toString() === loginUserId?.toString()
82+
);
83+
if (alreadyDisliked) {
84+
const blog = await Blog.findByIdAndUpdate(
85+
blogId,
86+
{
87+
$pull: { dislikes: loginUserId },
88+
isDisliked: false,
89+
},
90+
{ new: true }
91+
);
92+
res.json(blog);
93+
}
94+
if (isLiked) {
95+
const blog = await Blog.findByIdAndUpdate(
96+
blogId,
97+
{
98+
$pull: { likes: loginUserId },
99+
isLiked: false,
100+
},
101+
{ new: true }
102+
);
103+
res.json(blog);
104+
} else {
105+
const blog = await Blog.findByIdAndUpdate(
106+
blogId,
107+
{
108+
$push: { likes: loginUserId },
109+
isLiked: true,
110+
},
111+
{ new: true }
112+
);
113+
res.json(blog);
114+
}
115+
});
116+
const disliketheBlog = asyncHandler(async (req, res) => {
117+
const { blogId } = req.body;
118+
validateMongoDBID(blogId);
119+
// Find the blog which you want to be liked
120+
const blog = await Blog.findById(blogId);
121+
// find the login user
122+
const loginUserId = req?.user?._id;
123+
// find if the user has liked the blog
124+
const isDisLiked = blog?.isDisliked;
125+
// find if the user has disliked the blog
126+
const alreadyLiked = blog?.likes?.find(
127+
(userId) => userId?.toString() === loginUserId?.toString()
128+
);
129+
if (alreadyLiked) {
130+
const blog = await Blog.findByIdAndUpdate(
131+
blogId,
132+
{
133+
$pull: { likes: loginUserId },
134+
isLiked: false,
135+
},
136+
{ new: true }
137+
);
138+
res.json(blog);
139+
}
140+
if (isDisLiked) {
141+
const blog = await Blog.findByIdAndUpdate(
142+
blogId,
143+
{
144+
$pull: { dislikes: loginUserId },
145+
isDisliked: false,
146+
},
147+
{ new: true }
148+
);
149+
res.json(blog);
150+
} else {
151+
const blog = await Blog.findByIdAndUpdate(
152+
blogId,
153+
{
154+
$push: { dislikes: loginUserId },
155+
isDisliked: true,
156+
},
157+
{ new: true }
158+
);
159+
res.json(blog);
160+
}
161+
});
162+
163+
const uploadImages = asyncHandler(async (req, res) => {
164+
const { id } = req.params;
165+
validateMongoDBID(id);
166+
try {
167+
const uploader = (path) => cloudinaryUploadImg(path, "images");
168+
const urls = [];
169+
const files = req.files;
170+
for (const file of files) {
171+
const { path } = file;
172+
const newpath = await uploader(path);
173+
console.log(newpath);
174+
urls.push(newpath);
175+
fs.unlinkSync(path);
176+
}
177+
const findBlog = await Blog.findByIdAndUpdate(
178+
id,
179+
{
180+
images: urls.map((file) => {
181+
return file;
182+
}),
183+
},
184+
{
185+
new: true,
186+
}
187+
);
188+
res.json(findBlog);
189+
} catch (error) {
190+
throw new Error(error);
191+
}
192+
});
193+
28194
module.exports = {
29195
createBlog,
30196
updateBlog,
197+
getBlog,
198+
getAllBlogs,
199+
deleteBlog,
200+
liketheBlog,
201+
disliketheBlog,
202+
uploadImages,
31203
};

middlewares/uploadImage.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
const multer = require("multer");
2+
const sharp = require("sharp");
3+
const path = require("path");
4+
const fs = require("fs");
5+
const storage = multer.diskStorage({
6+
destination: function (req, file, cb) {
7+
cb(null, path.join(__dirname, "../public/images/"));
8+
},
9+
filename: function (req, file, cb) {
10+
const uniquesuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
11+
cb(null, file.fieldname + "-" + uniquesuffix + ".jpeg");
12+
},
13+
});
14+
15+
const multerFilter = (req, file, cb) => {
16+
if (file.mimetype.startsWith("image")) {
17+
cb(null, true);
18+
} else {
19+
cb({ message: "Unsupported file format" }, false);
20+
}
21+
};
22+
23+
const uploadPhoto = multer({
24+
storage: storage,
25+
fileFilter: multerFilter,
26+
limits: { fileSize: 1000000 },
27+
});
28+
29+
const productImgResize = async (req, res, next) => {
30+
if (!req.files) return next();
31+
await Promise.all(
32+
req.files.map(async (file) => {
33+
await sharp(file.path)
34+
.resize(300, 300)
35+
.toFormat("jpeg")
36+
.jpeg({ quality: 90 })
37+
.toFile(`public/images/products/${file.filename}`);
38+
fs.unlinkSync(`public/images/products/${file.filename}`);
39+
})
40+
);
41+
next();
42+
};
43+
44+
const blogImgResize = async (req, res, next) => {
45+
if (!req.files) return next();
46+
await Promise.all(
47+
req.files.map(async (file) => {
48+
await sharp(file.path)
49+
.resize(300, 300)
50+
.toFormat("jpeg")
51+
.jpeg({ quality: 90 })
52+
.toFile(`public/images/blogs/${file.filename}`);
53+
fs.unlinkSync(`public/images/blogs/${file.filename}`);
54+
})
55+
);
56+
next();
57+
};
58+
module.exports = { uploadPhoto, productImgResize, blogImgResize };

0 commit comments

Comments
 (0)