From 1628c3a019866caae54d89058bc812ec91be2bc1 Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Mon, 30 Nov 2020 20:01:26 +0200 Subject: Create model for form question --- backend/models/question.py | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 backend/models/question.py (limited to 'backend') 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 -- cgit v1.2.3