You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.0 KiB

import blogModel from "../models/blogModel.js";
import blogImage from "../models/blogImage.js";
// Get all blogs with images
export const getAllBlogs = async (req, res) => {
try {
const blogs = await blogModel.findAll({
include: [{ model: blogImage }]
});
res.json(blogs);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get a single blog by ID
export const getBlogById = async (req, res) => {
try {
const blog = await blogModel.findByPk(req.params.id, {
include: [{ model: blogImage }]
});
if (!blog) return res.status(404).json({ message: "Blog not found" });
res.json(blog);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Create a new blog
export const createBlog = async (req, res) => {
const { title, description, images } = req.body;
try {
const blog = await blogModel.create({ title, description });
if (images && images.length > 0) {
await blogImage.bulkCreate(images.map(imageUrl => ({ blogId: blog.id, imageUrl })));
}
res.status(201).json(blog);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Update a blog
export const updateBlog = async (req, res) => {
try {
const blog = await blogModel.findByPk(req.params.id);
if (!blog) return res.status(404).json({ message: "Blog not found" });
await blog.update(req.body);
res.json(blog);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Delete a blog
export const deleteBlog = async (req, res) => {
try {
const blog = await blogModel.findByPk(req.params.id);
if (!blog) return res.status(404).json({ message: "Blog not found" });
await blog.destroy();
res.json({ message: "Blog deleted successfully" });
} catch (error) {
res.status(500).json({ message: error.message });
}
};