Coverage for apps/kwai-api/src/kwai_api/v1/trainings/coaches/presenters.py: 100%
25 statements
« prev ^ index » next coverage.py v7.11.0, created at 2024-01-01 00:00 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2024-01-01 00:00 +0000
1"""Module that defines presenters for the trainings/coaches endpoints."""
3from typing import Self
5from kwai_bc_training.coaches.coach import CoachEntity
6from kwai_bc_training.trainings.training import TrainingEntity
7from kwai_core.domain.presenter import AsyncPresenter, IterableResult, Presenter
8from kwai_core.json_api import JsonApiPresenter, Meta, Relationship
10from kwai_api.schemas.resources import CoachResourceIdentifier
11from kwai_api.v1.trainings.coaches.schemas import (
12 CoachAttributes,
13 CoachDocument,
14 CoachesDocument,
15 CoachResource,
16 TrainingCoachAttributes,
17 TrainingCoachesDocument,
18 TrainingCoachRelationships,
19 TrainingCoachResource,
20)
23class JsonApiCoachPresenter(JsonApiPresenter[CoachDocument], Presenter[CoachEntity]):
24 """A presenter that transforms an iterable of coaches into a JSON:API document."""
26 def present(self, coach: CoachEntity) -> Self:
27 self._document = CoachDocument(
28 data=CoachResource(
29 id=str(coach.uuid),
30 attributes=CoachAttributes(
31 name=str(coach.name),
32 ),
33 )
34 )
35 return self
38class JsonApiCoachesPresenter(
39 JsonApiPresenter[CoachesDocument], AsyncPresenter[IterableResult[CoachEntity]]
40):
41 """A presenter that transforms an iterable of coaches into a JSON:API document."""
43 async def present(self, result: IterableResult[CoachEntity]) -> Self:
44 self._document = CoachesDocument(
45 meta=Meta(count=result.count, offset=result.offset, limit=result.limit)
46 )
47 async for coach in result.iterator:
48 self._document.data.append(
49 CoachResource(
50 id=str(coach.uuid),
51 attributes=CoachAttributes(name=str(coach.name)),
52 )
53 )
54 return self
57class JsonApiTrainingCoachesPresenter(
58 JsonApiPresenter[TrainingCoachesDocument],
59 Presenter[TrainingEntity],
60):
61 """A presenter that transforms an iterable of coaches of a training into a JSON:API document."""
63 def present(self, result: TrainingEntity) -> Self:
64 self._document = TrainingCoachesDocument(meta=Meta(count=len(result.coaches)))
65 for training_coach in result.coaches:
66 self._document.data.append(
67 TrainingCoachResource(
68 id=str(training_coach.id),
69 attributes=TrainingCoachAttributes(
70 payed=training_coach.payed,
71 present=training_coach.present,
72 head=training_coach.type == 1,
73 remark=training_coach.remark,
74 ),
75 relationships=TrainingCoachRelationships(
76 coach=Relationship[CoachResourceIdentifier](
77 data=CoachResourceIdentifier(
78 id=str(training_coach.coach.uuid)
79 )
80 )
81 ),
82 )
83 )
84 coach_document = (
85 JsonApiCoachPresenter().present(training_coach.coach).get_document()
86 )
87 self._document.included |= {coach_document.data}
88 return self