Initial commit
This commit is contained in:
77
app/api/routes/clientes.py
Normal file
77
app/api/routes/clientes.py
Normal file
@@ -0,0 +1,77 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from prisma import Prisma
|
||||
from typing import List
|
||||
from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse
|
||||
from app.api.dependencies import get_prisma
|
||||
|
||||
router = APIRouter(prefix="/clientes", tags=["clientes"])
|
||||
|
||||
|
||||
@router.get("/", response_model=List[ClienteResponse])
|
||||
async def listar_clientes(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Prisma = Depends(get_prisma)
|
||||
):
|
||||
"""Listar todos los clientes"""
|
||||
clientes = await db.cliente.find_many(skip=skip, take=limit)
|
||||
return clientes
|
||||
|
||||
|
||||
@router.get("/{cliente_id}", response_model=ClienteResponse)
|
||||
async def obtener_cliente(
|
||||
cliente_id: int,
|
||||
db: Prisma = Depends(get_prisma)
|
||||
):
|
||||
"""Obtener un cliente por ID"""
|
||||
cliente = await db.cliente.find_unique(where={"id": cliente_id})
|
||||
if not cliente:
|
||||
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
||||
return cliente
|
||||
|
||||
|
||||
@router.post("/", response_model=ClienteResponse, status_code=201)
|
||||
async def crear_cliente(
|
||||
cliente: ClienteCreate,
|
||||
db: Prisma = Depends(get_prisma)
|
||||
):
|
||||
"""Crear un nuevo cliente"""
|
||||
try:
|
||||
nuevo_cliente = await db.cliente.create(data=cliente.dict())
|
||||
return nuevo_cliente
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/{cliente_id}", response_model=ClienteResponse)
|
||||
async def actualizar_cliente(
|
||||
cliente_id: int,
|
||||
cliente: ClienteUpdate,
|
||||
db: Prisma = Depends(get_prisma)
|
||||
):
|
||||
"""Actualizar un cliente"""
|
||||
cliente_existente = await db.cliente.find_unique(where={"id": cliente_id})
|
||||
if not cliente_existente:
|
||||
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
||||
|
||||
data = {k: v for k, v in cliente.dict().items() if v is not None}
|
||||
cliente_actualizado = await db.cliente.update(
|
||||
where={"id": cliente_id},
|
||||
data=data
|
||||
)
|
||||
return cliente_actualizado
|
||||
|
||||
|
||||
@router.delete("/{cliente_id}", status_code=204)
|
||||
async def eliminar_cliente(
|
||||
cliente_id: int,
|
||||
db: Prisma = Depends(get_prisma)
|
||||
):
|
||||
"""Eliminar un cliente"""
|
||||
cliente = await db.cliente.find_unique(where={"id": cliente_id})
|
||||
if not cliente:
|
||||
raise HTTPException(status_code=404, detail="Cliente no encontrado")
|
||||
|
||||
await db.cliente.delete(where={"id": cliente_id})
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user