Coverage for bc/kwai-bc-portal/src/kwai_bc_portal/get_news_items.py: 91%

33 statements  

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

1"""Implement the use case: get news items.""" 

2 

3from dataclasses import dataclass 

4 

5from kwai_core.domain.presenter import AsyncPresenter, IterableResult 

6from kwai_core.domain.value_objects.unique_id import UniqueId 

7 

8from kwai_bc_portal.domain.news_item import NewsItemEntity 

9from kwai_bc_portal.news.news_item_repository import NewsItemRepository 

10 

11 

12@dataclass(kw_only=True, frozen=True, slots=True) 

13class GetNewsItemsCommand: 

14 """Input for use case: [GetNewsItems][kwai.modules.news.get_news_items.GetNewsItems]. 

15 

16 Attributes: 

17 offset: Offset to use. Default is None. 

18 limit: The max. number of elements to return. Default is None, which means all. 

19 enabled: When False, also news items that are not activated will be returned. 

20 """ 

21 

22 offset: int = 0 

23 limit: int = 0 

24 enabled: bool = True 

25 publish_year: int = 0 

26 publish_month: int = 0 

27 application: int | str | None = None 

28 promoted: bool = False 

29 author_uuid: str | None = None 

30 

31 

32class GetNewsItems: 

33 """Implementation of the use case. 

34 

35 Use this use case for getting news items. 

36 """ 

37 

38 def __init__( 

39 self, 

40 repo: NewsItemRepository, 

41 presenter: AsyncPresenter[IterableResult[NewsItemEntity]], 

42 ): 

43 """Initialize the use case. 

44 

45 Args: 

46 repo: A repository for getting the news items. 

47 presenter: The presenter for news items. 

48 """ 

49 self._repo = repo 

50 self._presenter = presenter 

51 

52 async def execute(self, command: GetNewsItemsCommand): 

53 """Execute the use case. 

54 

55 Args: 

56 command: The input for this use case. 

57 """ 

58 query = self._repo.create_query() 

59 

60 if command.enabled: 

61 query.filter_by_active() 

62 

63 if command.publish_year > 0: 

64 query.filter_by_publication_date( 

65 command.publish_year, command.publish_month 

66 ) 

67 

68 if command.promoted: 

69 query.filter_by_promoted() 

70 

71 if command.application is not None: 

72 query.filter_by_application(command.application) 

73 

74 if command.author_uuid is not None: 

75 query.filter_by_user(UniqueId.create_from_string(command.author_uuid)) 

76 

77 query.order_by_publication_date() 

78 

79 await self._presenter.present( 

80 IterableResult( 

81 count=await query.count(), 

82 limit=command.limit, 

83 offset=command.offset, 

84 iterator=self._repo.get_all( 

85 query=query, offset=command.offset, limit=command.limit 

86 ), 

87 ) 

88 )