Cantilever-Labs/.history/controllers/blog_20210519151942.js

105 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-05-19 03:18:45 -07:00
const { log } = require("handlebars");
const Blog = require("../models/Blog");
const Course = require("../models/Course");
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 course = await Course.find({ _id }).populate("").select("-password");
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 (course) {
let blog = new Blog({
title,
body,
image,
date: new Date(),
author: course,
});
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 });
};
}
};