1- import Product from '../models/product.model.js' ;
1+ import mongoose from "mongoose" ;
2+ import Product from "../models/product.model.js" ;
3+
24
35/**
46 * Get all products from the database
57 * @route GET /api/products
68 * @returns {Array } products - Array of product objects or empty array if no products
79 */
8- export const getAllProducts = async ( req , res ) => {
10+ const getAllProducts = async ( req , res ) => {
911 try {
1012 // Fetch all products from the database
1113 const products = await Product . find ( { } ) ;
@@ -21,3 +23,21 @@ export const getAllProducts = async (req, res) => {
2123 } ) ;
2224 }
2325} ;
26+
27+ const getProductById = async ( req , res ) => {
28+ //fetches ID from request parameters
29+ const id = req . params . id ;
30+ if ( ! mongoose . Types . ObjectId . isValid ( id ) ) {
31+ //checks for validity of the id
32+ return res . status ( 400 ) . json ( { error : "Invalid ID format" } ) ;
33+ }
34+ // fetches the product details if id is valid & exists
35+ const product = await Product . findById ( id ) ;
36+ if ( ! product ) {
37+ //sends 404 error if product not found
38+ return res . status ( 404 ) . json ( { message :"Product not found" } ) ;
39+ }
40+ return res . json ( product ) ;
41+ }
42+
43+ export { getAllProducts , getProductById }
0 commit comments