-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodels.py
68 lines (58 loc) · 2.02 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from typing import Any, Optional
import phonenumbers
from bson import ObjectId
from pydantic import BaseModel, field_validator
from pydantic_core import core_schema
# for handling mongo ObjectIds
class PyObjectId(ObjectId):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler):
return core_schema.union_schema(
[
# check if it's an instance first before doing any further work
core_schema.is_instance_schema(ObjectId),
core_schema.no_info_plain_validator_function(cls.validate),
],
serialization=core_schema.to_string_ser_schema(),
)
@classmethod
def validate(cls, v):
if not ObjectId.is_valid(v):
raise ValueError("Invalid ObjectId")
return ObjectId(v)
@classmethod
def __get_pydantic_json_schema__(cls, field_schema):
field_schema.update(type="string")
# user model
class User(BaseModel):
uid: str
img: Optional[str] = None
role: Optional[str] = "public"
phone: Optional[str] = None
@field_validator("uid", mode="before")
@classmethod
def transform_uid(cls, v):
return v.lower()
@field_validator("role")
@classmethod
def constrain_role(cls, v):
role = v.lower()
if role not in ["public", "club", "cc", "slc", "slo"]:
raise ValueError("Invalid role!")
return role
@field_validator("phone")
@classmethod
def constrain_phone(cls, v):
if v is None or v == "":
return None
try:
phone = phonenumbers.parse(v, "IN")
if not phonenumbers.is_valid_number(phone):
raise ValueError("Invalid phone number!")
return phonenumbers.format_number(
phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL
)
except phonenumbers.phonenumberutil.NumberParseException:
raise ValueError("Invalid phone number!")
except Exception as e:
raise ValueError(str(e))