Coverage for src/kwai/api/v1/club/schemas/person.py: 100%
30 statements
« prev ^ index » next coverage.py v7.6.10, created at 2024-01-01 00:00 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2024-01-01 00:00 +0000
1"""Module for defining the JSON:API resource for a person."""
3from typing import Annotated, Self
5from pydantic import BaseModel, Field
7from kwai.api.v1.club.schemas.contact import ContactDocument, ContactResource
8from kwai.api.v1.club.schemas.resources import (
9 ContactResourceIdentifier,
10 PersonResourceIdentifier,
11)
12from kwai.api.v1.resources import CountryResourceIdentifier
13from kwai.api.v1.schemas import CountryDocument, CountryResource
14from kwai.core.json_api import Document, Relationship, ResourceData, ResourceMeta
15from kwai.modules.club.domain.person import PersonEntity
18class PersonAttributes(BaseModel):
19 """Attributes for the person JSON:API resource."""
21 first_name: str
22 last_name: str
23 gender: int
24 birthdate: str
25 remark: str
28class PersonRelationships(BaseModel):
29 """Relationships of a person JSON:API resource."""
31 contact: Relationship[ContactResourceIdentifier]
32 nationality: Relationship[CountryResourceIdentifier]
35class PersonResource(
36 PersonResourceIdentifier, ResourceData[PersonAttributes, PersonRelationships]
37):
38 """A JSON:API resource for a person."""
41PersonInclude = Annotated[
42 ContactResource | CountryResource, Field(discriminator="type")
43]
46class PersonDocument(Document[PersonResource, PersonInclude]):
47 """A JSON:API document for one ore more persons."""
49 @classmethod
50 def create(cls, person: PersonEntity) -> Self:
51 """Create a person document from a person entity."""
52 country_document = CountryDocument.create(person.nationality)
53 contact_document = ContactDocument.create(person.contact)
55 person_resource = PersonResource(
56 id=str(person.id),
57 attributes=PersonAttributes(
58 first_name=person.name.first_name,
59 last_name=person.name.last_name,
60 gender=person.gender.value,
61 birthdate=str(person.birthdate),
62 remark=person.remark,
63 ),
64 relationships=PersonRelationships(
65 nationality=Relationship[CountryResourceIdentifier](
66 data=CountryResourceIdentifier(id=country_document.data.id)
67 ),
68 contact=Relationship[ContactResourceIdentifier](
69 data=ContactResourceIdentifier(id=contact_document.data.id)
70 ),
71 ),
72 meta=ResourceMeta(
73 created_at=str(person.traceable_time.created_at),
74 updated_at=str(person.traceable_time.updated_at),
75 ),
76 )
78 included: set[PersonInclude] = set()
79 included.add(country_document.data)
80 included.add(contact_document.data)
81 included = included.union(contact_document.included)
83 return PersonDocument(data=person_resource, included=included)