Skip to content

Automatically create a Type class from a Document #7

@njncalub

Description

@njncalub

Is your feature request related to a problem? Please describe.

I want to automatically map mongoengine fields to appropriate validators during serialization.

Describe the solution you'd like

Maybe we can create a DocumentType class that can be inherited that we can inherit from, similar to Django ModelForms.

from apistar_mongoengine.models import Document, DocumentType
from mongoengine.fields import (
    BooleanField, DateTimeField, DecimalField, IntField, ObjectIdField,
    StringField, URLField, UUIDField
)


class SampleModel(Document):
    sample_objectid = ObjectIdField()
    sample_boolean = BooleanField()
    sample_datetime = DateTimeField()
    sample_decimal = DecimalField()
    sample_int = IntField()
    sample_url = URLField()
    sample_uuid = UUIDField()
    sample_string = StringField()


class SampleOutputType(DocumentType):
    model = SampleModel


class SampleModelInputType(DocumentType):
    model = SampleModel
    
    exclude = (
        'sample_objectid',
    )


def get_object(object_id: str) -> SampleOutputType:
    instance = SampleModel.objects(sample_objectid=object_id).first_or_404()
    
    return SampleOutputType(instance)

Describe alternatives you've considered

Maybe we can also define the input_type and output_type at the Document itself:

class SampleOutputType(DocumentType):
    exclude = (
        'sample_objectid',
    )


class SampleModel(Document):
    sample_string = StringField()
    
    # explicitly set `input_type` or `output_type`
    output_type = SampleOutputType


def get_object(object_id: str) -> SampleModel.OutputType:
    instance = SampleModel.objects(sample_objectid=object_id).first_or_404()
    
    return instance.serialize_output()

Additional context

fields.ObjectIdField will map to validators.String, and so on.

Checklist:

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions