DigitalDB / src /controllers /ingredientController.js
Mr-Thop's picture
Add files
3db086d
Raw
History Blame Contribute Delete
2.35 kB
const db = require('../config/database');
exports.getAllIngredients = async (req, res) => {
try {
const [rows] = await db.query('SELECT * FROM ingredients');
res.json({ success: true, data: rows });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
exports.getIngredientById = async (req, res) => {
try {
const [rows] = await db.query('SELECT * FROM ingredients WHERE ingredient_id = ?', [req.params.id]);
if (rows.length === 0) {
return res.status(404).json({ success: false, error: 'Ingredient not found' });
}
res.json({ success: true, data: rows[0] });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
exports.createIngredient = async (req, res) => {
try {
const { ingredient_name } = req.body;
const [result] = await db.query(
'INSERT INTO ingredients (ingredient_name) VALUES (?)',
[ingredient_name]
);
res.status(201).json({
success: true,
message: 'Ingredient created successfully',
data: { ingredient_id: result.insertId }
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
exports.updateIngredient = async (req, res) => {
try {
const { ingredient_name } = req.body;
const [result] = await db.query(
'UPDATE ingredients SET ingredient_name = ? WHERE ingredient_id = ?',
[ingredient_name, req.params.id]
);
if (result.affectedRows === 0) {
return res.status(404).json({ success: false, error: 'Ingredient not found' });
}
res.json({ success: true, message: 'Ingredient updated successfully' });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};
exports.deleteIngredient = async (req, res) => {
try {
const [result] = await db.query('DELETE FROM ingredients WHERE ingredient_id = ?', [req.params.id]);
if (result.affectedRows === 0) {
return res.status(404).json({ success: false, error: 'Ingredient not found' });
}
res.json({ success: true, message: 'Ingredient deleted successfully' });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
};