Skip to content
This repository has been archived by the owner on Sep 12, 2023. It is now read-only.

Commit

Permalink
feat(repository): __class_getitem__ sets model_type on repo.
Browse files Browse the repository at this point in the history
  • Loading branch information
peterschutt committed Nov 17, 2022
1 parent 7fb352e commit d81e6c6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/starlite_saqlalchemy/repository/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
__all__ = ["AbstractRepository"]

T = TypeVar("T")
RepoT = TypeVar("RepoT", bound="AbstractRepository")


class AbstractRepository(Generic[T], metaclass=ABCMeta):
Expand All @@ -27,6 +28,12 @@ class AbstractRepository(Generic[T], metaclass=ABCMeta):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)

@classmethod
def __class_getitem__(cls: type[RepoT], item: type[T]) -> type[RepoT]:
if not isinstance(item, TypeVar) and not getattr(cls, "model_type", None):
cls.model_type = item
return cls

@abstractmethod
async def add(self, data: T) -> T:
"""Add `data` to the collection.
Expand Down
27 changes: 26 additions & 1 deletion src/starlite_saqlalchemy/repository/types.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,38 @@
"""Repository type definitions."""
from __future__ import annotations

from typing import Any
from typing import TYPE_CHECKING, Any, Protocol, TypeVar

from starlite_saqlalchemy.repository.filters import (
BeforeAfter,
CollectionFilter,
LimitOffset,
)

if TYPE_CHECKING:
from pydantic import BaseModel

FilterTypes = BeforeAfter | CollectionFilter[Any] | LimitOffset
"""Aggregate type alias of the types supported for collection filtering."""


T = TypeVar("T")


class ModelProtocol(Protocol): # pylint: disable=too-few-public-methods
"""Protocol for repository models."""

@classmethod
def from_dto(cls: type[T], dto_instance: BaseModel) -> T: # pragma: no cover
"""
Args:
dto_instance: A pydantic model.
Returns:
Instance of type with values populated from `dto_instance`.
"""
... # pylint: disable=unnecessary-ellipsis


ModelT = TypeVar("ModelT", bound=ModelProtocol)

0 comments on commit d81e6c6

Please sign in to comment.