list of products

This commit is contained in:
Kfir Dayan 2023-06-09 19:13:16 +03:00
parent 5ed21e9356
commit 52713221eb
2 changed files with 20 additions and 1 deletions

View file

@ -18,4 +18,22 @@ export async function createProduct(req: Request, res: Response) {
} }
} }
// List products: This should allow any user to view a paginated list of
// products, sorted by price.
export async function listProducts(req: Request, res: Response) {
try {
const { page, limit } = req.query;
const products = await Product.find()
.sort({ price: 1 })
.skip(Number(page) * Number(limit))
.limit(Number(limit));
res.json(products);
} catch (error) {
console.error('Error listing products:', error);
res.status(500).json({ error: 'An error occurred while listing the products.' });
}
}

View file

@ -1,6 +1,6 @@
import express, { Request } from 'express'; import express, { Request } from 'express';
import { authenticateToken } from '../middlewares/checkAuth'; import { authenticateToken } from '../middlewares/checkAuth';
import { createProduct } from '../controllers/ProductController'; import { createProduct, listProducts } from '../controllers/ProductController';
@ -9,5 +9,6 @@ const productRouter = express.Router();
// Create a product: This should require an authenticated user to provide a // Create a product: This should require an authenticated user to provide a
// product name, description, and price. // product name, description, and price.
productRouter.post('/', authenticateToken, createProduct) productRouter.post('/', authenticateToken, createProduct)
productRouter.get('/', listProducts);
export default productRouter; export default productRouter;