@amityco/ts-sdk-react-native 6.22.1-600ab29.0 → 6.22.1-b0a1854.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 (89) hide show
  1. package/package.json +3 -1
  2. package/rollup.config.js +6 -0
  3. package/src/@types/core/events.ts +8 -0
  4. package/src/@types/domains/channel.ts +1 -0
  5. package/src/@types/domains/community.ts +50 -1
  6. package/src/@types/domains/post.ts +3 -3
  7. package/src/channelRepository/api/getChannel.ts +1 -1
  8. package/src/channelRepository/api/getChannelByIds.ts +4 -3
  9. package/src/channelRepository/api/markAsRead.ts +6 -2
  10. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +2 -2
  11. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberQueryStreamController.ts +5 -2
  12. package/src/channelRepository/events/onChannelMemberRoleAdded.ts +1 -1
  13. package/src/channelRepository/events/onChannelMemberRoleRemoved.ts +1 -1
  14. package/src/channelRepository/observers/getChannel.ts +8 -4
  15. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +10 -8
  16. package/src/channelRepository/observers/observeChannel.ts +15 -3
  17. package/src/channelRepository/observers/observeChannels.ts +8 -4
  18. package/src/client/api/index.ts +3 -0
  19. package/src/client/api/logout.ts +1 -1
  20. package/src/client/api/registerPushNotification.ts +37 -0
  21. package/src/client/api/secureLogout.ts +1 -1
  22. package/src/client/api/unregisterPushNotification.ts +26 -0
  23. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +6 -3
  24. package/src/client/utils/markerSyncEngine.ts +4 -1
  25. package/src/commentRepository/api/createComment.ts +2 -2
  26. package/src/commentRepository/api/deleteComment.ts +2 -4
  27. package/src/commentRepository/events/utils.ts +9 -6
  28. package/src/commentRepository/internalApi/createComment.ts +3 -2
  29. package/src/commentRepository/internalApi/deleteComment.ts +2 -2
  30. package/src/communityRepository/api/createCommunity.ts +5 -2
  31. package/src/communityRepository/api/getCommunities.ts +5 -1
  32. package/src/communityRepository/api/getCommunity.ts +5 -1
  33. package/src/communityRepository/api/queryCommunities.ts +2 -2
  34. package/src/communityRepository/api/updateCommunity.ts +5 -1
  35. package/src/communityRepository/communityMembership/events/utils.ts +2 -2
  36. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +151 -0
  37. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.ts +26 -0
  38. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +114 -0
  39. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +10 -0
  40. package/src/communityRepository/communityMembership/observers/getMembers.ts +15 -128
  41. package/src/communityRepository/communityMembership/observers/index.ts +1 -0
  42. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.ts +130 -0
  43. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.ts +29 -0
  44. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.ts +105 -0
  45. package/src/communityRepository/communityMembership/observers/searchMembers/enums.ts +9 -0
  46. package/src/communityRepository/communityMembership/observers/searchMembers.ts +60 -0
  47. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +155 -0
  48. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +31 -0
  49. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +89 -0
  50. package/src/communityRepository/observers/getCommunities/enums.ts +5 -0
  51. package/src/communityRepository/observers/getCommunities.ts +7 -150
  52. package/src/communityRepository/observers/index.ts +1 -0
  53. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +127 -0
  54. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +31 -0
  55. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +82 -0
  56. package/src/communityRepository/observers/searchCommunities/enums.ts +5 -0
  57. package/src/communityRepository/observers/searchCommunities.ts +56 -0
  58. package/src/communityRepository/utils/payload.ts +35 -1
  59. package/src/communityRepository/utils/saveCommunityUsers.ts +16 -0
  60. package/src/core/liveCollection/LiveCollectionController.ts +10 -6
  61. package/src/fileRepository/api/createFile.ts +5 -2
  62. package/src/fileRepository/api/createImage.ts +6 -2
  63. package/src/fileRepository/api/createVideo.ts +5 -2
  64. package/src/fileRepository/api/uploadFile.ts +5 -2
  65. package/src/fileRepository/api/uploadImage.ts +5 -2
  66. package/src/fileRepository/api/uploadVideo.ts +5 -2
  67. package/src/marker/events/onChannelUnreadUpdatedLocal.ts +29 -0
  68. package/src/marker/events/onSubChannelMarkerFetched.ts +1 -1
  69. package/src/marker/events/onSubChannelUnreadUpdatedLocal.ts +29 -0
  70. package/src/marker/events/onUserFeedMarkerUpdated.ts +3 -4
  71. package/src/marker/utils/reCalculateChannelUnreadInfo.ts +7 -3
  72. package/src/messagePreview/utils/getChannelMessagePreviewWithUser.ts +5 -1
  73. package/src/messageRepository/events/onMessageCreated.ts +4 -0
  74. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +3 -3
  75. package/src/messageRepository/utils/markReadMessage.ts +8 -0
  76. package/src/postRepository/api/createPost.ts +1 -2
  77. package/src/postRepository/api/editPost.ts +1 -1
  78. package/src/postRepository/api/updatePost.ts +1 -1
  79. package/src/postRepository/observers/getPost.ts +26 -0
  80. package/src/postRepository/observers/getPosts.ts +31 -0
  81. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +2 -2
  82. package/src/storyRepository/observers/getStoriesByTargetIds/StoryLiveCollectionController.ts +1 -1
  83. package/src/subChannelRepository/observers/getSubChannel.ts +10 -6
  84. package/src/subChannelRepository/observers/getSubChannels/SubChannelLiveCollectionController.ts +13 -10
  85. package/src/utils/linkedObject/channelLinkedObject.ts +8 -0
  86. package/src/utils/linkedObject/index.ts +2 -0
  87. package/src/utils/linkedObject/messageLinkedObject.ts +2 -7
  88. package/src/utils/liveObject.ts +3 -0
  89. package/src/utils/object.ts +15 -0
