Skip to content

Commit 2836c83

Browse files
authored
Merge pull request #6 from mbm08/feature/fetchAllProducts
Feat : Created an endpoint to fetch all products
2 parents 1da0123 + eb31125 commit 2836c83

3 files changed

Lines changed: 34 additions & 4 deletions

File tree

src/app.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ app.use(express.json());
1212
app.get('/',(req,res)=>{
1313
res.send("Welcome to Homepage");
1414
})
15-
app.use('/api',productRoutes);
15+
16+
// Routes
17+
app.use('/api/products', productRoutes);
18+
1619
export default app
1720

src/controllers/product.controller.js

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,29 @@
11
import mongoose from "mongoose";
22
import Product from "../models/product.model.js";
33

4+
5+
/**
6+
* Get all products from the database
7+
* @route GET /api/products
8+
* @returns {Array} products - Array of product objects or empty array if no products
9+
*/
10+
const getAllProducts = async (req, res) => {
11+
try {
12+
// Fetch all products from the database
13+
const products = await Product.find({});
14+
15+
// Return products array (will be empty array if no products found)
16+
res.status(200).json(products);
17+
} catch (error) {
18+
// Handle any database errors
19+
console.error('Error fetching products:', error);
20+
res.status(500).json({
21+
message: 'Internal server error while fetching products',
22+
error: error.message
23+
});
24+
}
25+
};
26+
427
const getProductById = async(req,res)=>{
528
//fetches ID from request parameters
629
const id = req.params.id;
@@ -17,4 +40,4 @@ const getProductById = async(req,res)=>{
1740
return res.json(product);
1841
}
1942

20-
export {getProductById}
43+
export {getAllProducts, getProductById}

src/routes/product.routes.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import express from 'express';
2+
import { getAllProducts, getProductById } from '../controllers/product.controller.js';
3+
24
const router = express.Router();
3-
import {getProductById} from '../controllers/product.controller.js';
45

5-
router.get('/products/:id',getProductById);
6+
// Fetch all products
7+
router.get('/', getAllProducts);
8+
9+
router.get('/:id',getProductById);
610

711
export default router

0 commit comments

Comments
 (0)