@amityco/ts-sdk-react-native 6.24.1-13ac472.0 → 6.24.2-18b8e6d.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 (101) hide show
  1. package/dist/@types/domains/community.d.ts +15 -1
  2. package/dist/@types/domains/community.d.ts.map +1 -1
  3. package/dist/client/api/index.d.ts +2 -0
  4. package/dist/client/api/index.d.ts.map +1 -1
  5. package/dist/client/api/registerPushNotification.d.ts +2 -0
  6. package/dist/client/api/registerPushNotification.d.ts.map +1 -0
  7. package/dist/client/api/secureLogout.d.ts +1 -1
  8. package/dist/client/api/unregisterPushNotification.d.ts +2 -0
  9. package/dist/client/api/unregisterPushNotification.d.ts.map +1 -0
  10. package/dist/client/utils/markerSyncEngine.d.ts.map +1 -1
  11. package/dist/commentRepository/events/utils.d.ts.map +1 -1
  12. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  13. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  14. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  15. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  16. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  17. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts +14 -0
  18. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts.map +1 -0
  19. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts +9 -0
  20. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts.map +1 -0
  21. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +15 -0
  22. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -0
  23. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts +11 -0
  24. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts.map +1 -0
  25. package/dist/communityRepository/communityMembership/observers/getMembers.d.ts.map +1 -1
  26. package/dist/communityRepository/communityMembership/observers/index.d.ts +1 -0
  27. package/dist/communityRepository/communityMembership/observers/index.d.ts.map +1 -1
  28. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.d.ts +14 -0
  29. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.d.ts.map +1 -0
  30. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts +9 -0
  31. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts.map +1 -0
  32. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts +15 -0
  33. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts.map +1 -0
  34. package/dist/communityRepository/communityMembership/observers/searchMembers/enums.d.ts +10 -0
  35. package/dist/communityRepository/communityMembership/observers/searchMembers/enums.d.ts.map +1 -0
  36. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts +20 -0
  37. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts.map +1 -0
  38. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -1
  39. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +3 -2
  40. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -1
  41. package/dist/communityRepository/observers/getCommunities.d.ts.map +1 -1
  42. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts.map +1 -1
  43. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +3 -2
  44. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -1
  45. package/dist/communityRepository/observers/searchCommunities.d.ts +1 -1
  46. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  47. package/dist/communityRepository/utils/saveCommunityUsers.d.ts +2 -0
  48. package/dist/communityRepository/utils/saveCommunityUsers.d.ts.map +1 -0
  49. package/dist/fileRepository/api/createFile.d.ts.map +1 -1
  50. package/dist/fileRepository/api/createImage.d.ts.map +1 -1
  51. package/dist/fileRepository/api/createVideo.d.ts.map +1 -1
  52. package/dist/fileRepository/api/uploadFile.d.ts.map +1 -1
  53. package/dist/fileRepository/api/uploadImage.d.ts.map +1 -1
  54. package/dist/fileRepository/api/uploadVideo.d.ts.map +1 -1
  55. package/dist/index.cjs.js +849 -469
  56. package/dist/index.esm.js +830 -450
  57. package/dist/index.umd.js +3 -4
  58. package/dist/streamRepository/api/getStreams.d.ts +2 -2
  59. package/dist/utils/liveObject.d.ts +3 -0
  60. package/dist/utils/liveObject.d.ts.map +1 -1
  61. package/package.json +3 -1
  62. package/rollup.config.js +6 -0
  63. package/src/@types/domains/community.ts +25 -1
  64. package/src/client/api/index.ts +3 -0
  65. package/src/client/api/registerPushNotification.ts +37 -0
  66. package/src/client/api/secureLogout.ts +1 -1
  67. package/src/client/api/unregisterPushNotification.ts +26 -0
  68. package/src/client/utils/markerSyncEngine.ts +4 -1
  69. package/src/commentRepository/events/utils.ts +8 -5
  70. package/src/communityRepository/api/createCommunity.ts +5 -2
  71. package/src/communityRepository/api/getCommunities.ts +5 -1
  72. package/src/communityRepository/api/getCommunity.ts +5 -1
  73. package/src/communityRepository/api/queryCommunities.ts +2 -2
  74. package/src/communityRepository/api/updateCommunity.ts +5 -1
  75. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +151 -0
  76. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.ts +26 -0
  77. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +114 -0
  78. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +10 -0
  79. package/src/communityRepository/communityMembership/observers/getMembers.ts +15 -128
  80. package/src/communityRepository/communityMembership/observers/index.ts +1 -0
  81. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.ts +130 -0
  82. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.ts +29 -0
  83. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.ts +105 -0
  84. package/src/communityRepository/communityMembership/observers/searchMembers/enums.ts +9 -0
  85. package/src/communityRepository/communityMembership/observers/searchMembers.ts +60 -0
  86. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +9 -1
  87. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +6 -3
  88. package/src/communityRepository/observers/getCommunities.ts +7 -150
  89. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +11 -13
  90. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +3 -2
  91. package/src/communityRepository/observers/searchCommunities.ts +1 -1
  92. package/src/communityRepository/utils/payload.ts +35 -1
  93. package/src/communityRepository/utils/saveCommunityUsers.ts +16 -0
  94. package/src/fileRepository/api/createFile.ts +5 -2
  95. package/src/fileRepository/api/createImage.ts +6 -2
  96. package/src/fileRepository/api/createVideo.ts +5 -2
  97. package/src/fileRepository/api/uploadFile.ts +5 -2
  98. package/src/fileRepository/api/uploadImage.ts +5 -2
  99. package/src/fileRepository/api/uploadVideo.ts +5 -2
  100. package/src/streamRepository/api/getStreams.ts +2 -2
  101. package/src/utils/liveObject.ts +3 -0
package/dist/index.esm.js CHANGED
@@ -6,6 +6,7 @@ import HttpAgent, { HttpsAgent } from 'agentkeepalive';
6
6
  import io from 'socket.io-client';
7
7
  import AsyncStorage from '@react-native-async-storage/async-storage';
8
8
  import uuid$1 from 'react-native-uuid';
9
+ import { Platform } from 'react-native';
9
10
  import hash from 'object-hash';
10
11
  import Hls from 'hls.js';
11
12
 
