|
| 1 | +from datetime import datetime |
| 2 | +from . import schemas, models |
| 3 | +from sqlalchemy.orm import Session |
| 4 | +from fastapi import Depends, HTTPException, status, APIRouter, Response |
| 5 | +from .database import get_db |
| 6 | + |
| 7 | +router = APIRouter() |
| 8 | + |
| 9 | + |
| 10 | +@router.get('/') |
| 11 | +def get_notes(db: Session = Depends(get_db), limit: int = 10, page: int = 1, search: str = ''): |
| 12 | + skip = (page - 1) * limit |
| 13 | + |
| 14 | + notes = db.query(models.Note).group_by(models.Note.id).filter( |
| 15 | + models.Note.title.contains(search)).limit(limit).offset(skip).all() |
| 16 | + return {'status': 'success', 'results': len(notes), 'notes': notes} |
| 17 | + |
| 18 | + |
| 19 | +@router.post('/', status_code=status.HTTP_201_CREATED) |
| 20 | +def create_note(payload: schemas.NoteBaseSchema, db: Session = Depends(get_db)): |
| 21 | + new_note = models.Note(**payload.dict()) |
| 22 | + db.add(new_note) |
| 23 | + db.commit() |
| 24 | + db.refresh(new_note) |
| 25 | + return {"status": "success", "note": new_note} |
| 26 | + |
| 27 | + |
| 28 | +@router.patch('/{noteId}') |
| 29 | +def update_note(noteId: str, payload: schemas.NoteBaseSchema, db: Session = Depends(get_db)): |
| 30 | + note_query = db.query(models.Note).filter(models.Note.id == noteId) |
| 31 | + db_note = note_query.first() |
| 32 | + |
| 33 | + if not db_note: |
| 34 | + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, |
| 35 | + detail=f'No note with this id: {id} found') |
| 36 | + update_data = payload.dict(exclude_unset=True) |
| 37 | + # Work Here |
| 38 | + note_query.update(db_note, |
| 39 | + synchronize_session=False) |
| 40 | + db.commit() |
| 41 | + return {"status": "success", "note": db_note} |
| 42 | + |
| 43 | + |
| 44 | +@router.get('/{noteId}') |
| 45 | +def get_post(noteId: str, db: Session = Depends(get_db)): |
| 46 | + note = db.query(models.Note).filter(models.Note.id == noteId).first() |
| 47 | + if not note: |
| 48 | + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, |
| 49 | + detail=f"No note with this id: {id} found") |
| 50 | + return {"status": "success", "note": note} |
| 51 | + |
| 52 | + |
| 53 | +@router.delete('/{noteId}') |
| 54 | +def delete_post(noteId: str, db: Session = Depends(get_db)): |
| 55 | + note_query = db.query(models.Note).filter(models.Note.id == noteId) |
| 56 | + note = note_query.first() |
| 57 | + if not note: |
| 58 | + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, |
| 59 | + detail=f'No note with this id: {id} found') |
| 60 | + note_query.delete(synchronize_session=False) |
| 61 | + db.commit() |
| 62 | + return Response(status_code=status.HTTP_204_NO_CONTENT) |
0 commit comments