feat: Generated endpoint endpoints/get-grocery.get.py via AI for Groceryitem
This commit is contained in:
parent
4d20697219
commit
36ce1e8ab7
@ -0,0 +1,27 @@
|
||||
"""create grocery_items table
|
||||
Revision ID: 7d4e9f2a
|
||||
Revises: b8c2316d
|
||||
Create Date: 2024-01-19 10:23:45.123456
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '7d4e9f2a'
|
||||
down_revision = 'b8c2316d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'grocery_items',
|
||||
sa.Column('id', sa.String(36), primary_key=True),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index(op.f('ix_grocery_items_name'), 'grocery_items', ['name'], unique=True)
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f('ix_grocery_items_name'), table_name='grocery_items')
|
||||
op.drop_table('grocery_items')
|
@ -0,0 +1,21 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from core.database import get_db
|
||||
from helpers.grocery_item_helpers import get_grocery_item_id_by_name, validate_grocery_item_name, format_grocery_item_response
|
||||
from typing import Dict, Any
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/get-grocery", response_model=Dict[str, Any])
|
||||
async def get_grocery_by_name(
|
||||
name: str,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
if not validate_grocery_item_name(name):
|
||||
raise HTTPException(status_code=400, detail="Invalid grocery item name")
|
||||
|
||||
item_id = get_grocery_item_id_by_name(db, name)
|
||||
if not item_id:
|
||||
raise HTTPException(status_code=404, detail="Grocery item not found")
|
||||
|
||||
return format_grocery_item_response(item_id, name)
|
61
helpers/groceryitem_helpers.py
Normal file
61
helpers/groceryitem_helpers.py
Normal file
@ -0,0 +1,61 @@
|
||||
from typing import Optional, Dict, Any
|
||||
from uuid import UUID
|
||||
from sqlalchemy.orm import Session
|
||||
from models.grocery_item import GroceryItem
|
||||
from fastapi import HTTPException
|
||||
|
||||
def get_grocery_item_id_by_name(db: Session, name: str) -> Optional[UUID]:
|
||||
"""
|
||||
Retrieves the ID of a grocery item based on its name.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
name (str): The name of the grocery item to search for.
|
||||
|
||||
Returns:
|
||||
Optional[UUID]: The ID of the grocery item if found, None otherwise.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the name is empty or None.
|
||||
"""
|
||||
if not name or not name.strip():
|
||||
raise HTTPException(status_code=400, detail="Grocery item name cannot be empty")
|
||||
|
||||
grocery_item = db.query(GroceryItem).filter(GroceryItem.name == name.strip()).first()
|
||||
return grocery_item.id if grocery_item else None
|
||||
|
||||
def validate_grocery_item_name(name: str) -> bool:
|
||||
"""
|
||||
Validates the grocery item name.
|
||||
|
||||
Args:
|
||||
name (str): The name to validate.
|
||||
|
||||
Returns:
|
||||
bool: True if the name is valid, False otherwise.
|
||||
"""
|
||||
if not name or not isinstance(name, str):
|
||||
return False
|
||||
|
||||
# Remove leading/trailing whitespace and check length
|
||||
cleaned_name = name.strip()
|
||||
if len(cleaned_name) < 1 or len(cleaned_name) > 100: # Assuming reasonable length limits
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def format_grocery_item_response(item_id: UUID, name: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Formats the grocery item response data.
|
||||
|
||||
Args:
|
||||
item_id (UUID): The ID of the grocery item.
|
||||
name (str): The name of the grocery item.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: Formatted response dictionary.
|
||||
"""
|
||||
return {
|
||||
"id": str(item_id),
|
||||
"name": name
|
||||
}
|
13
models/groceryitem.py
Normal file
13
models/groceryitem.py
Normal file
@ -0,0 +1,13 @@
|
||||
from sqlalchemy import Column, String, DateTime
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.sql import func
|
||||
from core.database import Base
|
||||
import uuid
|
||||
|
||||
class GroceryItem(Base):
|
||||
__tablename__ = "grocery_items"
|
||||
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
name = Column(String, unique=True, nullable=False, index=True)
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
29
schemas/groceryitem.py
Normal file
29
schemas/groceryitem.py
Normal file
@ -0,0 +1,29 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
class GroceryItemBase(BaseModel):
|
||||
name: str = Field(..., description="Name of the grocery item")
|
||||
|
||||
class GroceryItemCreate(GroceryItemBase):
|
||||
pass
|
||||
|
||||
class GroceryItemUpdate(GroceryItemBase):
|
||||
name: Optional[str] = Field(None, description="Name of the grocery item")
|
||||
|
||||
class GroceryItemSchema(GroceryItemBase):
|
||||
id: UUID
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
schema_extra = {
|
||||
"example": {
|
||||
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
|
||||
"name": "Milk",
|
||||
"created_at": "2023-01-01T12:00:00",
|
||||
"updated_at": "2023-01-01T12:00:00"
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user