@@ -1,5 +1,5 @@
1
1
  import { getActiveClient } from '~/client/api';
2
- import { createEventSubscriber } from '~/core/events';
2
+ import { createEventSubscriber, fireEvent } from '~/core/events';
3
3
  import { pullFromCache, pushToCache, queryCache, upsertInCache } from '~/cache/api';
4
4
  import { ingestInCache } from '~/cache/api/ingestInCache';
5
5
  import { LinkedObject } from '~/utils/linkedObject';
@@ -39,11 +39,14 @@ export const createCommentEventSubscriber = (
39
39
  ]);
40
40
 
41
41
  if (parentComment?.data) {
42
- pushToCache(['comment', 'get', comments[0].parentId], {
43
- ...parentComment.data,
44
- childrenNumber: parentComment.data.childrenNumber + 1,
45
- children: [...new Set([...parentComment.data.children, comments[0].commentId])],
46
- });
42
+ // Skip to update parent childComment if current comment already exists
43
+ if (!parentComment.data.children.includes(comments[0].commentId)) {
44
+ pushToCache(['comment', 'get', comments[0].parentId], {
45
+ ...parentComment.data,
46
+ childrenNumber: parentComment.data.childrenNumber + 1,
47
+ children: [...new Set([...parentComment.data.children, comments[0].commentId])],
48
+ });
49
+ }
47
50
  }
48
51
  }
49
52
 