@@ -83,8 +84,8 @@ const PostContentType = Object.freeze({
83
84
 
84
85
  function getVersion() {
85
86
  try {
86
- // the string ''v6.24.0-esm'' should be replaced by actual value by @rollup/plugin-replace
87
- return 'v6.24.0-esm';
87
+ // the string ''v6.24.1-esm'' should be replaced by actual value by @rollup/plugin-replace
88
+ return 'v6.24.1-esm';
88
89
  }
89
90
  catch (error) {
90
91
  return '__dev__';
@@ -639,6 +640,18 @@ class ASCConnectionError extends ASCError {
639
640
  : 800210 /* Amity.ClientError.CONNECTION_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
640
641
  this.event = event;
641
642
  }
643
+ }
644
+ /**
645
+ * Input sanitization related error
646
+ * @category Errors
647
+ */
648
+ class ASCInvalidParameterError extends ASCError {
649
+ /**
650
+ * @param message A custom error message
651
+ */
652
+ constructor(message) {
653
+ super(message, 800110 /* Amity.ClientError.INVALID_PARAMETERS */, "error" /* Amity.ErrorLevel.ERROR */);
654
+ }
642
655
  }
643
656
 
644
657
  let activeClient = null;
@@ -24776,7 +24789,8 @@ const registerEventListeners = () => {
24776
24789
  events.push("resume" /* Amity.MarkerSyncEvent.RESUME */);
24777
24790
  }), onMessageCreatedMqtt(message => {
24778
24791
  // only conversation, community and broadcast types can sync
24779
- if (isUnreadCountSupport(message))
24792
+ const client = getActiveClient();
24793
+ if (isUnreadCountSupport(message) && message.creatorId !== client.userId)
24780
24794
  events.push("new message" /* Amity.MarkerSyncEvent.NEW_MESSAGE */);
24781
24795
  }), onChannelCreated(() => events.push("subchannel is created" /* Amity.MarkerSyncEvent.CHANNEL_CREATED */)), onChannelDeleted(() => events.push("subchannel is deleted" /* Amity.MarkerSyncEvent.CHANNEL_DELETED */)), onChannelJoined(() => events.push("subchannel is joined" /* Amity.MarkerSyncEvent.CHANNEL_JOINED */)), onChannelLeft(() => events.push("subchannel is left" /* Amity.MarkerSyncEvent.CHANNEL_LEFT */)), onSubChannelCreated(() => events.push("subchannel is created" /* Amity.MarkerSyncEvent.SUB_CHANNEL_CREATED */)), onSubChannelDeleted(() =>
24782
24796
  /*
@@ -25177,7 +25191,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25177
25191
  */
25178
25192
  /**
25179
25193
  * ```js
25180
- * import { Client } from '@amityco/ts-sdk'
25194
+ * import { Client } from '@amityco/ts-sdk-react-native'
25181
25195
  * const success = await Client.secureLogout()
25182
25196
  * ```
25183
25197
  *
@@ -25220,6 +25234,43 @@ const isConnected = () => {
25220
25234
  client.ws.connected);
25221
25235
  };
25222
25236
 
25237
+ const registerPushNotification = async (deviceToken) => {
25238
+ const client = getActiveClient();
25239
+ let platform;
25240
+ if (Platform.OS === 'ios' || Platform.OS === 'android') {
25241
+ platform = Platform.OS;
25242
+ }
25243
+ else {
25244
+ throw new ASCInvalidParameterError('Unsupported platform');
25245
+ }
25246
+ const deviceId = getDeviceId();
25247
+ const { data: { status, error }, } = await client.http.post('/v1/notification', {
25248
+ userId: client.userId,
25249
+ deviceId,
25250
+ platform,
25251
+ token: deviceToken,
25252
+ }, { headers: { 'X-API-Key': client.apiKey } });
25253
+ if (error) {
25254
+ throw new ASCApiError(error, 500000 /* Amity.ServerError.BUSINESS_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
25255
+ }
25256
+ return status === 'success';
25257
+ };
25258
+
25259
+ const unregisterPushNotification = async () => {
25260
+ const client = getActiveClient();
25261
+ const deviceId = getDeviceId();
25262
+ const { data: { status, error }, } = await client.http.delete('/v1/notification', {
25263
+ data: {
25264
+ deviceId,
25265
+ },
25266
+ headers: { 'X-API-Key': client.apiKey },
25267
+ });
25268
+ if (error) {
25269
+ throw new ASCApiError(error, 500000 /* Amity.ServerError.BUSINESS_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
25270
+ }
25271
+ return status === 'success';
25272
+ };
25273
+
25223
25274
  /**
25224
25275
  * ```js
25225
25276
  * import { onChannelMarkerFetched } from '@amityco/ts-sdk-react-native'
@@ -25533,6 +25584,9 @@ function isEqual(x, y) {
25533
25584
  }));
25534
25585
  }
25535
25586
 
25587
+ /**
25588
+ * @deprecated This function is deprecated
25589
+ */
25536
25590
  const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
25537
25591
  const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
25538
25592
  const { cache } = getActiveClient();
@@ -25747,6 +25801,8 @@ var index$k = /*#__PURE__*/Object.freeze({
25747
25801
  renewal: renewal,
25748
25802
  markerSync: markerSync,
25749
25803
  enableUnreadCount: enableUnreadCount,
25804
+ registerPushNotification: registerPushNotification,
25805
+ unregisterPushNotification: unregisterPushNotification,
25750
25806
  onConnectionError: onConnectionError,
25751
25807
  onClientDisconnected: onClientDisconnected,
25752
25808
  onClientBanned: onClientBanned,
@@ -27883,8 +27939,10 @@ getFile.locally = (fileId) => {
27883
27939
  const uploadFile = async (formData, onProgress) => {
27884
27940
  const client = getActiveClient();
27885
27941
  client.log('file/uploadFile', formData);
27886
- if (!formData.getAll('files').length)
27942
+ const files = formData.getAll('files');
27943
+ if (!files.length)
27887
27944
  throw new Error('The formData object must have a `files` key.');
27945
+ formData.append('preferredFilename', files[0].name);
27888
27946
  const headers = 'getHeaders' in formData
27889
27947
  ? formData.getHeaders()
27890
27948
  : { 'content-type': 'multipart/form-data' };
@@ -27966,8 +28024,10 @@ const fileUrlWithSize = (fileUrl, size) => {
27966
28024
  const uploadVideo = async (formData, feedType, onProgress) => {
27967
28025
  const client = getActiveClient();
27968
28026
  client.log('file/uploadVideo', formData);
27969
- if (!formData.getAll('files').length)
28027
+ const files = formData.getAll('files');
28028
+ if (!files.length)
27970
28029
  throw new Error('The formData object must have a `files` key.');
28030
+ formData.append('preferredFilename', files[0].name);
27971
28031
  if (feedType) {
27972
28032
  formData.append('feedType', feedType);
27973
28033
  }
@@ -28013,8 +28073,10 @@ const uploadVideo = async (formData, feedType, onProgress) => {
28013
28073
  const uploadImage = async (formData, onProgress) => {
28014
28074
  const client = getActiveClient();
28015
28075
  client.log('file/uploadImage', formData);
28016
- if (!formData.getAll('files').length)
28076
+ const files = formData.getAll('files');
28077
+ if (!files.length)
28017
28078
  throw new Error('The formData object must have a `files` key.');
28079
+ formData.append('preferredFilename', files[0].name);
28018
28080
  const headers = 'getHeaders' in formData
28019
28081
  ? formData.getHeaders()
28020
28082
  : { 'content-type': 'multipart/form-data' };
@@ -28054,8 +28116,10 @@ const uploadImage = async (formData, onProgress) => {
28054
28116
  const createImage = async (formData, onProgress) => {
28055
28117
  const client = getActiveClient();
28056
28118
  client.log('file/createImage', formData);
28057
- if (!formData.getAll('files').length)
28119
+ const files = formData.getAll('files');
28120
+ if (!files.length)
28058
28121
  throw new Error('The formData object must have a `files` key.');
28122
+ formData.append('preferredFilename', files[0].name);
28059
28123
  const headers = 'getHeaders' in formData
28060
28124
  ? formData.getHeaders()
28061
28125
  : { 'content-type': 'multipart/form-data' };
@@ -28095,8 +28159,10 @@ const createImage = async (formData, onProgress) => {
28095
28159
  const createFile = async (formData, onProgress) => {
28096
28160
  const client = getActiveClient();
28097
28161
  client.log('file/createFile', formData);
28098
- if (!formData.getAll('files').length)
28162
+ const files = formData.getAll('files');
28163
+ if (!files.length)
28099
28164
  throw new Error('The formData object must have a `files` key.');
28165
+ formData.append('preferredFilename', files[0].name);
28100
28166
  const headers = 'getHeaders' in formData
28101
28167
  ? formData.getHeaders()
28102
28168
  : { 'content-type': 'multipart/form-data' };
@@ -28136,8 +28202,10 @@ const createFile = async (formData, onProgress) => {
28136
28202
  const createVideo = async (formData, feedType, onProgress) => {
28137
28203
  const client = getActiveClient();
28138
28204
  client.log('file/createVideo', formData);
28139
- if (!formData.getAll('files').length)
28205
+ const files = formData.getAll('files');
28206
+ if (!files.length)
28140
28207
  throw new Error('The formData object must have a `files` key.');
28208
+ formData.append('preferredFilename', files[0].name);
28141
28209
  if (feedType) {
28142
28210
  formData.append('feedType', feedType);
28143
28211
  }
@@ -29089,7 +29157,10 @@ const createCommentEventSubscriber = (event, callback) => {
29089
29157
  comments[0].parentId,
29090
29158
  ]);
29091
29159
  if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
29092
- pushToCache(['comment', 'get', comments[0].parentId], Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber + 1, children: [...new Set([...parentComment.data.children, comments[0].commentId])] }));
29160
+ // Skip to update parent childComment if current comment already exists
29161
+ if (!parentComment.data.children.includes(comments[0].commentId)) {
29162
+ pushToCache(['comment', 'get', comments[0].parentId], Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber + 1, children: [...new Set([...parentComment.data.children, comments[0].commentId])] }));
29163
+ }
29093
29164
  }
29094
29165
  }
29095
29166
  const queries = (_a = queryCache(['comment', 'query'])) === null || _a === void 0 ? void 0 : _a.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
@@ -33607,7 +33678,7 @@ const getMembers$1 = (params, callback, config) => {
33607
33678
  *
33608
33679
  * @category Channel Live Collection
33609
33680
  */
33610
- const searchMembers = (params, callback, config) => {
33681
+ const searchMembers$1 = (params, callback, config) => {
33611
33682
  return getMembers$1(params, callback);
33612
33683
  };
33613
33684
  /* end_public_function */
@@ -33618,7 +33689,7 @@ var index$d = /*#__PURE__*/Object.freeze({
33618
33689
  removeMembers: removeMembers$1,
33619
33690
  applyFilter: applyFilter$1,
33620
33691
  getMembers: getMembers$1,
33621
- searchMembers: searchMembers
33692
+ searchMembers: searchMembers$1
33622
33693
  });
33623
33694
 
33624
33695
  /* begin_public_function
@@ -33861,12 +33932,30 @@ var index$b = /*#__PURE__*/Object.freeze({
33861
33932
  prepareChannelPayload: prepareChannelPayload
33862
33933
  });
33863
33934
 
33935
+ const saveCommunityUsers = (communities, communityUsers) => {
33936
+ if (communities.length === 0 || communityUsers.length === 0)
33937
+ return;
33938
+ communities.forEach(({ communityId }) => {
33939
+ const collection = communityUsers.filter(({ communityId: userCommunityId }) => communityId === userCommunityId);
33940
+ pushToCache(['communityUsers', 'collection', communityId], collection);
33941
+ });
33942
+ };
33943
+
33864
33944
  const getMatchPostSetting = (value) => {
33865
33945
  var _a;
33866
33946
  return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
33867
33947
  CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
33868
33948
  value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
33869
33949
  };
33950
+ const convertCommunityUsersToUniqueObject = (communityUsers) => {
33951
+ if (!communityUsers)
33952
+ return communityUsers;
33953
+ const result = {};
33954
+ communityUsers.forEach(user => {
33955
+ result[`${user.userId}#${user.communityId}`] = user;
33956
+ });
33957
+ return result;
33958
+ };
33870
33959
  const prepareCommunityPayload = (rawPayload) => {
33871
33960
  // Unpack community payload by mapping payload field to postSetting value.
33872
33961
  const communities = rawPayload.communities.map((_a) => {
@@ -33876,7 +33965,18 @@ const prepareCommunityPayload = (rawPayload) => {
33876
33965
  onlyAdminCanPost,
33877
33966
  }) }, restCommunityPayload));
33878
33967
  });
33879
- const communityUsers = withUsers(rawPayload.communityUsers);
33968
+ const mergeCommunityUsers = communities.reduce((acc, { communityId }) => {
33969
+ var _a;
33970
+ const users = (_a = pullFromCache([
33971
+ 'communityUsers',
33972
+ 'collection',
33973
+ communityId,
33974
+ ])) === null || _a === void 0 ? void 0 : _a.data;
33975
+ if (!users)
33976
+ return acc;
33977
+ return Object.assign(Object.assign({}, convertCommunityUsersToUniqueObject(users)), acc);
33978
+ }, convertCommunityUsersToUniqueObject(rawPayload.communityUsers));
33979
+ const communityUsers = withUsers(Object.values(mergeCommunityUsers));
33880
33980
  const communityWithMembershipStatus = updateMembershipStatus(communities, communityUsers);
33881
33981
  return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers });
33882
33982
  };
@@ -33910,8 +34010,10 @@ const getCommunities$1 = async (communityIds) => {
33910
34010
  });
33911
34011
  const data = prepareCommunityPayload(payload);
33912
34012
  const cachedAt = client.cache && Date.now();
33913
- if (client.cache)
34013
+ if (client.cache) {
33914
34014
  ingestInCache(data, { cachedAt });
34015
+ saveCommunityUsers(data.communities, data.communityUsers);
34016
+ }
33915
34017
  return {
33916
34018
  data: data.communities,
33917
34019
  cachedAt,
@@ -33973,8 +34075,10 @@ const createCommunity = async (bundle) => {
33973
34075
  fireEvent('community.created', payload);
33974
34076
  const data = prepareCommunityPayload(payload);
33975
34077
  const cachedAt = client.cache && Date.now();
33976
- if (client.cache)
34078
+ if (client.cache) {
33977
34079
  ingestInCache(data, { cachedAt });
34080
+ saveCommunityUsers(data.communities, data.communityUsers);
34081
+ }
33978
34082
  const { communities } = data;
33979
34083
  return {
33980
34084
  data: communities[0],
@@ -34008,8 +34112,10 @@ const updateCommunity = async (communityId, patch) => {
34008
34112
  fireEvent('community.updated', payload);
34009
34113
  const data = prepareCommunityPayload(payload);
34010
34114
  const cachedAt = client.cache && Date.now();
34011
- if (client.cache)
34115
+ if (client.cache) {
34012
34116
  ingestInCache(data, { cachedAt });
34117
+ saveCommunityUsers(data.communities, data.communityUsers);
34118
+ }
34013
34119
  const { communities } = data;
34014
34120
  return {
34015
34121
  data: communities.find(community => community.communityId === communityId),
@@ -34039,8 +34145,10 @@ const getCommunity$1 = async (communityId) => {
34039
34145
  const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
34040
34146
  const data = prepareCommunityPayload(payload);
34041
34147
  const cachedAt = client.cache && Date.now();
34042
- if (client.cache)
34148
+ if (client.cache) {
34043
34149
  ingestInCache(data, { cachedAt });
34150
+ saveCommunityUsers(data.communities, data.communityUsers);
34151
+ }
34044
34152
  const { communities } = data;
34045
34153
  return {
34046
34154
  data: communities.find(community => community.communityId === communityId),
@@ -34583,7 +34691,7 @@ const observeCommunity = (communityId, callback) => {
34583
34691
  * TODO: handle cache receive cache option, and cache policy
34584
34692
  * TODO: check if querybyIds is supported
34585
34693
  */
34586
- class CommunitiesPaginationController extends PaginationController {
34694
+ class CommunitiesPaginationController$1 extends PaginationController {
34587
34695
  async getRequest(queryParams, token) {
34588
34696
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
34589
34697
  const options = token ? { token } : { limit };
@@ -34594,7 +34702,7 @@ class CommunitiesPaginationController extends PaginationController {
34594
34702
  }
34595
34703
  }
34596
34704
 
34597
- class CommunitiesQueryStreamController extends QueryStreamController {
34705
+ class CommunitiesQueryStreamController$1 extends QueryStreamController {
34598
34706
  constructor(query, cacheKey, notifyChange, preparePayload) {
34599
34707
  super(query, cacheKey);
34600
34708
  this.notifyChange = notifyChange;
@@ -34636,22 +34744,412 @@ class CommunitiesQueryStreamController extends QueryStreamController {
34636
34744
  }
34637
34745
  }
34638
34746
 
34639
- var EnumCommunityActions;
34747
+ var EnumCommunityActions$1;
34640
34748
  (function (EnumCommunityActions) {
34641
34749
  EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
34642
34750
  EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
34643
34751
  EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
34644
- })(EnumCommunityActions || (EnumCommunityActions = {}));
34752
+ })(EnumCommunityActions$1 || (EnumCommunityActions$1 = {}));
34753
+
34754
+ var EnumCommunityMemberActions$1;
34755
+ (function (EnumCommunityMemberActions) {
34756
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
34757
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
34758
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
34759
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
34760
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
34761
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
34762
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
34763
+ EnumCommunityMemberActions["OnMemberCountChanged"] = "OnMemberCountChanged";
34764
+ })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
34765
+
34766
+ /* begin_public_function
34767
+ id: community.membership.add_members
34768
+ */
34769
+ /**
34770
+ * ```js
34771
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
34772
+ * const updated = await CommunityRepository.moderation.addMembers(communityId, ['foo', 'bar'])
34773
+ * ```
34774
+ *
34775
+ * Adds a list of {@link Amity.InternalUser} to a {@link Amity.Community} to add users to
34776
+ *
34777
+ * @param communityId The ID of the {@link Amity.Community} to perform
34778
+ * @param userIds The list of IDs {@link Amity.InternalUser} to add
34779
+ * @returns A success boolean if the {@link Amity.InternalUser} were added to the {@link Amity.Community}
34780
+ *
34781
+ * @category Community API
34782
+ * @async
34783
+ */
34784
+ const addMembers = async (communityId, userIds) => {
34785
+ const client = getActiveClient();
34786
+ client.log('community/moderation/addMembers', communityId, userIds);
34787
+ const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
34788
+ fireEvent('community.userAdded', payload);
34789
+ const data = prepareMembershipPayload(payload, 'communityUsers');
34790
+ if (client.cache)
34791
+ ingestInCache(data);
34792
+ const { communityUsers } = data;
34793
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership === 'member');
34794
+ };
34795
+ /* end_public_function */
34796
+
34797
+ /* begin_public_function
34798
+ id: community.membership.remove_member
34799
+ */
34800
+ /**
34801
+ * ```js
34802
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
34803
+ * const updated = await CommunityRepository.moderation.removeMembers(communityId, ['foo', 'bar'])
34804
+ * ```
34805
+ *
34806
+ * Removes a list of {@link Amity.InternalUser} from a {@link Amity.Community}
34807
+ *
34808
+ * @param communityId The ID of the {@link Amity.Community} to edit
34809
+ * @param userIds The list of IDs {@link Amity.InternalUser} to remove
34810
+ * @returns A success boolean if the list of {@link Amity.InternalUser} were removed from the {@link Amity.Community}
34811
+ *
34812
+ * @category Community API
34813
+ * @async
34814
+ */
34815
+ const removeMembers = async (communityId, userIds) => {
34816
+ const client = getActiveClient();
34817
+ client.log('community/moderation/removeMembers', communityId, userIds);
34818
+ const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
34819
+ fireEvent('community.userRemoved', payload);
34820
+ const data = prepareMembershipPayload(payload, 'communityUsers');
34821
+ if (client.cache)
34822
+ ingestInCache(data);
34823
+ const { communityUsers } = data;
34824
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
34825
+ };
34826
+ /* end_public_function */
34827
+
34828
+ /**
34829
+ * TODO: handle cache receive cache option, and cache policy
34830
+ * TODO: check if querybyIds is supported
34831
+ */
34832
+ class CommunityMembersPaginationController extends PaginationController {
34833
+ async getRequest(queryParams, token) {
34834
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
34835
+ const options = token ? { token } : { limit };
34836
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
34837
+ params: Object.assign(Object.assign({}, params), { options }),
34838
+ });
34839
+ return queryResponse;
34840
+ }
34841
+ }
34842
+
34843
+ class CommunityMembersQueryStreamController extends QueryStreamController {
34844
+ constructor(query, cacheKey, notifyChange, preparePayload) {
34845
+ super(query, cacheKey);
34846
+ this.notifyChange = notifyChange;
34847
+ this.preparePayload = preparePayload;
34848
+ }
34849
+ async saveToMainDB(response) {
34850
+ const processedPayload = await this.preparePayload(response);
34851
+ const client = getActiveClient();
34852
+ const cachedAt = client.cache && Date.now();
34853
+ if (client.cache) {
34854
+ ingestInCache(processedPayload, { cachedAt });
34855
+ }
34856
+ }
34857
+ appendToQueryStream(response, direction, refresh = false) {
34858
+ var _a, _b;
34859
+ if (refresh) {
34860
+ pushToCache(this.cacheKey, {
34861
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
34862
+ });
34863
+ }
34864
+ else {
34865
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34866
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34867
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
34868
+ ...new Set([
34869
+ ...communityUsers,
34870
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
34871
+ ]),
34872
+ ] }));
34873
+ }
34874
+ }
34875
+ reactor(action) {
34876
+ return (community, communityMembers) => {
34877
+ var _a;
34878
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34879
+ if (!collection)
34880
+ return;
34881
+ if (action === EnumCommunityMemberActions$1.OnCommunityUserRoleAdded &&
34882
+ this.query.sortBy === 'displayName') {
34883
+ return;
34884
+ }
34885
+ communityMembers.forEach(communityMember => {
34886
+ const communityMemberCacheId = getResolver('communityUsers')({
34887
+ communityId: this.query.communityId,
34888
+ userId: communityMember.userId,
34889
+ });
34890
+ if (communityMember.communityMembership === 'none') {
34891
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
34892
+ }
34893
+ else if (!collection.data.includes(communityMemberCacheId)) {
34894
+ collection.data = [communityMemberCacheId, ...collection.data];
34895
+ }
34896
+ });
34897
+ pushToCache(this.cacheKey, collection);
34898
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
34899
+ };
34900
+ }
34901
+ subscribeRTE(createSubscriber) {
34902
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
34903
+ }
34904
+ }
34905
+
34906
+ class CommunityMembersLiveCollectionController extends LiveCollectionController {
34907
+ constructor(query, callback) {
34908
+ const queryStreamId = hash(query);
34909
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
34910
+ const paginationController = new CommunityMembersPaginationController(query);
34911
+ super(paginationController, queryStreamId, cacheKey, callback);
34912
+ this.query = query;
34913
+ this.queryStreamController = new CommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
34914
+ this.callback = callback.bind(this);
34915
+ this.loadPage({ initial: true });
34916
+ }
34917
+ setup() {
34918
+ var _a;
34919
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34920
+ if (!collection) {
34921
+ pushToCache(this.cacheKey, {
34922
+ data: [],
34923
+ params: {},
34924
+ });
34925
+ }
34926
+ }
34927
+ async persistModel(queryPayload) {
34928
+ await this.queryStreamController.saveToMainDB(queryPayload);
34929
+ }
34930
+ persistQueryStream({ response, direction, refresh, }) {
34931
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
34932
+ }
34933
+ startSubscription() {
34934
+ return this.queryStreamController.subscribeRTE([
34935
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
34936
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
34937
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions$1.OnCommunityUserBanned },
34938
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnCommunityUserChanged },
34939
+ { fn: onCommunityUserRoleAdded, action: EnumCommunityMemberActions$1.OnCommunityUserRoleAdded },
34940
+ {
34941
+ fn: onCommunityUserRoleRemoved,
34942
+ action: EnumCommunityMemberActions$1.OnCommunityUserRoleRemoved,
34943
+ },
34944
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions$1.OnCommunityUserUnbanned },
34945
+ ]);
34946
+ }
34947
+ notifyChange({ origin, loading, error }) {
34948
+ var _a, _b;
34949
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34950
+ if (!collection)
34951
+ return;
34952
+ const data = this.applyFilter((_b = collection.data
34953
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
34954
+ .filter(isNonNullable)
34955
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
34956
+ if (!this.shouldNotify(data) && origin === 'event')
34957
+ return;
34958
+ this.callback({
34959
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
34960
+ data,
34961
+ hasNextPage: !!this.paginationController.getNextToken(),
34962
+ loading,
34963
+ error,
34964
+ });
34965
+ }
34966
+ applyFilter(data) {
34967
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
34968
+ if (this.query.memberships) {
34969
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
34970
+ const memberships = this.query.memberships || [];
34971
+ return memberships.includes(communityMembership);
34972
+ });
34973
+ }
34974
+ if (this.query.search) {
34975
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
34976
+ }
34977
+ switch (this.query.sortBy) {
34978
+ case 'firstCreated':
34979
+ communityMembers = communityMembers.sort(sortByFirstCreated);
34980
+ break;
34981
+ case 'displayName':
34982
+ communityMembers = communityMembers.sort((a, b) => {
34983
+ var _a, _b, _c, _d;
34984
+ if (((_a = a === null || a === void 0 ? void 0 : a.user) === null || _a === void 0 ? void 0 : _a.displayName) && ((_b = b === null || b === void 0 ? void 0 : b.user) === null || _b === void 0 ? void 0 : _b.displayName)) {
34985
+ return (_c = a === null || a === void 0 ? void 0 : a.user) === null || _c === void 0 ? void 0 : _c.displayName.localeCompare((_d = b === null || b === void 0 ? void 0 : b.user) === null || _d === void 0 ? void 0 : _d.displayName);
34986
+ }
34987
+ return 0;
34988
+ });
34989
+ break;
34990
+ case 'lastCreated':
34991
+ default:
34992
+ communityMembers = communityMembers.sort(sortByLastCreated);
34993
+ break;
34994
+ }
34995
+ return communityMembers;
34996
+ }
34997
+ }
34998
+
34999
+ /*
35000
+ * Exported for testing
35001
+ * @hidden
35002
+ */
35003
+ const applyFilter = (data, params) => {
35004
+ let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
35005
+ if (params.memberships) {
35006
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
35007
+ const membership = params.memberships;
35008
+ return membership.includes(communityMembership);
35009
+ });
35010
+ }
35011
+ if (params.search) {
35012
+ communityMembers = filterBySearchTerm(communityMembers, params.search);
35013
+ }
35014
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
35015
+ communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
35016
+ return communityMembers;
35017
+ };
35018
+ /* begin_public_function
35019
+ id: community.membership.query
35020
+ */
35021
+ /**
35022
+ * ```js
35023
+ * import { getMembers } from '@amityco/ts-sdk-react-native'
35024
+ *
35025
+ * let communityMembers = []
35026
+ * const unsub = getMembers({
35027
+ * communityId: Amity.Community['communityId'],
35028
+ * }, response => merge(communityMembers, response.data))
35029
+ * ```
35030
+ *
35031
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
35032
+ *
35033
+ * @param params for querying community users
35034
+ * @param callback the function to call when new data are available
35035
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
35036
+ *
35037
+ * @category Community Live Collection
35038
+ */
35039
+ const getMembers = (params, callback, config) => {
35040
+ const { log, cache } = getActiveClient();
35041
+ if (!cache) {
35042
+ console.log(ENABLE_CACHE_MESSAGE);
35043
+ }
35044
+ const timestamp = Date.now();
35045
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
35046
+ const communityMemberLiveCollection = new CommunityMembersLiveCollectionController(params, resp => {
35047
+ console.log('resp', resp);
35048
+ callback(resp);
35049
+ });
35050
+ const disposers = communityMemberLiveCollection.startSubscription();
35051
+ const cacheKey = communityMemberLiveCollection.getCacheKey();
35052
+ disposers.push(() => {
35053
+ dropFromCache(cacheKey);
35054
+ });
35055
+ return () => {
35056
+ log(`getMembers(tmpid: ${timestamp}) > dispose`);
35057
+ disposers.forEach(fn => fn());
35058
+ };
35059
+ };
35060
+ /* end_public_function */
35061
+
35062
+ /**
35063
+ * TODO: handle cache receive cache option, and cache policy
35064
+ * TODO: check if querybyIds is supported
35065
+ */
35066
+ class SearchCommunityMembersPaginationController extends PaginationController {
35067
+ async getRequest(queryParams, token) {
35068
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
35069
+ const options = token ? { token } : { limit };
35070
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
35071
+ params: Object.assign(Object.assign({}, params), { options }),
35072
+ });
35073
+ return queryResponse;
35074
+ }
35075
+ }
35076
+
35077
+ class SearchCommunityMembersQueryStreamController extends QueryStreamController {
35078
+ constructor(query, cacheKey, notifyChange, preparePayload) {
35079
+ super(query, cacheKey);
35080
+ this.notifyChange = notifyChange;
35081
+ this.preparePayload = preparePayload;
35082
+ }
35083
+ async saveToMainDB(response) {
35084
+ const processedPayload = await this.preparePayload(response);
35085
+ const client = getActiveClient();
35086
+ const cachedAt = client.cache && Date.now();
35087
+ if (client.cache) {
35088
+ ingestInCache(processedPayload, { cachedAt });
35089
+ }
35090
+ }
35091
+ appendToQueryStream(response, direction, refresh = false) {
35092
+ var _a, _b;
35093
+ if (refresh) {
35094
+ pushToCache(this.cacheKey, {
35095
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35096
+ });
35097
+ }
35098
+ else {
35099
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35100
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35101
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
35102
+ ...new Set([
35103
+ ...communityUsers,
35104
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35105
+ ]),
35106
+ ] }));
35107
+ }
35108
+ }
35109
+ reactor(action) {
35110
+ return (community, communityMembers) => {
35111
+ var _a;
35112
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35113
+ if (!collection)
35114
+ return;
35115
+ communityMembers.forEach(communityMember => {
35116
+ const communityMemberCacheId = getResolver('communityUsers')({
35117
+ communityId: this.query.communityId,
35118
+ userId: communityMember.userId,
35119
+ });
35120
+ if (communityMember.communityMembership === 'none') {
35121
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
35122
+ }
35123
+ });
35124
+ pushToCache(this.cacheKey, collection);
35125
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
35126
+ };
35127
+ }
35128
+ subscribeRTE(createSubscriber) {
35129
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
35130
+ }
35131
+ }
35132
+
35133
+ var EnumCommunityMemberActions;
35134
+ (function (EnumCommunityMemberActions) {
35135
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
35136
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
35137
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
35138
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
35139
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
35140
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
35141
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
35142
+ })(EnumCommunityMemberActions || (EnumCommunityMemberActions = {}));
34645
35143
 
