This is the initial push of the outline of the life dashboard
This commit is contained in:
71
backend/app/routers/weight.py
Normal file
71
backend/app/routers/weight.py
Normal file
@@ -0,0 +1,71 @@
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.auth import get_current_user
|
||||
from app.database import get_db
|
||||
from app.models.weight import WeightEntry
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/weight", tags=["weight"], dependencies=[Depends(get_current_user)]
|
||||
)
|
||||
|
||||
|
||||
class WeightCreate(BaseModel):
|
||||
date: date
|
||||
weight_lbs: float
|
||||
body_fat_pct: float | None = None
|
||||
notes: str | None = None
|
||||
|
||||
|
||||
class WeightRead(WeightCreate):
|
||||
id: int
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
@router.get("", response_model=list[WeightRead])
|
||||
def list_weight(
|
||||
from_date: date | None = Query(None, alias="from"),
|
||||
to_date: date | None = Query(None, alias="to"),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
q = select(WeightEntry).order_by(WeightEntry.date.desc())
|
||||
if from_date:
|
||||
q = q.where(WeightEntry.date >= from_date)
|
||||
if to_date:
|
||||
q = q.where(WeightEntry.date <= to_date)
|
||||
return db.scalars(q).all()
|
||||
|
||||
|
||||
@router.post("", response_model=WeightRead, status_code=201)
|
||||
def create_weight(body: WeightCreate, db: Session = Depends(get_db)):
|
||||
entry = WeightEntry(**body.model_dump())
|
||||
db.add(entry)
|
||||
db.commit()
|
||||
db.refresh(entry)
|
||||
return entry
|
||||
|
||||
|
||||
@router.put("/{entry_id}", response_model=WeightRead)
|
||||
def update_weight(entry_id: int, body: WeightCreate, db: Session = Depends(get_db)):
|
||||
entry = db.get(WeightEntry, entry_id)
|
||||
if not entry:
|
||||
raise HTTPException(status_code=404, detail="Entry not found")
|
||||
for key, val in body.model_dump().items():
|
||||
setattr(entry, key, val)
|
||||
db.commit()
|
||||
db.refresh(entry)
|
||||
return entry
|
||||
|
||||
|
||||
@router.delete("/{entry_id}", status_code=204)
|
||||
def delete_weight(entry_id: int, db: Session = Depends(get_db)):
|
||||
entry = db.get(WeightEntry, entry_id)
|
||||
if not entry:
|
||||
raise HTTPException(status_code=404, detail="Entry not found")
|
||||
db.delete(entry)
|
||||
db.commit()
|
||||
Reference in New Issue
Block a user