feat: add endpoint to create new fruit

This commit is contained in:
Backend IM Bot 2025-04-29 20:22:55 +00:00
parent cf810bf4f4
commit c268c00801
5 changed files with 44 additions and 5 deletions

View File

@ -0,0 +1,17 @@
"""add new helper function to create a new fruit in the database
Revision ID: 1ad6a8ecd0d7
Revises: 2c9a83e4f6b3
Create Date: 2023-05-25 12:45:32.770309
"""
# revision identifiers, used by Alembic.
revision = '1ad6a8ecd0d7'
down_revision = '2c9a83e4f6b3'
branch_labels = None
depends_on = None
def upgrade():
pass # No database changes required for the new helper function
def downgrade():
pass # No database changes required for the new helper function

View File

@ -0,0 +1,17 @@
from fastapi import APIRouter, status
from schemas.fruit import FruitCreate, FruitSchema
from helpers.fruit_helpers import create_fruit
from sqlalchemy.orm import Session
from fastapi import Depends
from core.database import get_db
router = APIRouter()
@router.post("/fruits", status_code=status.HTTP_201_CREATED, response_model=FruitSchema)
async def add_fruit(
fruit: FruitCreate,
db: Session = Depends(get_db)
):
"""Create a new fruit"""
new_fruit = create_fruit(db=db, fruit_data=fruit)
return new_fruit

View File

@ -47,7 +47,7 @@ def create_fruit(db: Session, fruit_data: FruitCreate) -> Fruit:
Returns:
Fruit: The newly created fruit object.
"""
db_fruit = Fruit(**fruit_data.dict())
db_fruit = Fruit.create_new_fruit(name=fruit_data.name, description=fruit_data.description, price=fruit_data.price)
db.add(db_fruit)
db.commit()
db.refresh(db_fruit)

View File

@ -12,4 +12,9 @@ class Fruit(Base):
description = Column(String, nullable=True)
price = Column(Integer, nullable=False)
created_at = Column(DateTime, default=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
@classmethod
def create_new_fruit(cls, name, description, price):
new_fruit = cls(name=name, description=description, price=price)
return new_fruit

View File

@ -1,7 +1,7 @@
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
import uuid
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class FruitBase(BaseModel):
name: str = Field(..., description="Name of the fruit")