const { log } = require("handlebars"); const Blog = require("../models/Blog"); const User = require("../models/User"); module.exports.getAllBlogs = async (req, res, next) => { try { let blog = await Blog.find(); if (blog) { res.json({ blogs: blog }); } else { console.log("Error in Blog", blog); return; } } catch { (err) => { res.status(422).json({ error: err }); }; } }; module.exports.addBlog = async (req, res, next) => { const { _id, title, body, image } = req.body; //_id is of user from frontend who is adding the blog. try { let user = await User.find({ _id }); console.log("User ", user); if (!title) { res.status(422).json({ message: "Please, Add Title of the Blog" }); return; } if (!body) { res.status(422).json({ message: "Please, Add Body of the Blog" }); return; } if (user) { let blog = new Blog({ title, body, image, date: new Date(), author: user, }); await blog.save(); res.json({ message: "Blog Saved Successfully!" }); } else { res.status.json({ error: "User Doesn't Exists" }); return; } } catch { (err) => { res.status(422).json({ error: err }); }; } }; module.exports.deleteBlog = async (req, res, next) => { const { _id } = req.body; try { let blog = await Blog.find({ _id }); if (blog) { await Blog.findByIdAndDelete(_id); res.json({ message: "Blog Deleted!" }); } else { res.status(404).json({ message: "Blog Not Found" }); return; } } catch { (err) => { res.status(422).json({ error: err }); }; } }; module.exports.editBlog = async (req, res, next) => { const { _id, body, title, image } = req.body; try { if (!title) { res.status(422).json({ message: "Please, Add the Title of the Blog." }); return; } if (!body) { res.status(422).json({ message: "Please, Add the Body of the Blog." }); return; } if (!image) { res.status(422).json({ message: "Please, Add the Image of the Blog." }); return; } let blog = Blog.findById(_id); if (blog) { blog.title = title; blog.body = body; blog.image = image; await blog.save(); res.json({ message: "Blog Updated!" }); } else { res.status(422).json({ error: "Blog Doesn't Found" }); return; } } catch { (err) => { res.status(422).json({ error: err }); }; } };