Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Enum Type for Enum Encoder #166

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions microcosm_postgres/encryption/v2/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import sqlalchemy
from sqlalchemy.dialects.postgresql import ARRAY, JSONB

from microcosm_postgres.types import EnumType


T = TypeVar("T")
JSONType: TypeAlias = (
Expand Down Expand Up @@ -196,20 +198,26 @@ def decode(self, value: str, **kwargs) -> T | None:
E = TypeVar("E", bound=Enum)


class EnumEncoder(Encoder[E], Generic[E]):
class EnumEncoder(Encoder[E | None], Generic[E]):
"""
Encodes and decodes an enum by its name.

"""
sa_type = sqlalchemy.String

def __init__(self, enum: type[E]):
self.sa_type = EnumType(enum)
self._enum = enum

@encode_exception_wrapper
def encode(self, value: E, **kwargs) -> str:
return value.name
def encode(self, value: E | None, **kwargs) -> str:
if value is not None:
return value.name
else:
return "None"

@decode_exception_wrapper
def decode(self, value: str, **kwargs) -> E:
return self._enum[value]
def decode(self, value: str, **kwargs) -> E | None:
if value == "None":
return None
else:
return self._enum[value]