|
| 1 | +import { Request, Response } from "express"; |
| 2 | +import Product from "../models/product.model"; |
| 3 | + |
| 4 | +export const createProduct = async (req: Request, res: Response) => { |
| 5 | + try { |
| 6 | + const { name, description, price, category, stock } = req.body; |
| 7 | + |
| 8 | + if (!name || !description || !price) { |
| 9 | + return res.status(400).json({ message: "Missing required fields" }); |
| 10 | + } |
| 11 | + |
| 12 | + const product = await Product.create({ name, description, price, category, stock }); |
| 13 | + return res.status(201).json(product); |
| 14 | + } catch (error) { |
| 15 | + console.error("Create Product Error:", error); |
| 16 | + res.status(500).json({ message: "Server error" }); |
| 17 | + } |
| 18 | +}; |
| 19 | + |
| 20 | +export const getProducts = async (_req: Request, res: Response) => { |
| 21 | + try { |
| 22 | + const products = await Product.find().sort({ createdAt: -1 }); |
| 23 | + res.status(200).json(products); |
| 24 | + } catch (error) { |
| 25 | + console.error("Get Products Error:", error); |
| 26 | + res.status(500).json({ message: "Server error" }); |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +export const getProductById = async (req: Request, res: Response) => { |
| 31 | + try { |
| 32 | + const product = await Product.findById(req.params.id); |
| 33 | + if (!product) return res.status(404).json({ message: "Product not found" }); |
| 34 | + res.status(200).json(product); |
| 35 | + } catch (error) { |
| 36 | + console.error("Get Product Error:", error); |
| 37 | + res.status(500).json({ message: "Server error" }); |
| 38 | + } |
| 39 | +}; |
| 40 | + |
| 41 | +export const updateProduct = async (req: Request, res: Response) => { |
| 42 | + try { |
| 43 | + const product = await Product.findByIdAndUpdate(req.params.id, req.body, { new: true }); |
| 44 | + if (!product) return res.status(404).json({ message: "Product not found" }); |
| 45 | + res.status(200).json(product); |
| 46 | + } catch (error) { |
| 47 | + console.error("Update Product Error:", error); |
| 48 | + res.status(500).json({ message: "Server error" }); |
| 49 | + } |
| 50 | +}; |
| 51 | + |
| 52 | +export const deleteProduct = async (req: Request, res: Response) => { |
| 53 | + try { |
| 54 | + const product = await Product.findByIdAndDelete(req.params.id); |
| 55 | + if (!product) return res.status(404).json({ message: "Product not found" }); |
| 56 | + res.status(200).json({ message: "Product deleted successfully" }); |
| 57 | + } catch (error) { |
| 58 | + console.error("Delete Product Error:", error); |
| 59 | + res.status(500).json({ message: "Server error" }); |
| 60 | + } |
| 61 | +}; |
0 commit comments