@amityco/ts-sdk-react-native 6.23.0 → 6.23.1-d5c2fe6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/.env +26 -26
  2. package/dist/@types/core/events.d.ts +5 -0
  3. package/dist/@types/core/events.d.ts.map +1 -1
  4. package/dist/@types/domains/community.d.ts +16 -1
  5. package/dist/@types/domains/community.d.ts.map +1 -1
  6. package/dist/client/api/secureLogout.d.ts +1 -1
  7. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  8. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  9. package/dist/commentRepository/events/utils.d.ts.map +1 -1
  10. package/dist/commentRepository/internalApi/createComment.d.ts.map +1 -1
  11. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  12. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  13. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  14. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  15. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  16. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts +14 -0
  17. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts.map +1 -0
  18. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts +9 -0
  19. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts.map +1 -0
  20. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +15 -0
  21. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -0
  22. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts +10 -0
  23. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts.map +1 -0
  24. package/dist/communityRepository/communityMembership/observers/getMembers.d.ts.map +1 -1
  25. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts +20 -0
  26. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts.map +1 -0
  27. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts +14 -0
  28. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -0
  29. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts +9 -0
  30. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts.map +1 -0
  31. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +15 -0
  32. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -0
  33. package/dist/communityRepository/observers/getCommunities/enums.d.ts +6 -0
  34. package/dist/communityRepository/observers/getCommunities/enums.d.ts.map +1 -0
  35. package/dist/communityRepository/observers/getCommunities.d.ts.map +1 -1
  36. package/dist/communityRepository/observers/index.d.ts +1 -0
  37. package/dist/communityRepository/observers/index.d.ts.map +1 -1
  38. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts +14 -0
  39. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts.map +1 -0
  40. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts +9 -0
  41. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -0
  42. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +15 -0
  43. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -0
  44. package/dist/communityRepository/observers/searchCommunities/enums.d.ts +6 -0
  45. package/dist/communityRepository/observers/searchCommunities/enums.d.ts.map +1 -0
  46. package/dist/communityRepository/observers/searchCommunities.d.ts +20 -0
  47. package/dist/communityRepository/observers/searchCommunities.d.ts.map +1 -0
  48. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  49. package/dist/communityRepository/utils/saveCommunityUsers.d.ts +2 -0
  50. package/dist/communityRepository/utils/saveCommunityUsers.d.ts.map +1 -0
  51. package/dist/core/events.d.ts +3 -3
  52. package/dist/core/events.d.ts.map +1 -1
  53. package/dist/core/liveCollection/LiveCollectionController.d.ts +4 -1
  54. package/dist/core/liveCollection/LiveCollectionController.d.ts.map +1 -1
  55. package/dist/index.cjs.js +1149 -797
  56. package/dist/index.esm.js +1148 -796
  57. package/dist/index.umd.js +4 -4
  58. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts +12 -0
  59. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts.map +1 -0
  60. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts +12 -0
  61. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts.map +1 -0
  62. package/dist/marker/events/onUserFeedMarkerUpdated.d.ts.map +1 -1
  63. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts +1 -1
  64. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts.map +1 -1
  65. package/dist/postRepository/observers/getPost.d.ts.map +1 -1
  66. package/dist/postRepository/observers/getPosts.d.ts.map +1 -1
  67. package/dist/streamRepository/api/getStreams.d.ts +2 -2
  68. package/dist/streamRepository/events/onStreamFlagged.d.ts +17 -0
  69. package/dist/streamRepository/events/onStreamFlagged.d.ts.map +1 -0
  70. package/dist/streamRepository/events/onStreamTerminated.d.ts +17 -0
  71. package/dist/streamRepository/events/onStreamTerminated.d.ts.map +1 -0
  72. package/dist/streamRepository/observers/getStreams.d.ts +1 -1
  73. package/dist/utils/liveObject.d.ts +3 -0
  74. package/dist/utils/liveObject.d.ts.map +1 -1
  75. package/package.json +1 -1
  76. package/src/@types/core/events.ts +8 -0
  77. package/src/@types/domains/community.ts +26 -1
  78. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +2 -2
  79. package/src/channelRepository/observers/getChannel.ts +2 -2
  80. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +7 -7
  81. package/src/client/api/secureLogout.ts +1 -1
  82. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +6 -3
  83. package/src/commentRepository/api/createComment.ts +2 -2
  84. package/src/commentRepository/api/deleteComment.ts +2 -4
  85. package/src/commentRepository/events/utils.ts +8 -5
  86. package/src/commentRepository/internalApi/createComment.ts +3 -2
  87. package/src/commentRepository/internalApi/deleteComment.ts +2 -2
  88. package/src/communityRepository/api/createCommunity.ts +5 -2
  89. package/src/communityRepository/api/getCommunities.ts +5 -1
  90. package/src/communityRepository/api/getCommunity.ts +5 -1
  91. package/src/communityRepository/api/queryCommunities.ts +2 -2
  92. package/src/communityRepository/api/updateCommunity.ts +5 -1
  93. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +152 -0
  94. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.ts +26 -0
  95. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +107 -0
  96. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +9 -0
  97. package/src/communityRepository/communityMembership/observers/getMembers.ts +15 -128
  98. package/src/communityRepository/communityMembership/observers/searchMembers.ts +60 -0
  99. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +147 -0
  100. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +31 -0
  101. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +88 -0
  102. package/src/communityRepository/observers/getCommunities/enums.ts +5 -0
  103. package/src/communityRepository/observers/getCommunities.ts +7 -150
  104. package/src/communityRepository/observers/index.ts +1 -0
  105. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +129 -0
  106. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +31 -0
  107. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +81 -0
  108. package/src/communityRepository/observers/searchCommunities/enums.ts +5 -0
  109. package/src/communityRepository/observers/searchCommunities.ts +56 -0
  110. package/src/communityRepository/utils/payload.ts +35 -1
  111. package/src/communityRepository/utils/saveCommunityUsers.ts +16 -0
  112. package/src/core/liveCollection/LiveCollectionController.ts +6 -3
  113. package/src/marker/events/onChannelUnreadUpdatedLocal.ts +29 -0
  114. package/src/marker/events/onSubChannelMarkerFetched.ts +1 -1
  115. package/src/marker/events/onSubChannelUnreadUpdatedLocal.ts +29 -0
  116. package/src/marker/events/onUserFeedMarkerUpdated.ts +3 -4
  117. package/src/marker/utils/reCalculateChannelUnreadInfo.ts +7 -3
  118. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +3 -3
  119. package/src/postRepository/api/editPost.ts +1 -1
  120. package/src/postRepository/api/updatePost.ts +1 -1
  121. package/src/postRepository/observers/getPost.ts +26 -0
  122. package/src/postRepository/observers/getPosts.ts +31 -0
  123. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +2 -2
  124. package/src/storyRepository/observers/getStoriesByTargetIds/StoryLiveCollectionController.ts +1 -1
  125. package/src/streamRepository/api/getStreams.ts +2 -2
  126. package/src/streamRepository/events/onStreamFlagged.ts +37 -0
  127. package/src/streamRepository/events/onStreamTerminated.ts +37 -0
  128. package/src/streamRepository/observers/getStreams.ts +1 -1
  129. package/src/subChannelRepository/observers/getSubChannel.ts +2 -2
  130. package/src/subChannelRepository/observers/getSubChannels/SubChannelLiveCollectionController.ts +4 -4
  131. package/src/utils/liveObject.ts +3 -0
@@ -0,0 +1,152 @@
1
+ /* eslint-disable no-use-before-define */
2
+ import hash from 'object-hash';
3
+ import { pullFromCache, pushToCache } from '~/cache/api';
4
+ import { CommunityMembersPaginationController } from './CommunityMembersPaginationController';
5
+ import { CommunityMembersQueryStreamController } from './CommunityMembersQueryStreamController';
6
+ import { LiveCollectionController } from '~/core/liveCollection/LiveCollectionController';
7
+ import {
8
+ onCommunityJoined,
9
+ onCommunityLeft,
10
+ onCommunityUserBanned,
11
+ onCommunityUserChanged,
12
+ onCommunityUserRoleAdded,
13
+ onCommunityUserRoleRemoved,
14
+ onCommunityUserUnbanned,
15
+ } from '~/communityRepository/communityMembership/events';
16
+ import {
17
+ filterByPropIntersection,
18
+ filterBySearchTerm,
19
+ sortByDisplayName,
20
+ sortByFirstCreated,
21
+ sortByLastCreated,
22
+ } from '~/core/query';
23
+ import { prepareCommunityPayload } from '~/communityRepository/utils';
24
+ import { isNonNullable } from '~/utils';
25
+ import { EnumCommunityMemberActions } from './enums';
26
+
27
+ export class CommunityMembersLiveCollectionController extends LiveCollectionController<
28
+ 'communityUser',
29
+ Amity.CommunityMemberLiveCollection,
30
+ Amity.Membership<'community'>,
31
+ CommunityMembersPaginationController
32
+ > {
33
+ private queryStreamController: CommunityMembersQueryStreamController;
34
+
35
+ private query: Amity.CommunityMemberLiveCollection;
36
+
37
+ constructor(
38
+ query: Amity.CommunityMemberLiveCollection,
39
+ callback: Amity.LiveCollectionCallback<Amity.Membership<'community'>>,
40
+ ) {
41
+ const queryStreamId = hash(query);
42
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
43
+ const paginationController = new CommunityMembersPaginationController(query);
44
+
45
+ super(paginationController, queryStreamId, cacheKey, callback);
46
+
47
+ this.query = query;
48
+ this.queryStreamController = new CommunityMembersQueryStreamController(
49
+ this.query,
50
+ this.cacheKey,
51
+ this.notifyChange.bind(this),
52
+ prepareCommunityPayload,
53
+ );
54
+
55
+ this.callback = callback.bind(this);
56
+ this.loadPage({ initial: true });
57
+ }
58
+
59
+ protected setup() {
60
+ const collection = pullFromCache<Amity.CommunityMemberLiveCollectionCache>(this.cacheKey)?.data;
61
+ if (!collection) {
62
+ pushToCache(this.cacheKey, {
63
+ data: [],
64
+ params: {},
65
+ });
66
+ }
67
+ }
68
+
69
+ protected async persistModel(queryPayload: Amity.CommunityMembershipPayload & Amity.Pagination) {
70
+ await this.queryStreamController.saveToMainDB(queryPayload);
71
+ }
72
+
73
+ protected persistQueryStream({
74
+ response,
75
+ direction,
76
+ refresh,
77
+ }: Amity.LiveCollectionPersistQueryStreamParams<'communityUser'>) {
78
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
79
+ }
80
+
81
+ startSubscription() {
82
+ return this.queryStreamController.subscribeRTE([
83
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions.OnCommunityJoined },
84
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
85
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
86
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
87
+ { fn: onCommunityUserRoleAdded, action: EnumCommunityMemberActions.OnCommunityUserRoleAdded },
88
+ {
89
+ fn: onCommunityUserRoleRemoved,
90
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
91
+ },
92
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
93
+ ]);
94
+ }
95
+
96
+ notifyChange({ origin, loading, error }: Amity.LiveCollectionNotifyParams) {
97
+ const collection = pullFromCache<Amity.CommunityMemberLiveCollectionCache>(this.cacheKey)?.data;
98
+ if (!collection) return;
99
+
100
+ const data = this.applyFilter(
101
+ collection.data
102
+ .map(id => pullFromCache<Amity.Membership<'community'>>(['communityUsers', 'get', id])!)
103
+ .filter(isNonNullable)
104
+ .map(({ data }) => data) ?? [],
105
+ );
106
+
107
+ if (!this.shouldNotify(data) && origin === 'event') return;
108
+
109
+ this.callback({
110
+ onNextPage: () => this.loadPage({ direction: Amity.LiveCollectionPageDirection.NEXT }),
111
+ data,
112
+ hasNextPage: !!this.paginationController.getNextToken(),
113
+ loading,
114
+ error,
115
+ });
116
+ }
117
+
118
+ applyFilter(data: Amity.Membership<'community'>[]) {
119
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
120
+
121
+ if (this.query.memberships) {
122
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
123
+ const memberships: Amity.GroupMembership[] = this.query.memberships || [];
124
+ return memberships.includes(communityMembership);
125
+ });
126
+ }
127
+
128
+ if (this.query.search) {
129
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
130
+ }
131
+
132
+ const sortBy = this.query.sortBy ? this.query.sortBy : 'lastCreated';
133
+ switch (sortBy) {
134
+ case 'lastCreated':
135
+ communityMembers = communityMembers.sort(sortByLastCreated);
136
+ break;
137
+ case 'firstCreated':
138
+ communityMembers = communityMembers.sort(sortByFirstCreated);
139
+ break;
140
+ case 'displayName':
141
+ communityMembers = communityMembers.sort((memberA, memberB) => {
142
+ if (!memberA.user || !memberB.user) return 0;
143
+ return sortByDisplayName(memberA.user, memberB.user);
144
+ });
145
+ break;
146
+ default:
147
+ break;
148
+ }
149
+
150
+ return communityMembers;
151
+ }
152
+ }
@@ -0,0 +1,26 @@
1
+ import { PaginationController } from '~/core/liveCollection/PaginationController';
2
+ import { COLLECTION_DEFAULT_PAGINATION_LIMIT } from '~/utils/constants';
3
+
4
+ /**
5
+ * TODO: handle cache receive cache option, and cache policy
6
+ * TODO: check if querybyIds is supported
7
+ */
8
+ export class CommunityMembersPaginationController extends PaginationController<
9
+ 'communityUser',
10
+ Amity.CommunityMemberLiveCollection
11
+ > {
12
+ async getRequest(queryParams: Amity.CommunityMemberLiveCollection, token: string | undefined) {
13
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, ...params } = queryParams;
14
+ const options = token ? { token } : { limit };
15
+
16
+ const { data: queryResponse } = await this.http.get<
17
+ Amity.CommunityMembershipPayload & Amity.Pagination
18
+ >(`/api/v3/communities/${params.communityId}/users`, {
19
+ params: {
20
+ ...params,
21
+ options,
22
+ },
23
+ });
24
+ return queryResponse;
25
+ }
26
+ }
@@ -0,0 +1,107 @@
1
+ import { QueryStreamController } from '~/core/liveCollection/QueryStreamController';
2
+ import { pullFromCache, pushToCache } from '~/cache/api';
3
+ import { ingestInCache } from '~/cache/api/ingestInCache';
4
+ import { getResolver } from '~/core/model';
5
+ import { getActiveClient } from '~/client';
6
+ import { EnumCommunityMemberActions } from './enums';
7
+
8
+ export class CommunityMembersQueryStreamController extends QueryStreamController<
9
+ Amity.CommunityMembershipPayload,
10
+ Amity.CommunityMemberLiveCollection
11
+ > {
12
+ private notifyChange: (params: Amity.LiveCollectionNotifyParams) => void;
13
+
14
+ private preparePayload: (
15
+ response: Amity.CommunityMembershipPayload,
16
+ ) => Amity.ProcessedCommunityMembershipPayload;
17
+
18
+ constructor(
19
+ query: Amity.CommunityMemberLiveCollection,
20
+ cacheKey: string[],
21
+ notifyChange: (params: Amity.LiveCollectionNotifyParams) => void,
22
+ preparePayload: (
23
+ response: Amity.CommunityMembershipPayload,
24
+ ) => Amity.ProcessedCommunityMembershipPayload,
25
+ ) {
26
+ super(query, cacheKey);
27
+ this.notifyChange = notifyChange;
28
+ this.preparePayload = preparePayload;
29
+ }
30
+
31
+ async saveToMainDB(response: Amity.CommunityMembershipPayload) {
32
+ const processedPayload = await this.preparePayload(response);
33
+
34
+ const client = getActiveClient();
35
+ const cachedAt = client.cache && Date.now();
36
+
37
+ if (client.cache) {
38
+ ingestInCache(processedPayload, { cachedAt });
39
+ }
40
+ }
41
+
42
+ appendToQueryStream(
43
+ response: Amity.CommunityMembershipPayload & Partial<Amity.Pagination>,
44
+ direction: Amity.LiveCollectionPageDirection,
45
+ refresh = false,
46
+ ) {
47
+ if (refresh) {
48
+ pushToCache(this.cacheKey, {
49
+ data: response.communityUsers.map(({ communityId, userId }) =>
50
+ getResolver('communityUsers')({ communityId, userId }),
51
+ ),
52
+ });
53
+ } else {
54
+ const collection = pullFromCache<Amity.CommunityLiveCollectionCache>(this.cacheKey)?.data;
55
+
56
+ const communityUsers = collection?.data ?? [];
57
+
58
+ pushToCache(this.cacheKey, {
59
+ ...collection,
60
+ data: [
61
+ ...new Set([
62
+ ...communityUsers,
63
+ ...response.communityUsers.map(({ communityId, userId }) =>
64
+ getResolver('communityUsers')({ communityId, userId }),
65
+ ),
66
+ ]),
67
+ ],
68
+ });
69
+ }
70
+ }
71
+
72
+ reactor(action: EnumCommunityMemberActions) {
73
+ return (community: Amity.Community, communityMembers: Amity.Membership<'community'>[]) => {
74
+ const collection = pullFromCache<Amity.CommunityMemberLiveCollectionCache>(
75
+ this.cacheKey,
76
+ )?.data;
77
+ if (!collection) return;
78
+
79
+ communityMembers.forEach(communityMember => {
80
+ const communityMemberCacheId = getResolver('communityUsers')({
81
+ communityId: this.query.communityId,
82
+ userId: communityMember.userId,
83
+ });
84
+
85
+ if (communityMember.communityMembership === 'none') {
86
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
87
+ } else if (!collection.data.includes(communityMemberCacheId)) {
88
+ collection.data = [communityMemberCacheId, ...collection.data];
89
+ }
90
+ });
91
+
92
+ pushToCache(this.cacheKey, collection);
93
+ this.notifyChange({ origin: Amity.LiveDataOrigin.EVENT, loading: false });
94
+ };
95
+ }
96
+
97
+ subscribeRTE(
98
+ createSubscriber: {
99
+ fn: (
100
+ reactor: (channel: Amity.Community, communityUser: Amity.Membership<'community'>[]) => void,
101
+ ) => Amity.Unsubscriber;
102
+ action: EnumCommunityMemberActions;
103
+ }[],
104
+ ) {
105
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
106
+ }
107
+ }
@@ -0,0 +1,9 @@
1
+ export enum EnumCommunityMemberActions {
2
+ OnCommunityJoined = 'onCommunityJoined',
3
+ OnCommunityLeft = 'onCommunityLeft',
4
+ OnCommunityUserBanned = 'onCommunityUserBanned',
5
+ OnCommunityUserChanged = 'onCommunityUserChanged',
6
+ OnCommunityUserRoleAdded = 'onCommunityUserRoleAdded',
7
+ OnCommunityUserRoleRemoved = 'onCommunityUserRoleRemoved',
8
+ OnCommunityUserUnbanned = 'onCommunityUserUnbanned',
9
+ }
@@ -1,32 +1,13 @@
1
- /* eslint-disable no-use-before-define */
2
- import { getResolver } from '~/core/model';
3
- import { pullFromCache, pushToCache } from '~/cache/api';
4
1
  import { getActiveClient } from '~/client/api';
