From 051e080f7e79d26cf729639fccf7f1fbaf5a08f8 Mon Sep 17 00:00:00 2001 From: KKlochko Date: Tue, 20 Jun 2023 21:01:48 +0300 Subject: [PATCH] Add the methods to show cart items and to add an item to a cart. --- src/api/v2/cart_api.py | 58 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/api/v2/cart_api.py diff --git a/src/api/v2/cart_api.py b/src/api/v2/cart_api.py new file mode 100644 index 0000000..ead031f --- /dev/null +++ b/src/api/v2/cart_api.py @@ -0,0 +1,58 @@ +import aiohttp +import asyncio +import ujson + +class CartAPI: + def __init__(self, fetcher, formatter): + """ + Sets needed classes: + + Fetcher (ApiFetcher) - class that will fetch data. + Format (AbstractFormat) - class that will format response data. + """ + self.__fetcher, self.__formatter = fetcher, formatter + + async def get_dict(self, username: str): + endpoint = f"/api/v2/cart?matrixUsername={username}" + + status, json_data = await self.__fetcher.fetch_json(endpoint) + + if status == 200: + return {"ok": json_data} + + return {"error": "Сталася помилка, спробуйте пізніше."} + + async def add_obj(self, item_name: str, count: int, username: str): + endpoint = "/api/v2/add-item" + + status, json_data = await self.__fetcher.send_json(endpoint, { + 'itemName': item_name, + 'itemCount': count, + 'matrixUsername': username, + }) + + if status == 200: + return {"ok": json_data} + + return {"error": "Сталася помилка, спробуйте пізніше."} + + async def get_objects_message(self, username: str) -> str: + response = await self.get_dict(username) + + match response: + case {"ok": json_data}: + return self.__formatter.format_all(json_data) + + case {"error": error_message}: + return error_message + + async def add_object_message(self, item_name: str, count: int, username: str) -> str: + response = await self.add_obj(item_name, count, username) + + match response: + case {"ok": json_data}: + return 'Успішно додано' + + case {"error": error_message}: + return error_message +