From 52713221ebd2133423b250bf77f456b91b1ddd08 Mon Sep 17 00:00:00 2001 From: Kfir Dayan Date: Fri, 9 Jun 2023 19:13:16 +0300 Subject: [PATCH] list of products --- src/controllers/ProductController.ts | 18 ++++++++++++++++++ src/routes/product.ts | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/controllers/ProductController.ts b/src/controllers/ProductController.ts index 870afdb..b13550a 100644 --- a/src/controllers/ProductController.ts +++ b/src/controllers/ProductController.ts @@ -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.' }); + } +} + diff --git a/src/routes/product.ts b/src/routes/product.ts index ad2688b..bc13f7b 100644 --- a/src/routes/product.ts +++ b/src/routes/product.ts @@ -1,6 +1,6 @@ import express, { Request } from 'express'; 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 // product name, description, and price. productRouter.post('/', authenticateToken, createProduct) +productRouter.get('/', listProducts); export default productRouter; \ No newline at end of file