diff options
| author | 2020-11-30 20:01:26 +0200 | |
|---|---|---|
| committer | 2020-11-30 20:01:26 +0200 | |
| commit | 1628c3a019866caae54d89058bc812ec91be2bc1 (patch) | |
| tree | bf4875187410c127c6cd952efa4c89572fd2cc95 /backend/models | |
| parent | Add question types data requirements to constants (diff) | |
Create model for form question
Diffstat (limited to 'backend/models')
| -rw-r--r-- | backend/models/question.py | 55 | 
1 files changed, 55 insertions, 0 deletions
diff --git a/backend/models/question.py b/backend/models/question.py new file mode 100644 index 0000000..ac585f9 --- /dev/null +++ b/backend/models/question.py @@ -0,0 +1,55 @@ +import typing as t + +from pydantic import BaseModel, Field, validator + +from backend.constants import QUESTION_TYPES, REQUIRED_QUESTION_TYPE_DATA +from backend.models.types import ObjectId + + +class Question(BaseModel): +    """Schema model for form question.""" + +    id: ObjectId = Field(alias="_id") +    name: str +    type: str +    data: t.Dict[str, t.Any] + +    @validator("type", pre=True) +    def validate_question_type(self, value: str) -> t.Optional[str]: +        """Checks if question type in currently allowed types list.""" +        value = value.lower() +        if value not in QUESTION_TYPES: +            raise ValueError( +                f"{value} is not valid question type. " +                f"Allowed question types: {QUESTION_TYPES}." +            ) + +        return value + +    @validator("data") +    def validate_question_data( +            self, +            value: t.Dict[str, t.Any] +    ) -> t.Optional[t.Dict[str, t.Any]]: +        """Check does required data exists for question type and remove other data.""" +        # When question type don't need data, don't add anything to keep DB clean. +        if self.type not in REQUIRED_QUESTION_TYPE_DATA: +            return {} + +        # Required keys (and values) will be stored to here +        # to remove all unnecessary stuff +        result = {} + +        for key, data_type in REQUIRED_QUESTION_TYPE_DATA[self.type].items(): +            if key not in value: +                raise ValueError(f"Required question data key '{key}' not provided.") + +            if not isinstance(value[key], data_type): +                raise ValueError( +                    f"Question data key '{key}' expects {data_type.__name__}, " +                    f"got {type(value[key]).__name__} instead." +                ) + +            result[key] = value[key] + +        return result  |