46 lines
1.7 KiB
Python
46 lines
1.7 KiB
Python
from typing import List, Optional
|
|
from app.models.product import Product
|
|
from app.schemas.product import ProductCreate, ProductUpdate
|
|
|
|
fake_products_db = [
|
|
Product(id=1, name="Laptop", description="High performance laptop", price=999.99, stock=10),
|
|
Product(id=2, name="Mouse", description="Wireless mouse", price=29.99, stock=50),
|
|
Product(id=3, name="Keyboard", description="Mechanical keyboard", price=89.99, stock=25),
|
|
]
|
|
|
|
class ProductService:
|
|
@staticmethod
|
|
def get_all_products() -> List[Product]:
|
|
return fake_products_db
|
|
|
|
@staticmethod
|
|
def get_product_by_id(product_id: int) -> Optional[Product]:
|
|
for product in fake_products_db:
|
|
if product.id == product_id:
|
|
return product
|
|
return None
|
|
|
|
@staticmethod
|
|
def create_product(product_data: ProductCreate) -> Product:
|
|
new_id = max([p.id for p in fake_products_db]) + 1 if fake_products_db else 1
|
|
new_product = Product(
|
|
id=new_id,
|
|
name=product_data.name,
|
|
description=product_data.description,
|
|
price=product_data.price,
|
|
stock=product_data.stock
|
|
)
|
|
fake_products_db.append(new_product)
|
|
return new_product
|
|
|
|
@staticmethod
|
|
def update_product(product_id: int, product_data: ProductUpdate) -> Optional[Product]:
|
|
for i, product in enumerate(fake_products_db):
|
|
if product.id == product_id:
|
|
update_data = product_data.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(product, field, value)
|
|
return product
|
|
return None
|
|
|
|
product_service = ProductService() |