72 lines
2.2 KiB
Python
72 lines
2.2 KiB
Python
from fastapi import APIRouter, HTTPException, status, Depends
|
|
from sqlalchemy.orm import Session
|
|
from typing import List
|
|
from app.schemas import ContactPerson, ContactPersonCreate, ContactPersonUpdate
|
|
from app.models import ContactPerson as ContactPersonModel
|
|
from app.dependencies import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
# Existing routes
|
|
@router.get("/", response_model=List[ContactPerson])
|
|
async def get_contacts(db: Session = Depends(get_db)):
|
|
return db.query(ContactPersonModel).all()
|
|
|
|
|
|
@router.post("/", response_model=ContactPerson, status_code=status.HTTP_201_CREATED)
|
|
async def create_contact(contact: ContactPersonCreate, db: Session = Depends(get_db)):
|
|
if (
|
|
db.query(ContactPersonModel)
|
|
.filter(ContactPersonModel.email == contact.email)
|
|
.first()
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="This contact already exists.",
|
|
)
|
|
|
|
db_contact = ContactPersonModel(
|
|
firstname=contact.firstname,
|
|
lastname=contact.lastname,
|
|
phone_number=contact.phone_number,
|
|
email=contact.email,
|
|
)
|
|
db.add(db_contact)
|
|
db.commit()
|
|
db.refresh(db_contact)
|
|
return db_contact
|
|
|
|
|
|
# New routes
|
|
@router.put("/{contact_id}", response_model=ContactPerson)
|
|
async def update_contact(
|
|
contact_id: int, contact: ContactPersonUpdate, db: Session = Depends(get_db)
|
|
):
|
|
db_contact = (
|
|
db.query(ContactPersonModel).filter(ContactPersonModel.id == contact_id).first()
|
|
)
|
|
if not db_contact:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND, detail="Contact not found."
|
|
)
|
|
for key, value in contact.dict(exclude_unset=True).items():
|
|
setattr(db_contact, key, value)
|
|
db.commit()
|
|
db.refresh(db_contact)
|
|
return db_contact
|
|
|
|
|
|
@router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
async def delete_contact(contact_id: int, db: Session = Depends(get_db)):
|
|
db_contact = (
|
|
db.query(ContactPersonModel).filter(ContactPersonModel.id == contact_id).first()
|
|
)
|
|
if not db_contact:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND, detail="Contact not found."
|
|
)
|
|
db.delete(db_contact)
|
|
db.commit()
|
|
return
|