feat: basic api setup and boilerplate
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
import prisma from "../prisma/client.js";
|
||||
|
||||
/* CREATE BLOG */
|
||||
|
||||
export async function createBlog(req, res) {
|
||||
const {title, writer, image, content, isActive} = req.body;
|
||||
|
||||
try {
|
||||
const blog = await prisma.blog.create({
|
||||
data: {
|
||||
title,
|
||||
writer,
|
||||
image,
|
||||
content,
|
||||
isActive,
|
||||
},
|
||||
});
|
||||
|
||||
res.json(blog);
|
||||
} catch (error) {
|
||||
res.status(500).json({error: "Blog creation failed"});
|
||||
}
|
||||
}
|
||||
|
||||
/* GET ALL BLOGS (Public) */
|
||||
|
||||
export async function getBlogs(req, res) {
|
||||
try {
|
||||
const blogs = await prisma.blog.findMany({
|
||||
where: {isActive: true},
|
||||
orderBy: {createdAt: "desc"},
|
||||
});
|
||||
|
||||
res.json(blogs);
|
||||
} catch (error) {
|
||||
res.status(500).json({error: error.message});
|
||||
}
|
||||
}
|
||||
|
||||
/* GET ALL BLOGS (Admin) */
|
||||
|
||||
export async function getAllBlogs(req, res) {
|
||||
try {
|
||||
const blogs = await prisma.blog.findMany({
|
||||
orderBy: {createdAt: "desc"},
|
||||
});
|
||||
|
||||
res.json(blogs);
|
||||
} catch (error) {
|
||||
res.status(500).json({error: error.message});
|
||||
}
|
||||
}
|
||||
|
||||
/* GET SINGLE BLOG */
|
||||
|
||||
export async function getBlog(req, res) {
|
||||
try {
|
||||
const id = Number(req.params.id);
|
||||
|
||||
const blog = await prisma.blog.findUnique({
|
||||
where: {id},
|
||||
});
|
||||
|
||||
if (!blog) {
|
||||
return res.status(404).json({error: "Blog not found"});
|
||||
}
|
||||
|
||||
res.json(blog);
|
||||
} catch (error) {
|
||||
res.status(500).json({error: error.message});
|
||||
}
|
||||
}
|
||||
|
||||
/* UPDATE BLOG */
|
||||
|
||||
export async function updateBlog(req, res) {
|
||||
try {
|
||||
const {title, writer, image, content} = req.body;
|
||||
|
||||
const blog = await prisma.blog.update({
|
||||
where: {id: Number(req.params.id)},
|
||||
data: {
|
||||
title,
|
||||
writer,
|
||||
image,
|
||||
content,
|
||||
},
|
||||
});
|
||||
|
||||
res.json(blog);
|
||||
} catch (error) {
|
||||
res.status(500).json({error: error.message});
|
||||
}
|
||||
}
|
||||
|
||||
/* DELETE BLOG */
|
||||
|
||||
export async function deleteBlog(req, res) {
|
||||
try {
|
||||
const id = Number(req.params.id);
|
||||
|
||||
await prisma.blog.delete({
|
||||
where: {id},
|
||||
});
|
||||
|
||||
res.json({message: "Blog deleted successfully"});
|
||||
} catch (error) {
|
||||
res.status(500).json({error: error.message});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user