Skip to content

Commit

Permalink
Fix: remove aliases for id field everywhere (#63)
Browse files Browse the repository at this point in the history
* fix: remove aliases for id field everywhere

* fix: fix response serialize
  • Loading branch information
Spotika authored Sep 20, 2024
1 parent 713b634 commit 114266b
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/db/methods/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ def insert_user_with_id(user: types.UserWithoutID) -> int | None:
Inserted user id or None, if error occurred
"""
try:
return insert_with_auto_increment_id(users, user.model_dump())
return insert_with_auto_increment_id(users, user.db_dump())
except DuplicateKeyError:
return None
5 changes: 2 additions & 3 deletions src/db/types/types.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import Literal
from pydantic import Field

from utils.schemas import BaseModel

Expand All @@ -13,7 +12,7 @@ class JWTPair(BaseModel):


class Entity(BaseModel):
id: str = Field(alias="_id")
id: str
target_type: EntityTargetType
target_id: int

Expand All @@ -31,4 +30,4 @@ class UserWithoutID(_UserBase): ...


class User(_UserBase):
id: int = Field(alias="_id")
id: int
13 changes: 11 additions & 2 deletions src/utils/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,14 @@


class BaseModel(pydantic.BaseModel):
def model_dump(self, by_alias=True, **kwargs) -> dict[str, Any]:
return super().model_dump(by_alias=by_alias, **kwargs)
def db_dump(self, by_alias=True, **kwargs) -> dict[str, Any]:
result = self.model_dump(by_alias=by_alias, **kwargs)
if "id" in result:
result["_id"] = result.pop("id")
return result

@pydantic.model_validator(mode="before")
def convert_id(cls, values):
if "_id" in values:
values["id"] = str(values.pop("_id"))
return values

0 comments on commit 114266b

Please sign in to comment.