prisma-CRUD-validate/controller/blog.controller.js

95 lines
2 KiB
JavaScript
Raw Normal View History

2025-01-24 06:09:35 +00:00
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
async function createBlog(req, res) {
const { slug, title, body, categoryIDs, tagIDs } = req.body;
const coverImage = req.file ? req.file.path : null;
try {
const newBlog = await prisma.Blog.create({
data: {
slug,
title,
body,
coverImage,
categoryIDs: JSON.parse(categoryIDs),
tagIDs: JSON.parse(tagIDs),
},
});
res.status(201).json(newBlog);
} catch (error) {
console.error("Error creating blog:", error);
res.status(500).json({ message: "Error creating blog" });
}
}
async function getBlogs(req, res) {
try {
const blogs = await prisma.Blog.findMany();
res.json(blogs);
} catch (error) {
console.error("Error getting blogs:", error);
res
.status(500)
.json({ message: "Error getting blogs", error: error.message });
}
}
async function updateBlog(req, res) {
const { slug, title, body, categoryIDs, tagIDs } = req.body;
const id = req.params.id;
try {
const blog = await prisma.Blog.findUnique({
where: { id },
});
if (!blog) {
return res.status(404).send({
message: "Blog not found",
});
}
const updatedBlog = await prisma.Blog.update({
where: { id },
data: {
slug,
title,
body,
categoryIDs,
tagIDs,
},
});
res.status(200).send(updatedBlog);
} catch (error) {
console.error("Error updating blog:", error);
res.status(500).send({
message: "Error updating blog",
error: error.message,
});
}
}
async function deleteBlog(req, res) {
const { id } = req.params;
try {
const blog = await prisma.Blog.delete({
where: { id },
});
res.json(blog);
} catch (error) {
console.error("Error deleting blog:", error);
res
.status(500)
.json({ message: "Error deleting blog", error: error.message });
}
}
module.exports = {
createBlog,
getBlogs,
updateBlog,
deleteBlog,
};