feat: add tag management functionality to items route with add and remove tag endpoints
This commit is contained in:
parent
4e451d751b
commit
a99c0218fb
2 changed files with 37 additions and 1 deletions
|
|
@ -3,7 +3,7 @@ from sqlalchemy.orm import Session, joinedload
|
|||
from uuid import UUID
|
||||
from backend.database import get_db
|
||||
from backend import models
|
||||
from backend.schemas import ItemCreate, ItemOut
|
||||
from backend.schemas import ItemCreate, ItemOut, TagIdPayload, TagOut
|
||||
|
||||
router = APIRouter(prefix="/items", tags=["items"])
|
||||
|
||||
|
|
@ -42,6 +42,39 @@ def create_item(payload: ItemCreate, db: Session = Depends(get_db)):
|
|||
|
||||
return item
|
||||
|
||||
@router.post("/{item_id}/tags", response_model=ItemOut)
|
||||
def add_tag_to_item(item_id: UUID, payload: TagIdPayload, db: Session = Depends(get_db)):
|
||||
tag_id = payload.tag_id
|
||||
item = db.get(models.Item, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
tag = db.get(models.Tag, tag_id)
|
||||
if not tag or tag.user_id != item.user_id:
|
||||
raise HTTPException(status_code=404, detail="Tag not found")
|
||||
|
||||
if tag in item.tags:
|
||||
raise HTTPException(status_code=400, detail="Tag already associated with item")
|
||||
|
||||
item.tags.append(tag)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
return item
|
||||
|
||||
@router.delete("/{item_id}/tags/{tag_id}", response_model=ItemOut)
|
||||
def remove_tag_from_item(item_id: UUID, tag_id: UUID, db: Session = Depends(get_db)):
|
||||
item = db.get(models.Item, item_id)
|
||||
if not item:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
|
||||
tag = db.get(models.Tag, tag_id)
|
||||
if not tag or tag.user_id != item.user_id:
|
||||
raise HTTPException(status_code=404, detail="Tag not found")
|
||||
|
||||
item.tags.remove(tag)
|
||||
db.commit()
|
||||
db.refresh(item)
|
||||
return item
|
||||
|
||||
@router.delete("/{item_id}", status_code=204)
|
||||
def delete_item(item_id: UUID, db: Session = Depends(get_db)):
|
||||
|
|
|
|||
|
|
@ -15,6 +15,9 @@ class TagOut(TagBase):
|
|||
class Config:
|
||||
orm_mode = True
|
||||
|
||||
class TagIdPayload(BaseModel):
|
||||
tag_id: UUID
|
||||
|
||||
class ItemBase(BaseModel):
|
||||
name: str
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue