From 4b9c5a0203f9b7486f76e8b75f3037401256eb3d Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Sun, 26 Mar 2023 03:48:32 +0200 Subject: [PATCH] Support for schema `EnumField`. --- platypush/schemas/__init__.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/platypush/schemas/__init__.py b/platypush/schemas/__init__.py index ce157319b5..6d12ce03e0 100644 --- a/platypush/schemas/__init__.py +++ b/platypush/schemas/__init__.py @@ -1,5 +1,6 @@ from datetime import datetime, date -from typing import Optional, Union +from enum import Enum +from typing import Any, Optional, Type, Union from dateutil.parser import isoparse from dateutil.tz import tzutc @@ -66,6 +67,23 @@ class Date(Function): # lgtm [py/missing-call-to-init] return date.fromtimestamp(dt.timestamp()) +class EnumField(Function): + """ + Field that maps enum values. + """ + + # pylint: disable=redefined-builtin + def __init__(self, *args, type: Type[Enum], **kwargs): + super().__init__(*args, **kwargs) + self.type = type + + def _serialize(self, value: Optional[Enum], *_, **__) -> Optional[Any]: + return value.value if value is not None else None + + def _deserialize(self, value: Optional[Any], *_, **__) -> Optional[Any]: + return self.type(value) if value is not None else None + + def normalize_datetime( dt: Optional[Union[str, date, datetime]] ) -> Optional[Union[date, datetime]]: