Skip to content

Commit

Permalink
Merge pull request #36 from CorrelAid/feature/backend-project-crud
Browse files Browse the repository at this point in the history
added simple project crud
  • Loading branch information
KonradUdoHannes authored Jul 28, 2023
2 parents ab61ae5 + 069219e commit 3dd019a
Show file tree
Hide file tree
Showing 13 changed files with 540 additions and 12 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,6 @@ migrate:

stop-test-db:
docker compose down

lint-backend:
cd backend && poetry run pre-commit run -c ../.pre-commit-config.yaml
124 changes: 123 additions & 1 deletion backend/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ black = "^23.1.0"
pre-commit = "^3.1.1"
pytest = "^7.4.0"
pytest-asyncio = "^0.21.1"
requests = "^2.31.0"

[tool.pytest.ini_options]
asyncio_mode="auto"
Expand Down
3 changes: 2 additions & 1 deletion backend/src/api/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Annotated

from api.auth.users import current_active_user
from api.routers import auth
from api.routers import auth, projects
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from models.user import User
Expand All @@ -18,6 +18,7 @@
)

app.include_router(router=auth.router)
app.include_router(router=projects.router, prefix="/projects", tags=["projects"])


@app.get("/authenticated-route")
Expand Down
145 changes: 145 additions & 0 deletions backend/src/api/routers/projects.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import uuid
from typing import Annotated

from api.auth.users import current_active_user
from database.session import transactional_session
from fastapi import APIRouter, Depends, HTTPException, status
from models.project import Project
from pydantic import BaseModel, ConfigDict, TypeAdapter
from sqlalchemy import select
from sqlalchemy.exc import NoResultFound
from sqlalchemy.ext.asyncio import AsyncSession

router = APIRouter()


class ReadProject(BaseModel):
model_config = ConfigDict(from_attributes=True)

id: uuid.UUID
title: str
summary: str | None = None
status: str


class CreateProject(BaseModel):
title: str
summary: str | None = None
status: str


class UpdateProject(BaseModel):
title: str | None = None
summary: str | None = None
status: str | None = None


class ProjectStore:
def __init__(
self, session: Annotated[AsyncSession, Depends(transactional_session)]
):
self.session = session

async def _get_orm_project(self, project_id: uuid.UUID) -> Project:
try:
project_entry = (
await self.session.execute(select(Project).filter_by(id=project_id))
).scalar_one()
except NoResultFound:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return project_entry

async def get(self, project_id: uuid.UUID) -> ReadProject:
project_entry = await self._get_orm_project(project_id)
return TypeAdapter(ReadProject).validate_python(project_entry)

async def get_all(self) -> list[ReadProject]:
stmt = select(Project)
projects = (await self.session.scalars(stmt)).all()
return TypeAdapter(list[ReadProject]).validate_python(projects)

async def create(self, project: CreateProject) -> ReadProject:
new_project = Project(id=uuid.uuid4(), **project.model_dump())
self.session.add(new_project)
return TypeAdapter(ReadProject).validate_python(new_project)

async def delete(self, project_id: uuid.UUID) -> None:
project_entry = await self._get_orm_project(project_id)
await self.session.delete(project_entry)
return None

async def update(
self, project_id: uuid.UUID, project: UpdateProject
) -> ReadProject:
project_entry = await self._get_orm_project(project_id)
for key, value in project.model_dump(exclude_defaults=True).items():
if getattr(project_entry, key) != value:
setattr(project_entry, key, value)
return TypeAdapter(ReadProject).validate_python(project_entry)


@router.get(
"/",
response_description="List all projects",
dependencies=[Depends(current_active_user)],
)
async def list_projects(
project_store: Annotated[ProjectStore, Depends()],
) -> list[ReadProject]:
projects = await project_store.get_all()
return projects


@router.post(
"/",
response_description="Create a new project",
status_code=status.HTTP_201_CREATED,
dependencies=[Depends(current_active_user)],
)
async def create_project(
project: CreateProject,
project_store: Annotated[ProjectStore, Depends()],
) -> ReadProject:
new_project = await project_store.create(project)
return new_project


@router.get(
"/{project_id}",
response_description="Get a single project",
dependencies=[Depends(current_active_user)],
)
async def read_project(
project_id: uuid.UUID,
project_store: Annotated[ProjectStore, Depends()],
) -> ReadProject:
project_entry = await project_store.get(project_id)
return project_entry


@router.delete(
"/{project_id}",
response_description="Delete a single project",
dependencies=[Depends(current_active_user)],
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_project(
project_id: uuid.UUID,
project_store: Annotated[ProjectStore, Depends()],
) -> None:
await project_store.delete(project_id)
return None


@router.patch(
"/{project_id}",
response_description="Update a single project",
dependencies=[Depends(current_active_user)],
)
async def update_project(
project_id: uuid.UUID,
project: UpdateProject,
project_store: Annotated[ProjectStore, Depends()],
) -> ReadProject:
project_entry = await project_store.update(project_id, project)
return project_entry
Loading

0 comments on commit 3dd019a

Please sign in to comment.