78 lines
2.5 KiB
Python
78 lines
2.5 KiB
Python
from fastapi import APIRouter, HTTPException, Depends, Query
|
|
import src.messages as messages
|
|
import src.models as models
|
|
from src.database import get_session
|
|
from sqlmodel import Session
|
|
import src.products.service as service
|
|
import src.products.exceptions as exceptions
|
|
from src.auth.auth import get_current_user
|
|
|
|
router = APIRouter(prefix='/products')
|
|
|
|
@router.get('', response_model=list[models.ProductPublic], )
|
|
def get_products(
|
|
user: models.User = Depends(get_current_user),
|
|
session: Session = Depends(get_session),
|
|
names: list[str] = Query([]),
|
|
types: list[str] = Query([]),
|
|
productors: list[str] = Query([]),
|
|
):
|
|
return service.get_all(
|
|
session,
|
|
user,
|
|
names,
|
|
productors,
|
|
types,
|
|
)
|
|
|
|
@router.get('/{id}', response_model=models.ProductPublic)
|
|
def get_product(
|
|
id: int,
|
|
user: models.User = Depends(get_current_user),
|
|
session: Session = Depends(get_session)
|
|
):
|
|
result = service.get_one(session, id)
|
|
if result is None:
|
|
raise HTTPException(status_code=404, detail=messages.notfound)
|
|
return result
|
|
|
|
@router.post('', response_model=models.ProductPublic)
|
|
def create_product(
|
|
product: models.ProductCreate,
|
|
user: models.User = Depends(get_current_user),
|
|
session: Session = Depends(get_session)
|
|
):
|
|
try:
|
|
result = service.create_one(session, product)
|
|
except exceptions.ProductCreateError:
|
|
raise HTTPException(status_code=400, detail=messages.productinputinvalid)
|
|
except exceptions.ProductorNotFoundError:
|
|
raise HTTPException(status_code=404, detail=messages.productornotfound)
|
|
return result
|
|
|
|
@router.put('/{id}', response_model=models.ProductPublic)
|
|
def update_product(
|
|
id: int, product: models.ProductUpdate,
|
|
user: models.User = Depends(get_current_user),
|
|
session: Session = Depends(get_session)
|
|
):
|
|
try:
|
|
result = service.update_one(session, id, product)
|
|
except exceptions.ProductNotFoundError:
|
|
raise HTTPException(status_code=404, detail=messages.productnotfound)
|
|
except exceptions.ProductorNotFoundError:
|
|
raise HTTPException(status_code=404, detail=messages.productornotfound)
|
|
return result
|
|
|
|
@router.delete('/{id}', response_model=models.ProductPublic)
|
|
def delete_product(
|
|
id: int,
|
|
user: models.User = Depends(get_current_user),
|
|
session: Session = Depends(get_session)
|
|
):
|
|
try:
|
|
result = service.delete_one(session, id)
|
|
except exceptions.ProductNotFoundError:
|
|
raise HTTPException(status_code=404, detail=messages.notfound)
|
|
return result
|