From 269470133748d43b5aa1a2fdf2f470ed0f30b5fd Mon Sep 17 00:00:00 2001 From: Thastertyn Date: Sun, 10 Mar 2024 17:11:26 +0100 Subject: [PATCH] Added product fetching and pages --- app/api/routes/product_routes.py | 11 +++++++++++ app/services/product_service.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/app/api/routes/product_routes.py b/app/api/routes/product_routes.py index 753a0bc..b174dc5 100644 --- a/app/api/routes/product_routes.py +++ b/app/api/routes/product_routes.py @@ -4,6 +4,17 @@ from app.api import bp_product from app.services.product_service import ProductService +@bp_product.route('/get', methods=['GET']) +def get_products(): + page = request.args.get('page', default=0, type=int) + + if page < 0: + return abort(400) + + result, status_code = ProductService.get_products(page) + + return result, status_code + @bp_product.route('/', methods=['GET']) def get_product_info(id: int): fields = ['name', 'price', 'image', 'image_name', 'seller'] diff --git a/app/services/product_service.py b/app/services/product_service.py index bf808d3..9aae4d1 100644 --- a/app/services/product_service.py +++ b/app/services/product_service.py @@ -7,6 +7,34 @@ from app.extensions import db_connection class ProductService: + @staticmethod + def get_products(page: int): + try: + with db_connection.cursor(dictionary=True) as cursor: + + offset = 10 * page + cursor.execute("select product.id, user.displayname as seller, product.name, product.price_pc from product inner join user on user.id = product.seller_id order by product.id limit 10 offset %s", (offset,)) + results = cursor.fetchall() + + if len(results) < 1: + return {"Failed": "Failed to fetch products. You've probably selected too far with pages"}, 400 + + result_obj = [] + for row in results: + mid_result = { + "id": row['id'], + "seller": row['seller'], + "name": row['name'], + "price": row['price_pc'] + } + + result_obj.append(mid_result) + + return result_obj, 200 + + except Error as e: + return {"Failed": f"Failed to load cart. Reason: {e}"}, 400 + @staticmethod def get_name(product_id: int): db_cursor.execute(f"select name from product where product.id = {product_id}")