odmantic icon indicating copy to clipboard operation
odmantic copied to clipboard

__bson__ serialization does not work when Optional / Union used with Custom Types

Open nikhildigde opened this issue 9 months ago • 0 comments

Bug

A clear and concise description of what the bug is. I have a requirement to create a custom type and implement the bson ser method. It works well when used normally, but if used with an Optional / Union , it dosent work. In this case, the internal logic considers the field type as a Union.

Current Behavior

... Steps to reproduce the bug ... `class EncryptedString(str):

@classmethod
def __get_validators__(cls):
    yield cls.validate

@classmethod
def validate(cls, v):
    if isinstance(v, bytes):
        return v.decode("utf-8")
    if not isinstance(v, str): 
        raise TypeError("Only string type is allowed")
     
    return v

@classmethod
def __bson__(cls, v) -> str:
    encrypted_data = v.encode("utf-8")
    return encrypted_data

class Model1(EmbeddedModel): key1: Optional[EncryptedString] = None # DOSNT WORK

class EncryptedModel(Model): encrypted_field: EncryptedString #WORKS WELL embedded_model: List[Union[Model1]] = [] #DOSNT WORK non_list_union: Model1`

Expected behavior

... A clear and concise description of what you expected to happen. ...

I expect the bson method to be invoked in every case for a custom type

Environment

  • ODMantic version: 0.9.2
...
  • Version of additional modules (if relevant):
    • ...

Additional context

Add any other context about the problem here.

nikhildigde avatar May 16 '24 04:05 nikhildigde