34646
35144
  /* eslint-disable no-use-before-define */
34647
- class SearchCommunityLiveCollectionController extends LiveCollectionController {
35145
+ class SearchCommunityMembersLiveCollectionController extends LiveCollectionController {
34648
35146
  constructor(query, callback) {
34649
35147
  const queryStreamId = hash(query);
34650
- const cacheKey = ['community', 'collection', queryStreamId];
34651
- const paginationController = new CommunitiesPaginationController(query);
35148
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
35149
+ const paginationController = new SearchCommunityMembersPaginationController(query);
34652
35150
  super(paginationController, queryStreamId, cacheKey, callback);
34653
35151
  this.query = query;
34654
- this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
35152
+ this.queryStreamController = new SearchCommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
34655
35153
  this.callback = callback.bind(this);
34656
35154
  this.loadPage({ initial: true });
34657
35155
  }
@@ -34673,8 +35171,146 @@ class SearchCommunityLiveCollectionController extends LiveCollectionController {
34673
35171
  }
34674
35172
  startSubscription() {
34675
35173
  return this.queryStreamController.subscribeRTE([
34676
- { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
34677
- { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
35174
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions.OnCommunityJoined },
35175
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
35176
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
35177
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
35178
+ {
35179
+ fn: onCommunityUserRoleRemoved,
35180
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
35181
+ },
35182
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
35183
+ ]);
35184
+ }
35185
+ notifyChange({ origin, loading, error }) {
35186
+ var _a, _b;
35187
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35188
+ if (!collection)
35189
+ return;
35190
+ const data = this.applyFilter((_b = collection.data
35191
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
35192
+ .filter(isNonNullable)
35193
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
35194
+ if (!this.shouldNotify(data) && origin === 'event')
35195
+ return;
35196
+ this.callback({
35197
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
35198
+ data,
35199
+ hasNextPage: !!this.paginationController.getNextToken(),
35200
+ loading,
35201
+ error,
35202
+ });
35203
+ }
35204
+ applyFilter(data) {
35205
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
35206
+ if (this.query.memberships) {
35207
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
35208
+ const memberships = this.query.memberships || [];
35209
+ return memberships.includes(communityMembership);
35210
+ });
35211
+ }
35212
+ if (this.query.search) {
35213
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
35214
+ }
35215
+ return communityMembers;
35216
+ }
35217
+ }
35218
+
35219
+ /* begin_public_function
35220
+ id: community.membership.query
35221
+ */
35222
+ /**
35223
+ * ```js
35224
+ * import { searchMembers } from '@amityco/ts-sdk-react-native'
35225
+ *
35226
+ * let communityMembers = []
35227
+ * const unsub = searchMembers({
35228
+ * communityId: Amity.Community['communityId'],
35229
+ * }, response => merge(communityMembers, response.data))
35230
+ * ```
35231
+ *
35232
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
35233
+ *
35234
+ * @param params for querying community users
35235
+ * @param callback the function to call when new data are available
35236
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
35237
+ *
35238
+ * @category Community Live Collection
35239
+ */
35240
+ const searchMembers = (params, callback, config) => {
35241
+ const { log, cache } = getActiveClient();
35242
+ if (!cache) {
35243
+ console.log(ENABLE_CACHE_MESSAGE);
35244
+ }
35245
+ const timestamp = Date.now();
35246
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
35247
+ const searchCommunityMemberLiveCollection = new SearchCommunityMembersLiveCollectionController(params, resp => {
35248
+ callback(resp);
35249
+ });
35250
+ const disposers = searchCommunityMemberLiveCollection.startSubscription();
35251
+ const cacheKey = searchCommunityMemberLiveCollection.getCacheKey();
35252
+ disposers.push(() => {
35253
+ dropFromCache(cacheKey);
35254
+ });
35255
+ return () => {
35256
+ log(`getMembers(tmpid: ${timestamp}) > dispose`);
35257
+ disposers.forEach(fn => fn());
35258
+ };
35259
+ };
35260
+ /* end_public_function */
35261
+
35262
+ var index$a = /*#__PURE__*/Object.freeze({
35263
+ __proto__: null,
35264
+ addMembers: addMembers,
35265
+ removeMembers: removeMembers,
35266
+ applyFilter: applyFilter,
35267
+ getMembers: getMembers,
35268
+ searchMembers: searchMembers,
35269
+ onCommunityUserAdded: onCommunityUserAdded,
35270
+ onCommunityUserRemoved: onCommunityUserRemoved,
35271
+ onCommunityUserBanned: onCommunityUserBanned,
35272
+ onCommunityUserChanged: onCommunityUserChanged,
35273
+ onCommunityUserUnbanned: onCommunityUserUnbanned,
35274
+ onCommunityUserRoleAdded: onCommunityUserRoleAdded,
35275
+ onCommunityUserRoleRemoved: onCommunityUserRoleRemoved,
35276
+ onCommunityJoined: onCommunityJoined,
35277
+ onCommunityLeft: onCommunityLeft
35278
+ });
35279
+
35280
+ class SearchCommunityLiveCollectionController extends LiveCollectionController {
35281
+ constructor(query, callback) {
35282
+ const queryStreamId = hash(query);
35283
+ const cacheKey = ['community', 'collection', queryStreamId];
35284
+ const paginationController = new CommunitiesPaginationController$1(query);
35285
+ super(paginationController, queryStreamId, cacheKey, callback);
35286
+ this.query = query;
35287
+ this.queryStreamController = new CommunitiesQueryStreamController$1(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
35288
+ this.callback = callback.bind(this);
35289
+ this.loadPage({ initial: true });
35290
+ }
35291
+ setup() {
35292
+ var _a;
35293
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35294
+ if (!collection) {
35295
+ pushToCache(this.cacheKey, {
35296
+ data: [],
35297
+ params: {},
35298
+ });
35299
+ }
35300
+ }
35301
+ async persistModel(queryPayload) {
35302
+ await this.queryStreamController.saveToMainDB(queryPayload);
35303
+ }
35304
+ persistQueryStream({ response, direction, refresh, }) {
35305
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
35306
+ }
35307
+ startSubscription() {
35308
+ return this.queryStreamController.subscribeRTE([
35309
+ { fn: onCommunityDeleted, action: EnumCommunityActions$1.OnCommunityDeleted },
35310
+ { fn: onCommunityUpdated, action: EnumCommunityActions$1.OnCommunityUpdated },
35311
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
35312
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
35313
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnMemberCountChanged },
34678
35314
  ]);
34679
35315
  }
34680
35316
  notifyChange({ origin, loading, error }) {
@@ -34720,7 +35356,7 @@ class SearchCommunityLiveCollectionController extends LiveCollectionController {
34720
35356
  */
34721
35357
  /**
34722
35358
  * ```js
34723
- * import { CommunityRepository } from '@amityco/ts-sdk'
35359
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
34724
35360
  *
34725
35361
  * let communities = []
34726
35362
  * const unsub = CommunityRepository.searchCommunities({
@@ -34755,50 +35391,166 @@ const searchCommunities = (params, callback, config) => {
34755
35391
  /* end_public_function */
34756
35392
 
34757
35393
  /**
34758
- * ```js
34759
- * import { queryCommunities } from '@amityco/ts-sdk-react-native'
34760
- * const communities = await queryCommunities()
34761
- * ```
34762
- *
34763
- * Queries a paginable list of {@link Amity.Community} objects
34764
- * Search is performed by displayName such as `.startsWith(search)`
34765
- *
34766
- * @param query The query parameters
34767
- * @returns A page of {@link Amity.Community} objects
34768
- *
34769
- * @category Community API
34770
- * @async
35394
+ * TODO: handle cache receive cache option, and cache policy
35395
+ * TODO: check if querybyIds is supported
34771
35396
  */
34772
- const queryCommunities = async (query) => {
34773
- const client = getActiveClient();
34774
- client.log('channel/queryCommunities', query);
34775
- // safe decapsulation
34776
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit = 10 } = _a, params = __rest(_a, ["page", "limit"]);
34777
- const _b = params !== null && params !== void 0 ? params : {}, { displayName, membership, includeDeleted } = _b, restParams = __rest(_b, ["displayName", "membership", "includeDeleted"]);
34778
- const options = (() => {
34779
- if (page)
34780
- return { token: page };
34781
- if (limit)
34782
- return { limit };
34783
- return undefined;
34784
- })();
34785
- // API-FIX: parameters should be querystring.
34786
- // API-FIX: backend doesn't answer Amity.Response
34787
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
34788
- const { data } = await client.http.get(`/api/v3/communities`, {
34789
- params: Object.assign(Object.assign({}, restParams), { isDeleted: inferIsDeleted(includeDeleted), keyword: displayName, filter: membership, options }),
34790
- });
34791
- const { paging } = data, payload = __rest(data, ["paging"]);
34792
- const unpackedPayload = prepareCommunityPayload(payload);
34793
- const { communities } = unpackedPayload;
34794
- const cachedAt = client.cache && Date.now();
34795
- if (client.cache) {
34796
- ingestInCache(unpackedPayload, { cachedAt });
34797
- const cacheKey = ['community', 'query', Object.assign(Object.assign({}, params), { options })];
34798
- pushToCache(cacheKey, { communities: communities.map(getResolver('community')), paging });
35397
+ class CommunitiesPaginationController extends PaginationController {
35398
+ async getRequest(queryParams, token) {
35399
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
35400
+ const options = token ? { token } : { limit };
35401
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
35402
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
35403
+ });
35404
+ return queryResponse;
34799
35405
  }
34800
- return { data: communities, cachedAt, paging };
34801
- };
35406
+ }
35407
+
35408
+ var EnumCommunityActions;
35409
+ (function (EnumCommunityActions) {
35410
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
35411
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
35412
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
35413
+ })(EnumCommunityActions || (EnumCommunityActions = {}));
35414
+
35415
+ class CommunitiesQueryStreamController extends QueryStreamController {
35416
+ constructor(query, cacheKey, notifyChange, preparePayload) {
35417
+ super(query, cacheKey);
35418
+ this.notifyChange = notifyChange;
35419
+ this.preparePayload = preparePayload;
35420
+ }
35421
+ async saveToMainDB(response) {
35422
+ const processedPayload = await this.preparePayload(response);
35423
+ const client = getActiveClient();
35424
+ const cachedAt = client.cache && Date.now();
35425
+ if (client.cache) {
35426
+ ingestInCache(processedPayload, { cachedAt });
35427
+ saveCommunityUsers(response.communities, response.communityUsers);
35428
+ }
35429
+ }
35430
+ appendToQueryStream(response, direction, refresh = false) {
35431
+ var _a, _b;
35432
+ if (refresh) {
35433
+ pushToCache(this.cacheKey, {
35434
+ data: response.communities.map(getResolver('community')),
35435
+ });
35436
+ }
35437
+ else {
35438
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35439
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35440
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
35441
+ }
35442
+ }
35443
+ reactor(action) {
35444
+ return (community) => {
35445
+ var _a;
35446
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35447
+ if (!collection)
35448
+ return;
35449
+ if (this.query.displayName && action === EnumCommunityActions.OnCommunityCreated) {
35450
+ return;
35451
+ }
35452
+ /*
35453
+ * Simply update a collection and let responder decide what to do with data
35454
+ */
35455
+ collection.data = [...new Set([community.communityId, ...collection.data])];
35456
+ pushToCache(this.cacheKey, collection);
35457
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
35458
+ };
35459
+ }
35460
+ subscribeRTE(createSubscriber) {
35461
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
35462
+ }
35463
+ }
35464
+
35465
+ class CommunityLiveCollectionController extends LiveCollectionController {
35466
+ constructor(query, callback) {
35467
+ const queryStreamId = hash(query);
35468
+ const cacheKey = ['community', 'collection', queryStreamId];
35469
+ const paginationController = new CommunitiesPaginationController(query);
35470
+ super(paginationController, queryStreamId, cacheKey, callback);
35471
+ this.query = query;
35472
+ this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
35473
+ this.callback = callback.bind(this);
35474
+ this.loadPage({ initial: true });
35475
+ }
35476
+ setup() {
35477
+ var _a;
35478
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35479
+ if (!collection) {
35480
+ pushToCache(this.cacheKey, {
35481
+ data: [],
35482
+ params: {},
35483
+ });
35484
+ }
35485
+ }
35486
+ async persistModel(queryPayload) {
35487
+ await this.queryStreamController.saveToMainDB(queryPayload);
35488
+ }
35489
+ persistQueryStream({ response, direction, refresh, }) {
35490
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
35491
+ }
35492
+ startSubscription() {
35493
+ return this.queryStreamController.subscribeRTE([
35494
+ { fn: onCommunityCreated, action: EnumCommunityActions.OnCommunityCreated },
35495
+ { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
35496
+ { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
35497
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
35498
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
35499
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnMemberCountChanged },
35500
+ ]);
35501
+ }
35502
+ notifyChange({ origin, loading, error }) {
35503
+ var _a, _b;
35504
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35505
+ if (!collection)
35506
+ return;
35507
+ const data = this.applyFilter((_b = collection.data
35508
+ .map(id => pullFromCache(['community', 'get', id]))
35509
+ .filter(Boolean)
35510
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
35511
+ if (!this.shouldNotify(data) && origin === 'event')
35512
+ return;
35513
+ this.callback({
35514
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
35515
+ data,
35516
+ hasNextPage: !!this.paginationController.getNextToken(),
35517
+ loading,
35518
+ error,
35519
+ });
35520
+ }
35521
+ applyFilter(data) {
35522
+ const { userId } = getActiveClient();
35523
+ let communities = data;
35524
+ if (this.query.includeDeleted) {
35525
+ communities = filterByPropEquality(communities, 'isDeleted', false);
35526
+ }
35527
+ if (this.query.categoryId) {
35528
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
35529
+ }
35530
+ if (this.query.tags) {
35531
+ communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = this.query.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
35532
+ }
35533
+ if (this.query.membership && userId) {
35534
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
35535
+ }
35536
+ if (!this.query.displayName) {
35537
+ const sortFn = (() => {
35538
+ switch (this.query.sortBy) {
35539
+ case 'firstCreated':
35540
+ return sortByFirstCreated;
35541
+ case 'lastCreated':
35542
+ return sortByLastCreated;
35543
+ case 'displayName':
35544
+ return sortByDisplayName;
35545
+ default:
35546
+ return sortByLastCreated;
35547
+ }
35548
+ })();
35549
+ communities = communities.sort(sortFn);
35550
+ }
35551
+ return communities;
35552
+ }
35553
+ }
34802
35554
 
34803
35555
  /* begin_public_function
34804
35556
  id: community.query
@@ -34822,98 +35574,15 @@ const queryCommunities = async (query) => {
34822
35574
  * @category Community Live Collection
34823
35575
  */
34824
35576
  const getCommunities = (params, callback, config) => {
34825
- const { log, cache, userId } = getActiveClient();
35577
+ const { log, cache } = getActiveClient();
34826
35578
  if (!cache) {
34827
35579
  console.log(ENABLE_CACHE_MESSAGE);
34828
35580
  }
34829
35581
  const timestamp = Date.now();
34830
35582
  log(`getCommunities(tmpid: ${timestamp}) > listen`);
34831
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
34832
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
34833
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
34834
- const disposers = [];
34835
- const cacheKey = ['community', 'collection', queryParams];
34836
- const responder = (data) => {
34837
- var _a, _b;
34838
- let communities = (_a = data.data
34839
- .map(communityId => pullFromCache(['community', 'get', communityId]))
34840
- .filter(Boolean)
34841
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
34842
- communities = filterByStringComparePartially(communities, 'displayName', params.displayName);
34843
- if (!params.includeDeleted) {
34844
- communities = filterByPropEquality(communities, 'isDeleted', false);
34845
- }
34846
- if (params.categoryId) {
34847
- communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(params.categoryId); });
34848
- }
34849
- if (params.tags) {
34850
- communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
34851
- }
34852
- if (params.membership && userId) {
34853
- communities = filterByCommunityMembership(communities, params.membership, userId);
34854
- }
34855
- const sortBy = params.sortBy || 'lastCreated';
34856
- if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
34857
- communities = communities.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
34858
- }
34859
- /*
34860
- * The server returns communities with empty | null displayName's first before
34861
- * returning sorted list of communities with displayNames
34862
- *
34863
- * This section needs to be updated as displayNames can be null as well
34864
- */
34865
- if (sortBy === 'displayName') {
34866
- communities = communities
34867
- // this needs to be aligned with the backend data type
34868
- .map(c => (c.displayName ? c : Object.assign(Object.assign({}, c), { displayName: '' })))
34869
- // @ts-ignore
34870
- .sort(sortByDisplayName);
34871
- }
34872
- callback({
34873
- onNextPage: onFetch,
34874
- data: communities,
34875
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
34876
- loading: data.loading,
34877
- error: data.error,
34878
- });
34879
- };
34880
- const realtimeRouter = (_) => (community) => {
34881
- var _a;
34882
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34883
- if (!collection)
34884
- return;
34885
- /*
34886
- * Simply update collection and let responder decide what to do with data
34887
- */
34888
- collection.data = [...new Set([community.communityId, ...collection.data])];
34889
- pushToCache(cacheKey, collection);
34890
- responder(collection);
34891
- };
34892
- const onFetch = (initial = false) => {
34893
- var _a, _b;
34894
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34895
- const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34896
- if (!initial && communities.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
34897
- return;
34898
- const query = createQuery(queryCommunities, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
34899
- runQuery(query, ({ data: result, error, loading, paging }) => {
34900
- const data = {
34901
- loading,
34902
- error,
34903
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
34904
- data: communities,
34905
- };
34906
- if (result) {
34907
- data.data = initial
34908
- ? result.map(getResolver('community'))
34909
- : [...new Set([...communities, ...result.map(getResolver('community'))])];
34910
- }
34911
- pushToCache(cacheKey, data);
34912
- responder(data);
34913
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
34914
- };
34915
- disposers.push(onCommunityCreated(realtimeRouter()), onCommunityDeleted(realtimeRouter()), onCommunityUpdated(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityLeft(realtimeRouter()), onCommunityUserChanged(realtimeRouter()));
34916
- onFetch(true);
35583
+ const communitiesLiveCollection = new CommunityLiveCollectionController(params, callback);
35584
+ const disposers = communitiesLiveCollection.startSubscription();
35585
+ const cacheKey = communitiesLiveCollection.getCacheKey();
34917
35586
  disposers.push(() => dropFromCache(cacheKey));
34918
35587
  return () => {
34919
35588
  log(`getCommunities(tmpid: ${timestamp}) > dispose`);
@@ -35371,7 +36040,7 @@ const unbanMembers = async (communityId, userIds) => {
35371
36040
  };
35372
36041
  /* end_public_function */
35373
36042
 
35374
- var index$a = /*#__PURE__*/Object.freeze({
36043
+ var index$9 = /*#__PURE__*/Object.freeze({
35375
36044
  __proto__: null,
35376
36045
  addRoles: addRoles,
35377
36046
  removeRoles: removeRoles,
@@ -35379,299 +36048,10 @@ var index$a = /*#__PURE__*/Object.freeze({
35379
36048
  unbanMembers: unbanMembers
35380
36049
  });
35381
36050
 
35382
- /* begin_public_function
35383
- id: community.membership.add_members
35384
- */
35385
- /**
35386
- * ```js
35387
- * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
35388
- * const updated = await CommunityRepository.moderation.addMembers(communityId, ['foo', 'bar'])
35389
- * ```
35390
- *
35391
- * Adds a list of {@link Amity.InternalUser} to a {@link Amity.Community} to add users to
35392
- *
35393
- * @param communityId The ID of the {@link Amity.Community} to perform
35394
- * @param userIds The list of IDs {@link Amity.InternalUser} to add
35395
- * @returns A success boolean if the {@link Amity.InternalUser} were added to the {@link Amity.Community}
35396
- *
35397
- * @category Community API
35398
- * @async
35399
- */
35400
- const addMembers = async (communityId, userIds) => {
35401
- const client = getActiveClient();
35402
- client.log('community/moderation/addMembers', communityId, userIds);
35403
- const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
35404
- fireEvent('community.userAdded', payload);
35405
- const data = prepareMembershipPayload(payload, 'communityUsers');
35406
- if (client.cache)
35407
- ingestInCache(data);
35408
- const { communityUsers } = data;
35409
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership === 'member');
35410
- };
35411
- /* end_public_function */
35412
-
35413
- /* begin_public_function
35414
- id: community.membership.remove_member
35415
- */
35416
- /**
35417
- * ```js
35418
- * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
35419
- * const updated = await CommunityRepository.moderation.removeMembers(communityId, ['foo', 'bar'])
35420
- * ```
35421
- *
35422
- * Removes a list of {@link Amity.InternalUser} from a {@link Amity.Community}
35423
- *
35424
- * @param communityId The ID of the {@link Amity.Community} to edit
35425
- * @param userIds The list of IDs {@link Amity.InternalUser} to remove
35426
- * @returns A success boolean if the list of {@link Amity.InternalUser} were removed from the {@link Amity.Community}
35427
- *
35428
- * @category Community API
35429
- * @async
35430
- */
35431
- const removeMembers = async (communityId, userIds) => {
35432
- const client = getActiveClient();
35433
- client.log('community/moderation/removeMembers', communityId, userIds);
35434
- const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
35435
- fireEvent('community.userRemoved', payload);
35436
- const data = prepareMembershipPayload(payload, 'communityUsers');
35437
- if (client.cache)
35438
- ingestInCache(data);
35439
- const { communityUsers } = data;
35440
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
35441
- };
35442
- /* end_public_function */
35443
-
35444
- /**
35445
- * ```js
35446
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
35447
- * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
35448
- * ```
35449
- *
35450
- * Queries a paginable list of {@link Amity.CommunityUser} objects
35451
- *
35452
- * @param query The query parameters
35453
- * @returns A page of {@link Amity.CommunityUser} objects
35454
- *
35455
- * @category Community API
35456
- * @async
35457
- * */
35458
- const queryCommunityMembers = async (query) => {
35459
- const client = getActiveClient();
35460
- client.log('community/queryCommunityMembers', query);
35461
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit } = _a, params = __rest(_a, ["page", "limit"]);
35462
- const options = (() => {
35463
- if (page)
35464
- return { token: page };
35465
- if (limit)
35466
- return { limit };
35467
- return undefined;
35468
- })();
35469
- const { data: queryPayload } = await client.http.get(`/api/v3/communities/${params.communityId}/users`, {
35470
- params: Object.assign(Object.assign({}, params), { options }),
35471
- });
35472
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
35473
- const preparedPayload = prepareMembershipPayload(payload, 'communityUsers');
35474
- const { communityUsers } = preparedPayload;
35475
- const cachedAt = client.cache && Date.now();
35476
- if (client.cache) {
35477
- ingestInCache(preparedPayload, { cachedAt });
35478
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
35479
- pushToCache(cacheKey, {
35480
- communityUsers: communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35481
- paging,
35482
- });
35483
- }
35484
- return { data: communityUsers, cachedAt, paging };
35485
- };
35486
- /**
35487
- * ```js
35488
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
35489
- * const communityMembers = await queryCommunityMembers(query)
35490
- * ```
35491
- *
35492
- * Queries a paginable list of {@link Amity.InternalPost} objects from cache
35493
- *
35494
- * @param query The query parameters
35495
- * @returns posts
35496
- *
35497
- * @category Post API
35498
- */
35499
- queryCommunityMembers.locally = (query) => {
35500
- var _a, _b;
35501
- const client = getActiveClient();
35502
- client.log('community/queryCommunityMembers', query);
35503
- if (!client.cache)
35504
- return;
35505
- const _c = query !== null && query !== void 0 ? query : {}, { page, limit } = _c, params = __rest(_c, ["page", "limit"]);
35506
- const options = (() => {
35507
- if (page)
35508
- return { token: page };
35509
- if (limit)
35510
- return { limit };
35511
- return undefined;
35512
- })();
35513
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
35514
- const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
35515
- if (!(data === null || data === void 0 ? void 0 : data.communityUsers.length))
35516
- return;
35517
- const communityUsers = data.communityUsers
35518
- .map(key => pullFromCache(['communityUsers', 'get', key]))
35519
- .filter(Boolean)
35520
- .map(({ data }) => data);
35521
- const { paging } = data;
35522
- return communityUsers.length === ((_b = data === null || data === void 0 ? void 0 : data.communityUsers) === null || _b === void 0 ? void 0 : _b.length)
35523
- ? { data: communityUsers, cachedAt, paging }
35524
- : undefined;
35525
- };
35526
-
35527
- /*
35528
- * Exported for testing
35529
- * @hidden
35530
- */
35531
- const applyFilter = (data, params) => {
35532
- let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
35533
- if (params.memberships) {
35534
- communityMembers = communityMembers.filter(({ communityMembership }) => {
35535
- const membership = params.memberships;
35536
- return membership.includes(communityMembership);
35537
- });
35538
- }
35539
- if (params.search) {
35540
- communityMembers = filterBySearchTerm(communityMembers, params.search);
35541
- }
35542
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
35543
- communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
35544
- return communityMembers;
35545
- };
35546
- /* begin_public_function
35547
- id: community.membership.query
35548
- */
35549
- /**
35550
- * ```js
35551
- * import { getMembers } from '@amityco/ts-sdk-react-native'
35552
- *
35553
- * let communityMembers = []
35554
- * const unsub = getMembers({
35555
- * communityId: Amity.Community['communityId'],
35556
- * }, response => merge(communityMembers, response.data))
35557
- * ```
35558
- *
35559
- * Observe all mutations on a list of {@link Amity.CommunityUser}s
35560
- *
35561
- * @param params for querying community users
35562
- * @param callback the function to call when new data are available
35563
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
35564
- *
35565
- * @category Community Live Collection
35566
- */
35567
- const getMembers = (params, callback, config) => {
35568
- const { log, cache } = getActiveClient();
35569
- if (!cache) {
35570
- console.log(ENABLE_CACHE_MESSAGE);
35571
- }
35572
- const timestamp = Date.now();
35573
- log(`getMembers(tmpid: ${timestamp}) > listen`);
35574
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
35575
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
35576
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
35577
- const disposers = [];
35578
- const cacheKey = ['communityUsers', 'collection', queryParams];
35579
- const cacheByCommunityIdKey = [
35580
- 'communityUsers',
35581
- 'collection',
35582
- { communityId: params.communityId },
35583
- ];
35584
- const responder = (data, isEventModel = false) => {
35585
- var _a, _b;
35586
- const communityMembers = (_a = data.data
35587
- .map(id => pullFromCache(['communityUsers', 'get', id]))
35588
- .filter(Boolean)
35589
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
35590
- callback({
35591
- onNextPage: onFetch,
35592
- data: isEventModel ? applyFilter(communityMembers, params) : communityMembers,
35593
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
35594
- loading: data.loading,
35595
- error: data.error,
35596
- });
35597
- };
35598
- const realtimeRouter = (_) => (_, communityMembers) => {
35599
- var _a;
35600
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35601
- if (!collection) {
35602
- return;
35603
- }
35604
- const communityMemberCacheIds = communityMembers
35605
- .map(communityMember => {
35606
- if (params.communityId !== communityMember.communityId) {
35607
- return;
35608
- }
35609
- const communityMemberCacheId = getResolver('communityUsers')({
35610
- communityId: params.communityId,
35611
- userId: communityMember.userId,
35612
- });
35613
- return communityMemberCacheId;
35614
- })
35615
- .filter(isNonNullable);
35616
- collection.data = [...new Set([...communityMemberCacheIds, ...collection.data])];
35617
- pushToCache(cacheKey, collection);
35618
- pushToCache(cacheByCommunityIdKey, collection);
35619
- responder(collection, true);
35620
- };
35621
- const onFetch = (initial = false) => {
35622
- var _a, _b;
35623
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35624
- const communityMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35625
- if (!initial && communityMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
35626
- return;
35627
- const query = createQuery(queryCommunityMembers, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
35628
- runQuery(query, ({ data: result, error, loading, paging }) => {
35629
- const data = {
35630
- loading,
35631
- error,
35632
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
35633
- data: communityMembers,
35634
- };
35635
- if (result) {
35636
- data.data = [
35637
- ...new Set([...communityMembers, ...result.map(getResolver('communityUsers'))]),
35638
- ];
35639
- }
35640
- pushToCache(cacheKey, data);
35641
- pushToCache(cacheByCommunityIdKey, data);
35642
- responder(data);
35643
- }, queryOptions(policy));
35644
- };
35645
- disposers.push(onCommunityLeft(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityUserBanned(realtimeRouter()), onCommunityUserUnbanned(realtimeRouter()), onCommunityUserChanged(realtimeRouter()), onCommunityUserRoleAdded(realtimeRouter()), onCommunityUserRoleRemoved(realtimeRouter()));
35646
- onFetch(true);
35647
- return () => {
35648
- log(`getMembers(tmpid: ${timestamp}) > dispose`);
35649
- disposers.forEach(fn => fn());
35650
- };
35651
- };
35652
- /* end_public_function */
35653
-
35654
- var index$9 = /*#__PURE__*/Object.freeze({
35655
- __proto__: null,
35656
- addMembers: addMembers,
35657
- removeMembers: removeMembers,
35658
- applyFilter: applyFilter,
35659
- getMembers: getMembers,
35660
- onCommunityUserAdded: onCommunityUserAdded,
35661
- onCommunityUserRemoved: onCommunityUserRemoved,
35662
- onCommunityUserBanned: onCommunityUserBanned,
35663
- onCommunityUserChanged: onCommunityUserChanged,
35664
- onCommunityUserUnbanned: onCommunityUserUnbanned,
35665
- onCommunityUserRoleAdded: onCommunityUserRoleAdded,
35666
- onCommunityUserRoleRemoved: onCommunityUserRoleRemoved,
35667
- onCommunityJoined: onCommunityJoined,
35668
- onCommunityLeft: onCommunityLeft
35669
- });
35670
-
35671
36051
  var index$8 = /*#__PURE__*/Object.freeze({
35672
36052
  __proto__: null,
35673
- Moderation: index$a,
35674
- Membership: index$9,
36053
+ Moderation: index$9,
36054
+ Membership: index$a,
35675
36055
  getCommunityByIds: getCommunities$1,
35676
36056
  createCommunity: createCommunity,
35677
36057
  updateCommunity: updateCommunity,