@@ -27,7 +27,7 @@ export const createComment = async (
27
27
 
28
28
  const post = await getPost(bundle.referenceId);
29
29
 
30
- fireEvent('post.updated', {
30
+ fireEvent('local.post.updated', {
31
31
  posts: [post.data],
32
32
  categories: [],
33
33
  comments: [],
@@ -38,7 +38,8 @@ export const createComment = async (
38
38
  postChildren: [],
39
39
  users: [],
40
40
  });
41
- fireEvent('comment.created', data);
41
+
42
+ fireEvent('local.comment.created', data);
42
43
 
43
44
  const { comments } = data;
44
45
  return {
@@ -33,7 +33,7 @@ export const deleteComment = async (
33
33
 
34
34
  const post = await getPost(comment.data.referenceId);
35
35
 
36
- fireEvent('post.updated', {
36
+ fireEvent('local.post.updated', {
37
37
  posts: [post.data],
38
38
  categories: [],
39
39
  comments: [],
@@ -45,7 +45,7 @@ export const deleteComment = async (
45
45
  users: [],
46
46
  });
47
47
 
48
- fireEvent('comment.deleted', {
48
+ fireEvent('local.comment.deleted', {
49
49
  comments: [deleted],
50
50
  commentChildren: [],
51
51
  files: [],
@@ -2,7 +2,7 @@ import { getActiveClient } from '~/client/api';
2
2
 
3
3
  import { ingestInCache } from '~/cache/api/ingestInCache';
4
4
  import { fireEvent } from '~/core/events';
5
-
5
+ import { saveCommunityUsers } from '~/communityRepository/utils/saveCommunityUsers';
6
6
  import { prepareCommunityPayload, prepareCommunityRequest } from '../utils';
7
7
 
8
8
  /* begin_public_function
@@ -53,7 +53,10 @@ export const createCommunity = async (
53
53
  const data = prepareCommunityPayload(payload);
54
54
 
55
55
  const cachedAt = client.cache && Date.now();
56
- if (client.cache) ingestInCache(data, { cachedAt });
56
+ if (client.cache) {
57
+ ingestInCache(data, { cachedAt });
58
+ saveCommunityUsers(data.communities, data.communityUsers);
59
+ }
57
60
 
58
61
  const { communities } = data;
59
62
  return {
@@ -3,6 +3,7 @@ import { getActiveClient } from '~/client/api';
3
3
  import { pullFromCache } from '~/cache/api';
4
4
  import { ingestInCache } from '~/cache/api/ingestInCache';
5
5
 
6
+ import { saveCommunityUsers } from '~/communityRepository/utils/saveCommunityUsers';
6
7
  import { prepareCommunityPayload } from '../utils';
7
8
 
8
9
  /**
@@ -36,7 +37,10 @@ export const getCommunities = async (
36
37
  const data = prepareCommunityPayload(payload);
37
38
 
38
39
  const cachedAt = client.cache && Date.now();
39
- if (client.cache) ingestInCache(data, { cachedAt });
40
+ if (client.cache) {
41
+ ingestInCache(data, { cachedAt });
42
+ saveCommunityUsers(data.communities, data.communityUsers);
43
+ }
40
44
 
41
45
  return {
42
46
  data: data.communities,
@@ -3,6 +3,7 @@ import { getActiveClient } from '~/client/api';
3
3
  import { pullFromCache } from '~/cache/api';
4
4
  import { ingestInCache } from '~/cache/api/ingestInCache';
5
5
 
6
+ import { saveCommunityUsers } from '~/communityRepository/utils/saveCommunityUsers';
6
7
  import { prepareCommunityPayload } from '../utils';
7
8
 
8
9
  /**
@@ -33,7 +34,10 @@ export const getCommunity = async (
33
34
  const data = prepareCommunityPayload(payload);
34
35
 
35
36
  const cachedAt = client.cache && Date.now();
36
- if (client.cache) ingestInCache(data, { cachedAt });
37
+ if (client.cache) {
38
+ ingestInCache(data, { cachedAt });
39
+ saveCommunityUsers(data.communities, data.communityUsers);
40
+ }
37
41
 
38
42
  const { communities } = data;
39
43
 
@@ -1,11 +1,10 @@
1
1
  import { getActiveClient } from '~/client/api';
2
-
3
- import { toPage, toToken } from '~/core/query';
4
2
  import { pushToCache } from '~/cache/api';
5
3
  import { ingestInCache } from '~/cache/api/ingestInCache';
6
4
  import { getResolver } from '~/core/model';
7
5
 
8
6
  import { inferIsDeleted } from '~/utils/inferIsDeleted';
7
+ import { saveCommunityUsers } from '~/communityRepository/utils/saveCommunityUsers';
9
8
  import { prepareCommunityPayload } from '../utils';
10
9
 
11
10
  /**
@@ -67,6 +66,7 @@ export const queryCommunities = async (
67
66
 
68
67
  const cacheKey = ['community', 'query', { ...params, options } as Amity.Serializable];
69
68
  pushToCache(cacheKey, { communities: communities.map(getResolver('community')), paging });
69
+ saveCommunityUsers(data.communities, data.communityUsers);
70
70
  }
71
71
 
72
72
  return { data: communities, cachedAt, paging };
@@ -3,6 +3,7 @@ import { getActiveClient } from '~/client/api';
3
3
  import { ingestInCache } from '~/cache/api/ingestInCache';
4
4
  import { fireEvent } from '~/core/events';
5
5
 
6
+ import { saveCommunityUsers } from '~/communityRepository/utils/saveCommunityUsers';
6
7
  import { prepareCommunityPayload, prepareCommunityRequest } from '../utils';
7
8
 
8
9
  /* begin_public_function
@@ -44,7 +45,10 @@ export const updateCommunity = async (
44
45
  const data = prepareCommunityPayload(payload);
45
46
 
46
47
  const cachedAt = client.cache && Date.now();
47
- if (client.cache) ingestInCache(data, { cachedAt });
48
+ if (client.cache) {
49
+ ingestInCache(data, { cachedAt });
50
+ saveCommunityUsers(data.communities, data.communityUsers);
51
+ }
48
52
 
49
53
  const { communities } = data;
50
54
 
@@ -11,7 +11,7 @@ import { isNonNullable } from '~/utils';
11
11
  function hasPermission(
12
12
  member: Amity.Membership<'community'>,
13
13
  payload: {
14
- users: Amity.InternalUser[];
14
+ communityUsers: Amity.Membership<'community'>[];
15
15
  },
16
16
  permission: string,
17
17
  ) {
@@ -20,7 +20,7 @@ function hasPermission(
20
20
  }
21
21
 
22
22
  return payload
23
- .users!.find(user => user.userId === member.userId)!
23
+ .communityUsers!.find(user => user.userId === member.userId)!
24
24
  .permissions.some(x => x === permission);
25
25
  }
26
26
 
@@ -0,0 +1,151 @@
1
+ import hash from 'object-hash';
2
+ import { pullFromCache, pushToCache } from '~/cache/api';
3
+ import { CommunityMembersPaginationController } from './CommunityMembersPaginationController';
4
+ import { CommunityMembersQueryStreamController } from './CommunityMembersQueryStreamController';
5
+ import { LiveCollectionController } from '~/core/liveCollection/LiveCollectionController';
6
+ import {
7
+ onCommunityJoined,
8
+ onCommunityLeft,
9
+ onCommunityUserBanned,
10
+ onCommunityUserChanged,
11
+ onCommunityUserRoleAdded,
12
+ onCommunityUserRoleRemoved,
13
+ onCommunityUserUnbanned,
14
+ } from '~/communityRepository/communityMembership/events';
15
+ import {
16
+ filterByPropIntersection,
17
+ filterBySearchTerm,
18
+ sortByDisplayName,
19
+ sortByFirstCreated,
20
+ sortByLastCreated,
21
+ } from '~/core/query';
22
+ import { prepareCommunityPayload } from '~/communityRepository/utils';
23
+ import { isNonNullable } from '~/utils';
24
+ import { EnumCommunityMemberActions } from './enums';
25
+
26
+ export class CommunityMembersLiveCollectionController extends LiveCollectionController<
27
+ 'communityUser',
28
+ Amity.CommunityMemberLiveCollection,
29
+ Amity.Membership<'community'>,
30
+ CommunityMembersPaginationController
31
+ > {
32
+ private queryStreamController: CommunityMembersQueryStreamController;
33
+
34
+ private query: Amity.CommunityMemberLiveCollection;
35
+
36
+ constructor(
37
+ query: Amity.CommunityMemberLiveCollection,
38
+ callback: Amity.LiveCollectionCallback<Amity.Membership<'community'>>,
39
+ ) {
40
+ const queryStreamId = hash(query);
41
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
42
+ const paginationController = new CommunityMembersPaginationController(query);
43
+
44
+ super(paginationController, queryStreamId, cacheKey, callback);
45
+
46
+ this.query = query;
47
+ this.queryStreamController = new CommunityMembersQueryStreamController(
48
+ this.query,
49
+ this.cacheKey,
50
+ this.notifyChange.bind(this),
51
+ prepareCommunityPayload,
52
+ );
53
+
54
+ this.callback = callback.bind(this);
55
+ this.loadPage({ initial: true });
56
+ }
57
+
58
+ protected setup() {
59
+ const collection = pullFromCache<Amity.CommunityMemberLiveCollectionCache>(this.cacheKey)?.data;
60
+ if (!collection) {
61
+ pushToCache(this.cacheKey, {
62
+ data: [],
63
+ params: {},
64
+ });
65
+ }
66
+ }
67
+
68
+ protected async persistModel(queryPayload: Amity.CommunityMembershipPayload & Amity.Pagination) {
69
+ await this.queryStreamController.saveToMainDB(queryPayload);
70
+ }
71
+
72
+ protected persistQueryStream({
73
+ response,
74
+ direction,
75
+ refresh,
76
+ }: Amity.LiveCollectionPersistQueryStreamParams<'communityUser'>) {
77
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
78
+ }
79
+
80
+ startSubscription() {
81
+ return this.queryStreamController.subscribeRTE([
82
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions.OnCommunityJoined },
83
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
84
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
85
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
86
+ { fn: onCommunityUserRoleAdded, action: EnumCommunityMemberActions.OnCommunityUserRoleAdded },
87
+ {
88
+ fn: onCommunityUserRoleRemoved,
89
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
90
+ },
91
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
92
+ ]);
93
+ }
94
+
95
+ notifyChange({ origin, loading, error }: Amity.LiveCollectionNotifyParams) {
96
+ const collection = pullFromCache<Amity.CommunityMemberLiveCollectionCache>(this.cacheKey)?.data;
97
+ if (!collection) return;
98
+
99
+ const data = this.applyFilter(
100
+ collection.data
101
+ .map(id => pullFromCache<Amity.Membership<'community'>>(['communityUsers', 'get', id])!)
102
+ .filter(isNonNullable)
103
+ .map(({ data }) => data) ?? [],
104
+ );
105
+
106
+ if (!this.shouldNotify(data) && origin === 'event') return;
107
+
108
+ this.callback({
109
+ onNextPage: () => this.loadPage({ direction: Amity.LiveCollectionPageDirection.NEXT }),
110
+ data,
111
+ hasNextPage: !!this.paginationController.getNextToken(),
112
+ loading,
113
+ error,
114
+ });
115
+ }
116
+
117
+ applyFilter(data: Amity.Membership<'community'>[]) {
118
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
119
+
120
+ if (this.query.memberships) {
121
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
122
+ const memberships: Amity.GroupMembership[] = this.query.memberships || [];
123
+ return memberships.includes(communityMembership);
124
+ });
125
+ }
126
+
127
+ if (this.query.search) {
128
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
129
+ }
130
+
131
+ switch (this.query.sortBy) {
132
+ case 'firstCreated':
133
+ communityMembers = communityMembers.sort(sortByFirstCreated);
134
+ break;
135
+ case 'displayName':
136
+ communityMembers = communityMembers.sort((a, b) => {
137
+ if (a?.user?.displayName && b?.user?.displayName) {
138
+ return a?.user?.displayName.localeCompare(b?.user?.displayName);
139
+ }
140
+ return 0;
141
+ });
142
+ break;
143
+ case 'lastCreated':
144
+ default:
145
+ communityMembers = communityMembers.sort(sortByLastCreated);
146
+ break;
147
+ }
148
+
149
+ return communityMembers;
150
+ }
151
+ }
@@ -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,114 @@
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
+ if (
80
+ action === EnumCommunityMemberActions.OnCommunityUserRoleAdded &&
81
+ this.query.sortBy === 'displayName'
82
+ ) {
83
+ return;
84
+ }
85
+
86
+ communityMembers.forEach(communityMember => {
87
+ const communityMemberCacheId = getResolver('communityUsers')({
88
+ communityId: this.query.communityId,
89
+ userId: communityMember.userId,
90
+ });
91
+
92
+ if (communityMember.communityMembership === 'none') {
93
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
94
+ } else if (!collection.data.includes(communityMemberCacheId)) {
95
+ collection.data = [communityMemberCacheId, ...collection.data];
96
+ }
97
+ });
98
+
99
+ pushToCache(this.cacheKey, collection);
100
+ this.notifyChange({ origin: Amity.LiveDataOrigin.EVENT, loading: false });
101
+ };
102
+ }
103
+
104
+ subscribeRTE(
105
+ createSubscriber: {
106
+ fn: (
107
+ reactor: (channel: Amity.Community, communityUser: Amity.Membership<'community'>[]) => void,
108
+ ) => Amity.Unsubscriber;
109
+ action: EnumCommunityMemberActions;
110
+ }[],
111
+ ) {
112
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
113
+ }
114
+ }
@@ -0,0 +1,10 @@
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
+ OnMemberCountChanged = 'OnMemberCountChanged',
10
+ }
@@ -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`);
@@ -1 +1,2 @@
1
1
  export * from './getMembers';
2
+ export * from './searchMembers';