Skip to content

Commit b28d3af

Browse files
committed
feat:endpoint to fetch all products
1 parent e2ba5c8 commit b28d3af

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

src/app.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
import express from 'express';
22
import cors from 'cors';
3+
import productRoutes from './routes/product.routes.js';
34

45
const app = express();
56

67
app.use(cors());
78
app.use(express.json());
89

10+
// Routes
11+
app.use('/api/products', productRoutes);
12+
913
export default app
1014

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import Product from '../models/product.model.js';
2+
3+
/**
4+
* Get all products from the database
5+
* @route GET /api/products
6+
* @returns {Array} products - Array of product objects or empty array if no products
7+
*/
8+
export const getAllProducts = async (req, res) => {
9+
try {
10+
// Fetch all products from the database
11+
const products = await Product.find({});
12+
13+
// Return products array (will be empty array if no products found)
14+
res.status(200).json(products);
15+
} catch (error) {
16+
// Handle any database errors
17+
console.error('Error fetching products:', error);
18+
res.status(500).json({
19+
message: 'Internal server error while fetching products',
20+
error: error.message
21+
});
22+
}
23+
};

src/routes/product.routes.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import express from 'express';
2+
import { getAllProducts } from '../controllers/product.controller.js';
3+
4+
const router = express.Router();
5+
6+
// Fetch all products
7+
router.get('/', getAllProducts);
8+
9+
export default router;

0 commit comments

Comments
 (0)