Skip to content

Commit

Permalink
Add database interface and in-memory database infrastructure
Browse files Browse the repository at this point in the history
  • Loading branch information
dmb225 committed Oct 4, 2024
1 parent a412d73 commit e2ca1fd
Show file tree
Hide file tree
Showing 9 changed files with 78 additions and 31 deletions.
31 changes: 0 additions & 31 deletions pyproject.toml

This file was deleted.

20 changes: 20 additions & 0 deletions src/application/entities/user.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass, field
from typing import Any, Self
from uuid import UUID, uuid4


Expand All @@ -9,3 +10,22 @@ class User:
password: str
confirmed: bool
id: UUID = field(default_factory=uuid4)

def to_dict(self) -> dict[str, Any]:
return {
"id": str(self.id),
"name": self.name,
"email": self.email,
"password": self.password,
"confirmed": self.confirmed,
}

@classmethod
def from_dict(cls, data: dict[str, Any]) -> Self:
return cls(
id=UUID(data["id"]),
name=data["name"],
email=data["email"],
password=data["password"],
confirmed=data["confirmed"],
)
Empty file.
32 changes: 32 additions & 0 deletions src/application/interfaces/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from abc import ABC, abstractmethod
from typing import Generic, Protocol, TypeVar, Optional
from uuid import UUID


class HasID(Protocol):
id: UUID # Enforce that any entity passed to the repository must have an `id` attribute


T = TypeVar("T", bound=HasID)


class Database(ABC, Generic[T]):
@abstractmethod
async def add(self, entity: T) -> None:
pass

@abstractmethod
async def get(self, id: UUID) -> Optional[T]:
pass

@abstractmethod
async def update(self, entity: T) -> None:
pass

@abstractmethod
async def delete(self, id: UUID) -> None:
pass

@abstractmethod
async def list_all(self) -> list[T]:
pass
Empty file added src/infrastructure/__init__.py
Empty file.
Empty file.
26 changes: 26 additions & 0 deletions src/infrastructure/databases/in_memory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from typing import Optional
from uuid import UUID

from application.interfaces.database import T, Database


class InMemoryDatabase(Database[T]):
def __init__(self) -> None:
self._data: dict[UUID, T] = {}

async def add(self, entity: T) -> None:
self._data[entity.id] = entity

async def get(self, id: UUID) -> Optional[T]:
return self._data.get(id)

async def update(self, entity: T) -> None:
if entity.id in self._data:
self._data[entity.id] = entity

async def delete(self, id: UUID) -> None:
if id in self._data:
del self._data[id]

async def list_all(self) -> list[T]:
return list(self._data.values())
Empty file.
Empty file.

0 comments on commit e2ca1fd

Please sign in to comment.