Coverage for src/kwai/api/v1/club/presenters.py: 89%

35 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2024-01-01 00:00 +0000

1"""Module that defines presenters for the club api.""" 

2 

3from kwai.api.v1.club.schemas.member import MemberDocument 

4from kwai.core.domain.presenter import AsyncPresenter, IterableResult, Presenter 

5from kwai.core.json_api import Error, ErrorSource, JsonApiPresenter, Meta 

6from kwai.modules.club.domain.member import MemberEntity 

7from kwai.modules.club.import_members import ( 

8 FailureMemberImportResult, 

9 MemberImportResult, 

10 OkMemberImportResult, 

11) 

12 

13 

14class JsonApiMemberPresenter(JsonApiPresenter[MemberDocument], Presenter[MemberEntity]): 

15 """A presenter that transform a member entity into a JSON:API document.""" 

16 

17 def present(self, member: MemberEntity) -> None: 

18 self._document = MemberDocument.create(member) 

19 

20 

21class JsonApiMembersPresenter( 

22 JsonApiPresenter[MemberDocument], AsyncPresenter[IterableResult[MemberEntity]] 

23): 

24 """A presenter that transform an iterator for members into a JSON:API document.""" 

25 

26 async def present(self, result: IterableResult[MemberEntity]) -> None: 

27 self._document = MemberDocument( 

28 meta=Meta(count=result.count, offset=result.offset, limit=result.limit), 

29 data=[], 

30 ) 

31 async for member in result.iterator: 

32 member_document = MemberDocument.create(member) 

33 self._document.merge(member_document) 

34 

35 

36class JsonApiUploadMemberPresenter( 

37 JsonApiPresenter[MemberDocument], Presenter[MemberImportResult] 

38): 

39 """A presenter that transform a file upload of a member into a JSON:API document.""" 

40 

41 def __init__(self) -> None: 

42 super().__init__() 

43 self._document = MemberDocument( 

44 meta=Meta(count=0, offset=0, limit=0), data=[], errors=[] 

45 ) 

46 

47 def present(self, result: MemberImportResult) -> None: 

48 match result: 

49 case OkMemberImportResult(): 

50 member_document = MemberDocument.create(result.member) 

51 member_document.resource.meta.row = result.row 

52 member_document.resource.meta.new = not result.member.has_id() 

53 # A new member has related resources that are not saved yet, 

54 # so give them temporarily the same id as the member. 

55 if member_document.resource.meta.new: 

56 member_document.resource.relationships.person.data.id = ( 

57 member_document.resource.id 

58 ) 

59 for included in member_document.included: 

60 if included.type == "persons": 

61 included.relationships.contact.data.id = ( 

62 member_document.resource.id 

63 ) 

64 if included.id == "0": 

65 included.id = member_document.resource.id 

66 self._document.meta.count += 1 

67 self._document.merge(member_document) 

68 case FailureMemberImportResult(): 

69 self._document.errors.append( 

70 Error( 

71 source=ErrorSource(pointer=str(result.row)), 

72 detail=result.to_message(), 

73 ) 

74 )