Subir todos los cambios recientes a la rama principal
This commit is contained in:
61
backend/app/api/v1/endpoints/clients.py
Normal file
61
backend/app/api/v1/endpoints/clients.py
Normal file
@@ -0,0 +1,61 @@
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import text # <--- IMPORTANTE: Necesario para consultas SQL
|
||||
from app.core.database import get_db
|
||||
|
||||
# IMPORTANTE: Renombramos para evitar conflictos
|
||||
from app.models.client import Client as ClientModel
|
||||
from app.schemas.client import ClientCreate, ClientUpdate, Client as ClientSchema
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# GET: Obtener todos los clientes
|
||||
@router.get("/clients", response_model=list[ClientSchema])
|
||||
async def get_clients(db: AsyncSession = Depends(get_db)):
|
||||
# Corrección: Usamos text() y mappings().all()
|
||||
query = text("SELECT * FROM clients")
|
||||
result = await db.execute(query)
|
||||
return result.mappings().all()
|
||||
|
||||
# POST: Crear cliente
|
||||
@router.post("/clients", response_model=ClientSchema)
|
||||
async def create_client(client: ClientCreate, db: AsyncSession = Depends(get_db)):
|
||||
# Usamos ClientModel para guardar en BD
|
||||
new_client = ClientModel(**client.dict())
|
||||
db.add(new_client)
|
||||
await db.commit()
|
||||
await db.refresh(new_client)
|
||||
return new_client
|
||||
|
||||
# GET ONE: Obtener un cliente por ID
|
||||
@router.get("/clients/{client_id}", response_model=ClientSchema)
|
||||
async def read_client(client_id: int, db: AsyncSession = Depends(get_db)):
|
||||
db_client = await db.get(ClientModel, client_id)
|
||||
if not db_client:
|
||||
raise HTTPException(status_code=404, detail="Client not found")
|
||||
return db_client
|
||||
|
||||
# PUT: Actualizar cliente
|
||||
@router.put("/clients/{client_id}", response_model=ClientSchema)
|
||||
async def update_client(client_id: int, client: ClientUpdate, db: AsyncSession = Depends(get_db)):
|
||||
db_client = await db.get(ClientModel, client_id)
|
||||
if not db_client:
|
||||
raise HTTPException(status_code=404, detail="Client not found")
|
||||
|
||||
for key, value in client.dict(exclude_unset=True).items():
|
||||
setattr(db_client, key, value)
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(db_client)
|
||||
return db_client
|
||||
|
||||
# DELETE: Borrar cliente
|
||||
@router.delete("/clients/{client_id}")
|
||||
async def delete_client(client_id: int, db: AsyncSession = Depends(get_db)):
|
||||
db_client = await db.get(ClientModel, client_id)
|
||||
if not db_client:
|
||||
raise HTTPException(status_code=404, detail="Client not found")
|
||||
|
||||
await db.delete(db_client)
|
||||
await db.commit()
|
||||
return {"message": "Client deleted successfully"}
|
||||
Reference in New Issue
Block a user