5
2
  import {
6
- createQuery,
7
3
  filterByPropIntersection,
8
4
  filterBySearchTerm,
9
- queryOptions,
10
- runQuery,
11
5
  sortByFirstCreated,
12
6
  sortByLastCreated,
13
7
  } from '~/core/query';
14
- import {
15
- COLLECTION_DEFAULT_CACHING_POLICY,
16
- COLLECTION_DEFAULT_PAGINATION_LIMIT,
17
- ENABLE_CACHE_MESSAGE,
18
- } from '~/utils/constants';
19
- import { isNonNullable } from '~/utils';
20
- import {
21
- onCommunityJoined,
22
- onCommunityLeft,
23
- onCommunityUserBanned,
24
- onCommunityUserChanged,
25
- onCommunityUserRoleAdded,
26
- onCommunityUserRoleRemoved,
27
- onCommunityUserUnbanned,
28
- } from '../events';
29
- import { queryCommunityMembers } from '../api/queryCommunityMembers';
8
+ import { ENABLE_CACHE_MESSAGE } from '~/utils/constants';
9
+ import { CommunityMembersLiveCollectionController } from './getMembers/CommunityMembersLiveCollectionController';
10
+ import { dropFromCache } from '~/cache/api';
30
11
 
31
12
  /*
32
13
  * Exported for testing
@@ -92,114 +73,20 @@ export const getMembers = (
92
73
  const timestamp = Date.now();
93
74
  log(`getMembers(tmpid: ${timestamp}) > listen`);
94
75
 
95
- const { limit: queryLimit, ...queryParams } = params;
96
-
97
- const limit = queryLimit ?? COLLECTION_DEFAULT_PAGINATION_LIMIT;
98
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config ?? {};
99
-
100
- const disposers: Amity.Unsubscriber[] = [];
101
- const cacheKey = ['communityUsers', 'collection', queryParams as unknown as Amity.Serializable];
102
- const cacheByCommunityIdKey = [
103
- 'communityUsers',
104
- 'collection',
105
- { communityId: params.communityId },
106
- ];
107
-
108
- const responder = (data: Amity.CommunityMemberLiveCollectionCache, isEventModel = false) => {
109
- const communityMembers: Amity.Membership<'community'>[] =
110
- data.data
111
- .map(id => pullFromCache<Amity.Membership<'community'>>(['communityUsers', 'get', id])!)
112
- .filter(Boolean)
113
- .map(({ data }) => data) ?? [];
114
-
115
- callback({
116
- onNextPage: onFetch,
117
- data: isEventModel ? applyFilter(communityMembers, params) : communityMembers,
118
- hasNextPage: !!data.params?.page,
119
- loading: data.loading,
120
- error: data.error,
121
- });
122
- };
123
-
124
- const realtimeRouter =
125
- (_: Amity.CommunityMemberActionType) =>
126
- (_: Amity.Community, communityMembers: Amity.Membership<'community'>[]) => {
127
- const collection = pullFromCache<Amity.CommunityMemberLiveCollectionCache>(cacheKey)?.data;
128
- if (!collection) {
129
- return;
130
- }
131
-
132
- const communityMemberCacheIds = communityMembers
133
- .map(communityMember => {
134
- if (params.communityId !== communityMember.communityId) {
135
- return;
136
- }
137
-
138
- const communityMemberCacheId = getResolver('communityUsers')({
139
- communityId: params.communityId,
140
- userId: communityMember.userId,
141
- });
142
-
143
- return communityMemberCacheId;
144
- })
145
- .filter(isNonNullable);
146
-
147
- collection.data = [...new Set([...communityMemberCacheIds, ...collection.data])];
148
-
149
- pushToCache(cacheKey, collection);
150
- pushToCache(cacheByCommunityIdKey, collection);
151
- responder(collection, true);
152
- };
153
-
154
- const onFetch = (initial = false) => {
155
- const collection = pullFromCache<Amity.CommunityMemberLiveCollectionCache>(cacheKey)?.data;
156
-
157
- const communityMembers = collection?.data ?? [];
158
-
159
- if (!initial && communityMembers.length > 0 && !collection?.params.page) return;
160
-
161
- const query = createQuery(queryCommunityMembers, {
162
- ...queryParams,
163
- limit: initial ? limit : undefined,
164
- page: !initial ? collection?.params.page : undefined,
165
- });
166
-
167
- runQuery(
168
- query,
169
- ({ data: result, error, loading, paging }) => {
170
- const data = {
171
- loading,
172
- error,
173
- params: { page: paging?.next },
174
- data: communityMembers,
175
- };
176
-
177
- if (result) {
178
- data.data = [
179
- ...new Set([...communityMembers, ...result.map(getResolver('communityUsers'))]),
180
- ];
181
- }
182
-
183
- pushToCache(cacheKey, data);
184
- pushToCache(cacheByCommunityIdKey, data);
185
-
186
- responder(data);
187
- },
188
- queryOptions(policy),
189
- );
190
- };
191
-
192
- disposers.push(
193
- onCommunityLeft(realtimeRouter('onLeft')),
194
- onCommunityJoined(realtimeRouter('onJoin')),
195
- onCommunityUserBanned(realtimeRouter('onBan')),
196
- onCommunityUserUnbanned(realtimeRouter('onUnban')),
197
- onCommunityUserChanged(realtimeRouter('onMemberCountChanged')),
198
- onCommunityUserRoleAdded(realtimeRouter('onMemberCountChanged')),
199
- onCommunityUserRoleRemoved(realtimeRouter('onMemberCountChanged')),
76
+ const communityMemberLiveCollection = new CommunityMembersLiveCollectionController(
77
+ params,
78
+ resp => {
79
+ console.log('resp', resp);
80
+ callback(resp);
81
+ },
200
82
  );
83
+ const disposers = communityMemberLiveCollection.startSubscription();
84
+
85
+ const cacheKey = communityMemberLiveCollection.getCacheKey();
201
86
 
202
- onFetch(true);
87
+ disposers.push(() => {
88
+ dropFromCache(cacheKey);
89
+ });
203
90
 
204
91
  return () => {
205
92
  log(`getMembers(tmpid: ${timestamp}) > dispose`);
@@ -0,0 +1,60 @@
1
+ import { getActiveClient } from '~/client/api';
2
+ import { ENABLE_CACHE_MESSAGE } from '~/utils/constants';
3
+ import { dropFromCache } from '~/cache/api';
4
+ import { SearchCommunityMembersLiveCollectionController } from './searchMembers/SearchCommunityMembersLiveCollectionController';
5
+
6
+ /* begin_public_function
7
+ id: community.membership.query
8
+ */
9
+ /**
10
+ * ```js
11
+ * import { searchMembers } from '@amityco/ts-sdk-react-native'
12
+ *
13
+ * let communityMembers = []
14
+ * const unsub = searchMembers({
15
+ * communityId: Amity.Community['communityId'],
16
+ * }, response => merge(communityMembers, response.data))
17
+ * ```
18
+ *
19
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
20
+ *
21
+ * @param params for querying community users
22
+ * @param callback the function to call when new data are available
23
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
24
+ *
25
+ * @category Community Live Collection
26
+ */
27
+ export const searchMembers = (
28
+ params: Amity.SearchCommunityMemberLiveCollection,
29
+ callback: Amity.LiveCollectionCallback<Amity.Membership<'community'>>,
30
+ config?: Amity.LiveCollectionConfig,
31
+ ) => {
32
+ const { log, cache } = getActiveClient();
33
+
34
+ if (!cache) {
35
+ console.log(ENABLE_CACHE_MESSAGE);
36
+ }
37
+
38
+ const timestamp = Date.now();
39
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
40
+
41
+ const searchCommunityMemberLiveCollection = new SearchCommunityMembersLiveCollectionController(
42
+ params,
43
+ resp => {
44
+ callback(resp);
45
+ },
46
+ );
47
+ const disposers = searchCommunityMemberLiveCollection.startSubscription();
48
+
49
+ const cacheKey = searchCommunityMemberLiveCollection.getCacheKey();
50
+
51
+ disposers.push(() => {
52
+ dropFromCache(cacheKey);
53
+ });
54
+
55
+ return () => {
56
+ log(`getMembers(tmpid: ${timestamp}) > dispose`);
57
+ disposers.forEach(fn => fn());
58
+ };
59
+ };
60
+ /* end_public_function */
@@ -0,0 +1,147 @@
1
+ /* eslint-disable no-use-before-define */
2
+ import hash from 'object-hash';
3
+ import { pullFromCache, pushToCache } from '~/cache/api';
4
+ import { CommunitiesPaginationController } from './CommunitiesPaginationController';
5
+ import { CommunitiesQueryStreamController } from './CommunitiesQueryStreamController';
6
+ import { LiveCollectionController } from '~/core/liveCollection/LiveCollectionController';
7
+ import {
8
+ onCommunityCreated,
9
+ onCommunityDeleted,
10
+ onCommunityUpdated,
11
+ } from '~/communityRepository/events';
12
+ import {
13
+ filterByCommunityMembership,
14
+ filterByPropEquality,
15
+ sortByDisplayName,
16
+ sortByFirstCreated,
17
+ sortByLastCreated,
18
+ } from '~/core/query';
19
+ import { prepareCommunityPayload } from '~/communityRepository/utils';
20
+ import { getActiveClient } from '~/client';
21
+ import { EnumCommunityActions } from './enums';
22
+
23
+ export class CommunityLiveCollectionController extends LiveCollectionController<
24
+ 'community',
25
+ Amity.CommunityLiveCollection,
26
+ Amity.Community,
27
+ CommunitiesPaginationController
28
+ > {
29
+ private queryStreamController: CommunitiesQueryStreamController;
30
+
31
+ private query: Amity.CommunityLiveCollection;
32
+
33
+ constructor(
34
+ query: Amity.CommunityLiveCollection,
35
+ callback: Amity.LiveCollectionCallback<Amity.Community>,
36
+ ) {
37
+ const queryStreamId = hash(query);
38
+ const cacheKey = ['community', 'collection', queryStreamId];
39
+ const paginationController = new CommunitiesPaginationController(query);
40
+
41
+ super(paginationController, queryStreamId, cacheKey, callback);
42
+
43
+ this.query = query;
44
+ this.queryStreamController = new CommunitiesQueryStreamController(
45
+ this.query,
46
+ this.cacheKey,
47
+ this.notifyChange.bind(this),
48
+ prepareCommunityPayload,
49
+ );
50
+
51
+ this.callback = callback.bind(this);
52
+ this.loadPage({ initial: true });
53
+ }
54
+
55
+ protected setup() {
56
+ const collection = pullFromCache<Amity.CommunityLiveCollectionCache>(this.cacheKey)?.data;
57
+ if (!collection) {
58
+ pushToCache(this.cacheKey, {
59
+ data: [],
60
+ params: {},
61
+ });
62
+ }
63
+ }
64
+
65
+ protected async persistModel(queryPayload: Amity.CommunityPayload & Amity.Pagination) {
66
+ await this.queryStreamController.saveToMainDB(queryPayload);
67
+ }
68
+
69
+ protected persistQueryStream({
70
+ response,
71
+ direction,
72
+ refresh,
73
+ }: Amity.LiveCollectionPersistQueryStreamParams<'community'>) {
74
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
75
+ }
76
+
77
+ startSubscription() {
78
+ return this.queryStreamController.subscribeRTE([
79
+ { fn: onCommunityCreated, action: EnumCommunityActions.OnCommunityCreated },
80
+ { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
81
+ { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
82
+ ]);
83
+ }
84
+
85
+ notifyChange({ origin, loading, error }: Amity.LiveCollectionNotifyParams) {
86
+ const collection = pullFromCache<Amity.CommunityLiveCollectionCache>(this.cacheKey)?.data;
87
+ if (!collection) return;
88
+
89
+ const data = this.applyFilter(
90
+ collection.data
91
+ .map(id => pullFromCache<Amity.Community>(['community', 'get', id])!)
92
+ .filter(Boolean)
93
+ .map(({ data }) => data) ?? [],
94
+ );
95
+
96
+ if (!this.shouldNotify(data) && origin === 'event') return;
97
+
98
+ this.callback({
99
+ onNextPage: () => this.loadPage({ direction: Amity.LiveCollectionPageDirection.NEXT }),
100
+ data,
101
+ hasNextPage: !!this.paginationController.getNextToken(),
102
+ loading,
103
+ error,
104
+ });
105
+ }
106
+
107
+ applyFilter(data: Amity.Community[]) {
108
+ const { userId } = getActiveClient();
109
+
110
+ let communities = data;
111
+
112
+ if (this.query.includeDeleted) {
113
+ communities = filterByPropEquality(communities, 'isDeleted', false);
114
+ }
115
+
116
+ if (this.query.categoryId) {
117
+ communities = communities.filter(c => c.categoryIds?.includes(this.query.categoryId!));
118
+ }
119
+
120
+ if (this.query.tags) {
121
+ communities = communities.filter(c => c.tags?.some(t => this.query.tags?.includes(t)));
122
+ }
123
+
124
+ if (this.query.membership && userId) {
125
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
126
+ }
127
+
128
+ if (!this.query.displayName) {
129
+ const sortFn = (() => {
130
+ switch (this.query.sortBy) {
131
+ case 'firstCreated':
132
+ return sortByFirstCreated;
133
+ case 'lastCreated':
134
+ return sortByLastCreated;
135
+ case 'displayName':
136
+ return sortByDisplayName;
137
+ default:
138
+ return sortByLastCreated;
139
+ }
140
+ })();
141
+
142
+ communities = communities.sort(sortFn);
143
+ }
144
+
145
+ return communities;
146
+ }
147
+ }