90 lines
2.2 KiB
Python
90 lines
2.2 KiB
Python
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
from pydantic import model_validator
|
|
import uuid
|
|
|
|
|
|
def not_blank(value: str) -> str:
|
|
if not value.strip():
|
|
raise ValueError("must not be blank")
|
|
return value
|
|
|
|
|
|
class RequestModel(BaseModel):
|
|
# Лишние поля и неверные типы в JSON -> 400
|
|
model_config = ConfigDict(extra="forbid", strict=True)
|
|
|
|
|
|
# ---------- Запросы ----------
|
|
|
|
class CreateUser(RequestModel):
|
|
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
|
display_name: str = Field(min_length=1, max_length=100)
|
|
password: str = Field(min_length=12, max_length=128)
|
|
|
|
_display_name_not_blank = field_validator("display_name")(not_blank)
|
|
_password_not_blank = field_validator("password")(not_blank)
|
|
|
|
|
|
class CreateChat(RequestModel):
|
|
title: str = Field(min_length=1, max_length=100)
|
|
member_ids: list[str] = Field(min_length=1, max_length=100)
|
|
|
|
_title_not_blank = field_validator("title")(not_blank)
|
|
|
|
|
|
class CreateMessage(RequestModel):
|
|
text: str = Field(max_length=4000)
|
|
|
|
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
|
|
|
|
@model_validator(mode="after")
|
|
def validate_message(self):
|
|
self.attachment_ids = [str(uuid.UUID(value)) for value in self.attachment_ids]
|
|
if len(set(self.attachment_ids)) != len(self.attachment_ids):
|
|
raise ValueError("duplicate attachment")
|
|
if not self.text.strip() and not self.attachment_ids:
|
|
raise ValueError("message is empty")
|
|
return self
|
|
|
|
|
|
# ---------- Ответы ----------
|
|
|
|
class User(BaseModel):
|
|
id: str
|
|
username: str
|
|
display_name: str
|
|
created_at: str
|
|
|
|
|
|
class Session(BaseModel):
|
|
token: str
|
|
token_type: str = "Bearer"
|
|
expires_at: str
|
|
user: User
|
|
|
|
|
|
class Chat(BaseModel):
|
|
id: str
|
|
title: str
|
|
member_ids: list[str]
|
|
created_at: str
|
|
|
|
|
|
class ChatPage(BaseModel):
|
|
items: list[Chat]
|
|
next_cursor: str | None
|
|
|
|
|
|
class Message(BaseModel):
|
|
attachment_ids: list[str]
|
|
id: str
|
|
chat_id: str
|
|
sender_id: str
|
|
text: str
|
|
created_at: str
|
|
|
|
|
|
class MessagePage(BaseModel):
|
|
items: list[Message]
|
|
next_cursor: str | None
|