import response from "../response.js"; import models from "../models/index.js"; export const getTopics = async (req, res) => { try { const topics = await models.Topic.findAll(); response(200, topics, "Success", res); } catch (error) { console.log(error); response(500, null, "Error retrieving topics data!", res); } }; export const getTopicById = async (req, res) => { try { const { id } = req.params; const topic = await models.Topic.findByPk(id); if (!topic) { return response(404, null, "Topic not found", res); } response(200, topic, "Success", res); } catch (error) { console.log(error); res.status(500).json({ message: "Internal Server Error" }); } }; export const createTopic = async (req, res) => { const { subject_id, title } = req.body; // Validate subject_id if (!subject_id) { return response(400, null, "Subject ID is required", res); } // Validate title if (!title) { return response(400, null, "Title is required", res); } try { // Verify that the subject_id exists in the m_subjects table const subject = await models.Subject.findByPk(subject_id); if (!subject) { return response(404, null, "Subject not found", res); } const newTopic = await models.Topic.create({ subject_id, title, }); response(201, newTopic, "Topic created successfully", res); } catch (error) { console.log(error); response(500, null, "Internal Server Error", res); } }; export const updateTopicById = async (req, res) => { const { id } = req.params; const { subject_id, title } = req.body; try { // Find the topic by its ID const topic = await models.Topic.findByPk(id); if (!topic) { return response(404, null, "Topic not found", res); } // Validate and update subject_id if provided if (subject_id) { const subject = await models.Subject.findByPk(subject_id); if (!subject) { return response(404, null, "Subject not found", res); } topic.subject_id = subject_id; } // Validate and update title if provided if (title) { topic.title = title; } // Save the updated topic await topic.save(); response(200, topic, "Topic updated successfully", res); } catch (error) { console.log(error); response(500, null, "Internal Server Error", res); } }; export const deleteTopicById = async (req, res) => { const { id } = req.params; try { // Find the topic by its ID const topic = await models.Topic.findByPk(id); if (!topic) { return response(404, null, "Topic not found", res); } // Delete the topic await topic.destroy(); response(200, null, "Topic deleted successfully", res); } catch (error) { console.log(error); response(500, null, "Internal Server Error", res); } };