69 lines
2.1 KiB
Python
69 lines
2.1 KiB
Python
"""Request bodies from the lab 1 contract."""
|
|
|
|
from uuid import UUID
|
|
|
|
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
|
|
|
|
class StrictBody(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", strict=True)
|
|
|
|
|
|
class CreateUser(StrictBody):
|
|
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)
|
|
|
|
@field_validator("display_name")
|
|
@classmethod
|
|
def nonblank_name(cls, value: str) -> str:
|
|
if not value.strip():
|
|
raise ValueError("blank display name")
|
|
return value
|
|
|
|
@field_validator("password")
|
|
@classmethod
|
|
def nonblank_password(cls, value: str) -> str:
|
|
if not value.strip():
|
|
raise ValueError("blank password")
|
|
return value
|
|
|
|
|
|
class CreateChat(StrictBody):
|
|
title: str = Field(min_length=1, max_length=100)
|
|
member_ids: list[str] = Field(min_length=1, max_length=100)
|
|
|
|
@field_validator("title")
|
|
@classmethod
|
|
def nonblank_title(cls, value: str) -> str:
|
|
if not value.strip():
|
|
raise ValueError("blank title")
|
|
return value
|
|
|
|
@field_validator("member_ids")
|
|
@classmethod
|
|
def valid_members(cls, value: list[str]) -> list[str]:
|
|
members = [str(UUID(member_id)) for member_id in value]
|
|
if len(set(members)) != len(members):
|
|
raise ValueError("duplicate member")
|
|
return members
|
|
|
|
|
|
class CreateMessage(StrictBody):
|
|
text: str = Field(max_length=4000)
|
|
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
|
|
|
|
@field_validator("attachment_ids")
|
|
@classmethod
|
|
def valid_attachments(cls, value: list[str]) -> list[str]:
|
|
ids = [str(UUID(item)) for item in value]
|
|
if len(set(ids)) != len(ids):
|
|
raise ValueError("duplicate attachment")
|
|
return ids
|
|
|
|
@model_validator(mode="after")
|
|
def text_or_attachment(self):
|
|
if not self.text.strip() and not self.attachment_ids:
|
|
raise ValueError("message needs text or attachment")
|
|
return self
|