65 lines
2.0 KiB

1 month ago
  1. import blogModel from "../models/blogModel.js";
  2. import blogImage from "../models/blogImage.js";
  3. // Get all blogs with images
  4. export const getAllBlogs = async (req, res) => {
  5. try {
  6. const blogs = await blogModel.findAll({
  7. include: [{ model: blogImage }]
  8. });
  9. res.json(blogs);
  10. } catch (error) {
  11. res.status(500).json({ message: error.message });
  12. }
  13. };
  14. // Get a single blog by ID
  15. export const getBlogById = async (req, res) => {
  16. try {
  17. const blog = await blogModel.findByPk(req.params.id, {
  18. include: [{ model: blogImage }]
  19. });
  20. if (!blog) return res.status(404).json({ message: "Blog not found" });
  21. res.json(blog);
  22. } catch (error) {
  23. res.status(500).json({ message: error.message });
  24. }
  25. };
  26. // Create a new blog
  27. export const createBlog = async (req, res) => {
  28. const { title, description, images } = req.body;
  29. try {
  30. const blog = await blogModel.create({ title, description });
  31. if (images && images.length > 0) {
  32. await blogImage.bulkCreate(images.map(imageUrl => ({ blogId: blog.id, imageUrl })));
  33. }
  34. res.status(201).json(blog);
  35. } catch (error) {
  36. res.status(500).json({ message: error.message });
  37. }
  38. };
  39. // Update a blog
  40. export const updateBlog = async (req, res) => {
  41. try {
  42. const blog = await blogModel.findByPk(req.params.id);
  43. if (!blog) return res.status(404).json({ message: "Blog not found" });
  44. await blog.update(req.body);
  45. res.json(blog);
  46. } catch (error) {
  47. res.status(500).json({ message: error.message });
  48. }
  49. };
  50. // Delete a blog
  51. export const deleteBlog = async (req, res) => {
  52. try {
  53. const blog = await blogModel.findByPk(req.params.id);
  54. if (!blog) return res.status(404).json({ message: "Blog not found" });
  55. await blog.destroy();
  56. res.json({ message: "Blog deleted successfully" });
  57. } catch (error) {
  58. res.status(500).json({ message: error.message });
  59. }
  60. };