@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.cjs.js CHANGED
@@ -10,6 +10,7 @@ var HttpAgent = require('agentkeepalive');
10
10
  var io = require('socket.io-client');
11
11
  var AsyncStorage = require('@react-native-async-storage/async-storage');
12
12
  var uuid$1 = require('react-native-uuid');
13
+ var reactNative = require('react-native');
13
14
  var hash = require('object-hash');
14
15
  var Hls = require('hls.js');
15
16
 
@@ -117,8 +118,8 @@ const PostContentType = Object.freeze({
117
118
 
118
119
  function getVersion() {
119
120
  try {
120
- // the string ''v6.24.0-cjs'' should be replaced by actual value by @rollup/plugin-replace
121
- return 'v6.24.0-cjs';
121
+ // the string ''v6.24.1-cjs'' should be replaced by actual value by @rollup/plugin-replace
122
+ return 'v6.24.1-cjs';
122
123
  }
123
124
  catch (error) {
124
125
  return '__dev__';
@@ -673,6 +674,18 @@ class ASCConnectionError extends ASCError {
673
674
  : 800210 /* Amity.ClientError.CONNECTION_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
674
675
  this.event = event;
675
676
  }
677
+ }
678
+ /**
679
+ * Input sanitization related error
680
+ * @category Errors
681
+ */
682
+ class ASCInvalidParameterError extends ASCError {
683
+ /**
684
+ * @param message A custom error message
685
+ */
686
+ constructor(message) {
687
+ super(message, 800110 /* Amity.ClientError.INVALID_PARAMETERS */, "error" /* Amity.ErrorLevel.ERROR */);
688
+ }
676
689
  }
677
690
 
678
691
  let activeClient = null;
@@ -8705,7 +8718,8 @@ const registerEventListeners = () => {
8705
8718
  events.push("resume" /* Amity.MarkerSyncEvent.RESUME */);
8706
8719
  }), onMessageCreatedMqtt(message => {
8707
8720
  // only conversation, community and broadcast types can sync
8708
- if (isUnreadCountSupport(message))
8721
+ const client = getActiveClient();
8722
+ if (isUnreadCountSupport(message) && message.creatorId !== client.userId)
8709
8723
  events.push("new message" /* Amity.MarkerSyncEvent.NEW_MESSAGE */);
8710
8724
  }), 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(() =>
8711
8725
  /*
@@ -9106,7 +9120,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
9106
9120
  */
9107
9121
  /**
9108
9122
  * ```js
9109
- * import { Client } from '@amityco/ts-sdk'
9123
+ * import { Client } from '@amityco/ts-sdk-react-native'
9110
9124
  * const success = await Client.secureLogout()
9111
9125
  * ```
9112
9126
  *
@@ -9149,6 +9163,43 @@ const isConnected = () => {
9149
9163
  client.ws.connected);
9150
9164
  };
9151
9165
 
9166
+ const registerPushNotification = async (deviceToken) => {
9167
+ const client = getActiveClient();
9168
+ let platform;
9169
+ if (reactNative.Platform.OS === 'ios' || reactNative.Platform.OS === 'android') {
9170
+ platform = reactNative.Platform.OS;
9171
+ }
9172
+ else {
9173
+ throw new ASCInvalidParameterError('Unsupported platform');
9174
+ }
9175
+ const deviceId = getDeviceId();
9176
+ const { data: { status, error }, } = await client.http.post('/v1/notification', {
9177
+ userId: client.userId,
9178
+ deviceId,
9179
+ platform,
9180
+ token: deviceToken,
9181
+ }, { headers: { 'X-API-Key': client.apiKey } });
9182
+ if (error) {
9183
+ throw new ASCApiError(error, 500000 /* Amity.ServerError.BUSINESS_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
9184
+ }
9185
+ return status === 'success';
9186
+ };
9187
+
9188
+ const unregisterPushNotification = async () => {
9189
+ const client = getActiveClient();
9190
+ const deviceId = getDeviceId();
9191
+ const { data: { status, error }, } = await client.http.delete('/v1/notification', {
9192
+ data: {
9193
+ deviceId,
9194
+ },
9195
+ headers: { 'X-API-Key': client.apiKey },
9196
+ });
9197
+ if (error) {
9198
+ throw new ASCApiError(error, 500000 /* Amity.ServerError.BUSINESS_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
9199
+ }
9200
+ return status === 'success';
9201
+ };
9202
+
9152
9203
  /**
9153
9204
  * ```js
9154
9205
  * import { onChannelMarkerFetched } from '@amityco/ts-sdk-react-native'
@@ -9462,6 +9513,9 @@ function isEqual(x, y) {
9462
9513
  }));
9463
9514
  }
9464
9515
 
9516
+ /**
9517
+ * @deprecated This function is deprecated
9518
+ */
9465
9519
  const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
9466
9520
  const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
9467
9521
  const { cache } = getActiveClient();
@@ -9676,6 +9730,8 @@ var index$k = /*#__PURE__*/Object.freeze({
9676
9730
  renewal: renewal,
9677
9731
  markerSync: markerSync,
9678
9732
  enableUnreadCount: enableUnreadCount,
9733
+ registerPushNotification: registerPushNotification,
9734
+ unregisterPushNotification: unregisterPushNotification,
9679
9735
  onConnectionError: onConnectionError,
9680
9736
  onClientDisconnected: onClientDisconnected,
9681
9737
  onClientBanned: onClientBanned,
@@ -11812,8 +11868,10 @@ getFile.locally = (fileId) => {
11812
11868
  const uploadFile = async (formData, onProgress) => {
11813
11869
  const client = getActiveClient();
11814
11870
  client.log('file/uploadFile', formData);
11815
- if (!formData.getAll('files').length)
11871
+ const files = formData.getAll('files');
11872
+ if (!files.length)
11816
11873
  throw new Error('The formData object must have a `files` key.');
11874
+ formData.append('preferredFilename', files[0].name);
11817
11875
  const headers = 'getHeaders' in formData
11818
11876
  ? formData.getHeaders()
11819
11877
  : { 'content-type': 'multipart/form-data' };
@@ -11895,8 +11953,10 @@ const fileUrlWithSize = (fileUrl, size) => {
11895
11953
  const uploadVideo = async (formData, feedType, onProgress) => {
11896
11954
  const client = getActiveClient();
11897
11955
  client.log('file/uploadVideo', formData);
11898
- if (!formData.getAll('files').length)
11956
+ const files = formData.getAll('files');
11957
+ if (!files.length)
11899
11958
  throw new Error('The formData object must have a `files` key.');
11959
+ formData.append('preferredFilename', files[0].name);
11900
11960
  if (feedType) {
11901
11961
  formData.append('feedType', feedType);
11902
11962
  }
@@ -11942,8 +12002,10 @@ const uploadVideo = async (formData, feedType, onProgress) => {
11942
12002
  const uploadImage = async (formData, onProgress) => {
11943
12003
  const client = getActiveClient();
11944
12004
  client.log('file/uploadImage', formData);
11945
- if (!formData.getAll('files').length)
12005
+ const files = formData.getAll('files');
12006
+ if (!files.length)
11946
12007
  throw new Error('The formData object must have a `files` key.');
12008
+ formData.append('preferredFilename', files[0].name);
11947
12009
  const headers = 'getHeaders' in formData
11948
12010
  ? formData.getHeaders()
11949
12011
  : { 'content-type': 'multipart/form-data' };
@@ -11983,8 +12045,10 @@ const uploadImage = async (formData, onProgress) => {
11983
12045
  const createImage = async (formData, onProgress) => {
11984
12046
  const client = getActiveClient();
11985
12047
  client.log('file/createImage', formData);
11986
- if (!formData.getAll('files').length)
12048
+ const files = formData.getAll('files');
12049
+ if (!files.length)
11987
12050
  throw new Error('The formData object must have a `files` key.');
12051
+ formData.append('preferredFilename', files[0].name);
11988
12052
  const headers = 'getHeaders' in formData
11989
12053
  ? formData.getHeaders()
11990
12054
  : { 'content-type': 'multipart/form-data' };
@@ -12024,8 +12088,10 @@ const createImage = async (formData, onProgress) => {
12024
12088
  const createFile = async (formData, onProgress) => {
12025
12089
  const client = getActiveClient();
12026
12090
  client.log('file/createFile', formData);
12027
- if (!formData.getAll('files').length)
12091
+ const files = formData.getAll('files');
12092
+ if (!files.length)
12028
12093
  throw new Error('The formData object must have a `files` key.');
12094
+ formData.append('preferredFilename', files[0].name);
12029
12095
  const headers = 'getHeaders' in formData
12030
12096
  ? formData.getHeaders()
12031
12097
  : { 'content-type': 'multipart/form-data' };
@@ -12065,8 +12131,10 @@ const createFile = async (formData, onProgress) => {
12065
12131
  const createVideo = async (formData, feedType, onProgress) => {
12066
12132
  const client = getActiveClient();
12067
12133
  client.log('file/createVideo', formData);
12068
- if (!formData.getAll('files').length)
12134
+ const files = formData.getAll('files');
12135
+ if (!files.length)
12069
12136
  throw new Error('The formData object must have a `files` key.');
12137
+ formData.append('preferredFilename', files[0].name);
12070
12138
  if (feedType) {
12071
12139
  formData.append('feedType', feedType);
12072
12140
  }
@@ -13018,7 +13086,10 @@ const createCommentEventSubscriber = (event, callback) => {
13018
13086
  comments[0].parentId,
13019
13087
  ]);
13020
13088
  if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
13021
- 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])] }));
13089
+ // Skip to update parent childComment if current comment already exists
13090
+ if (!parentComment.data.children.includes(comments[0].commentId)) {
13091
+ 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])] }));
13092
+ }
13022
13093
  }
13023
13094
  }
13024
13095
  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; });
@@ -17536,7 +17607,7 @@ const getMembers$1 = (params, callback, config) => {
17536
17607
  *
17537
17608
  * @category Channel Live Collection
17538
17609
  */
17539
- const searchMembers = (params, callback, config) => {
17610
+ const searchMembers$1 = (params, callback, config) => {
17540
17611
  return getMembers$1(params, callback);
17541
17612
  };
17542
17613
  /* end_public_function */
@@ -17547,7 +17618,7 @@ var index$d = /*#__PURE__*/Object.freeze({
17547
17618
  removeMembers: removeMembers$1,
17548
17619
  applyFilter: applyFilter$1,
17549
17620
  getMembers: getMembers$1,
17550
- searchMembers: searchMembers
17621
+ searchMembers: searchMembers$1
17551
17622
  });
17552
17623
 
17553
17624
  /* begin_public_function
@@ -17790,12 +17861,30 @@ var index$b = /*#__PURE__*/Object.freeze({
17790
17861
  prepareChannelPayload: prepareChannelPayload
17791
17862
  });
17792
17863
 
17864
+ const saveCommunityUsers = (communities, communityUsers) => {
17865
+ if (communities.length === 0 || communityUsers.length === 0)
17866
+ return;
17867
+ communities.forEach(({ communityId }) => {
17868
+ const collection = communityUsers.filter(({ communityId: userCommunityId }) => communityId === userCommunityId);
17869
+ pushToCache(['communityUsers', 'collection', communityId], collection);
17870
+ });
17871
+ };
17872
+
17793
17873
  const getMatchPostSetting = (value) => {
17794
17874
  var _a;
17795
17875
  return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
17796
17876
  CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
17797
17877
  value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
17798
17878
  };
17879
+ const convertCommunityUsersToUniqueObject = (communityUsers) => {
17880
+ if (!communityUsers)
17881
+ return communityUsers;
17882
+ const result = {};
17883
+ communityUsers.forEach(user => {
17884
+ result[`${user.userId}#${user.communityId}`] = user;
17885
+ });
17886
+ return result;
17887
+ };
17799
17888
  const prepareCommunityPayload = (rawPayload) => {
17800
17889
  // Unpack community payload by mapping payload field to postSetting value.
17801
17890
  const communities = rawPayload.communities.map((_a) => {
@@ -17805,7 +17894,18 @@ const prepareCommunityPayload = (rawPayload) => {
17805
17894
  onlyAdminCanPost,
17806
17895
  }) }, restCommunityPayload));
17807
17896
  });
17808
- const communityUsers = withUsers(rawPayload.communityUsers);
17897
+ const mergeCommunityUsers = communities.reduce((acc, { communityId }) => {
17898
+ var _a;
17899
+ const users = (_a = pullFromCache([
17900
+ 'communityUsers',
17901
+ 'collection',
17902
+ communityId,
17903
+ ])) === null || _a === void 0 ? void 0 : _a.data;
17904
+ if (!users)
17905
+ return acc;
17906
+ return Object.assign(Object.assign({}, convertCommunityUsersToUniqueObject(users)), acc);
17907
+ }, convertCommunityUsersToUniqueObject(rawPayload.communityUsers));
17908
+ const communityUsers = withUsers(Object.values(mergeCommunityUsers));
17809
17909
  const communityWithMembershipStatus = updateMembershipStatus(communities, communityUsers);
17810
17910
  return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers });
17811
17911
  };
@@ -17839,8 +17939,10 @@ const getCommunities$1 = async (communityIds) => {
17839
17939
  });
17840
17940
  const data = prepareCommunityPayload(payload);
17841
17941
  const cachedAt = client.cache && Date.now();
17842
- if (client.cache)
17942
+ if (client.cache) {
17843
17943
  ingestInCache(data, { cachedAt });
17944
+ saveCommunityUsers(data.communities, data.communityUsers);
17945
+ }
17844
17946
  return {
17845
17947
  data: data.communities,
17846
17948
  cachedAt,
@@ -17902,8 +18004,10 @@ const createCommunity = async (bundle) => {
17902
18004
  fireEvent('community.created', payload);
17903
18005
  const data = prepareCommunityPayload(payload);
17904
18006
  const cachedAt = client.cache && Date.now();
17905
- if (client.cache)
18007
+ if (client.cache) {
17906
18008
  ingestInCache(data, { cachedAt });
18009
+ saveCommunityUsers(data.communities, data.communityUsers);
18010
+ }
17907
18011
  const { communities } = data;
17908
18012
  return {
17909
18013
  data: communities[0],
@@ -17937,8 +18041,10 @@ const updateCommunity = async (communityId, patch) => {
17937
18041
  fireEvent('community.updated', payload);
17938
18042
  const data = prepareCommunityPayload(payload);
17939
18043
  const cachedAt = client.cache && Date.now();
17940
- if (client.cache)
18044
+ if (client.cache) {
17941
18045
  ingestInCache(data, { cachedAt });
18046
+ saveCommunityUsers(data.communities, data.communityUsers);
18047
+ }
17942
18048
  const { communities } = data;
17943
18049
  return {
17944
18050
  data: communities.find(community => community.communityId === communityId),
@@ -17968,8 +18074,10 @@ const getCommunity$1 = async (communityId) => {
17968
18074
  const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
17969
18075
  const data = prepareCommunityPayload(payload);
17970
18076
  const cachedAt = client.cache && Date.now();
17971
- if (client.cache)
18077
+ if (client.cache) {
17972
18078
  ingestInCache(data, { cachedAt });
18079
+ saveCommunityUsers(data.communities, data.communityUsers);
18080
+ }
17973
18081
  const { communities } = data;
17974
18082
  return {
17975
18083
  data: communities.find(community => community.communityId === communityId),
@@ -18512,7 +18620,7 @@ const observeCommunity = (communityId, callback) => {
18512
18620
  * TODO: handle cache receive cache option, and cache policy
18513
18621
  * TODO: check if querybyIds is supported
18514
18622
  */
18515
- class CommunitiesPaginationController extends PaginationController {
18623
+ class CommunitiesPaginationController$1 extends PaginationController {
18516
18624
  async getRequest(queryParams, token) {
18517
18625
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18518
18626
  const options = token ? { token } : { limit };
@@ -18523,7 +18631,7 @@ class CommunitiesPaginationController extends PaginationController {
18523
18631
  }
18524
18632
  }
18525
18633
 
18526
- class CommunitiesQueryStreamController extends QueryStreamController {
18634
+ class CommunitiesQueryStreamController$1 extends QueryStreamController {
18527
18635
  constructor(query, cacheKey, notifyChange, preparePayload) {
18528
18636
  super(query, cacheKey);
18529
18637
  this.notifyChange = notifyChange;
@@ -18565,22 +18673,173 @@ class CommunitiesQueryStreamController extends QueryStreamController {
18565
18673
  }
18566
18674
  }
18567
18675
 
18568
- var EnumCommunityActions;
18676
+ var EnumCommunityActions$1;
18569
18677
  (function (EnumCommunityActions) {
18570
18678
  EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
18571
18679
  EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
18572
18680
  EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
18573
- })(EnumCommunityActions || (EnumCommunityActions = {}));
18681
+ })(EnumCommunityActions$1 || (EnumCommunityActions$1 = {}));
18682
+
18683
+ var EnumCommunityMemberActions$1;
18684
+ (function (EnumCommunityMemberActions) {
18685
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
18686
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
18687
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
18688
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
18689
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
18690
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
18691
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
18692
+ EnumCommunityMemberActions["OnMemberCountChanged"] = "OnMemberCountChanged";
18693
+ })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
18574
18694
 
18575
- /* eslint-disable no-use-before-define */
18576
- class SearchCommunityLiveCollectionController extends LiveCollectionController {
18695
+ /* begin_public_function
18696
+ id: community.membership.add_members
18697
+ */
18698
+ /**
18699
+ * ```js
18700
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
18701
+ * const updated = await CommunityRepository.moderation.addMembers(communityId, ['foo', 'bar'])
18702
+ * ```
18703
+ *
18704
+ * Adds a list of {@link Amity.InternalUser} to a {@link Amity.Community} to add users to
18705
+ *
18706
+ * @param communityId The ID of the {@link Amity.Community} to perform
18707
+ * @param userIds The list of IDs {@link Amity.InternalUser} to add
18708
+ * @returns A success boolean if the {@link Amity.InternalUser} were added to the {@link Amity.Community}
18709
+ *
18710
+ * @category Community API
18711
+ * @async
18712
+ */
18713
+ const addMembers = async (communityId, userIds) => {
18714
+ const client = getActiveClient();
18715
+ client.log('community/moderation/addMembers', communityId, userIds);
18716
+ const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
18717
+ fireEvent('community.userAdded', payload);
18718
+ const data = prepareMembershipPayload(payload, 'communityUsers');
18719
+ if (client.cache)
18720
+ ingestInCache(data);
18721
+ const { communityUsers } = data;
18722
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership === 'member');
18723
+ };
18724
+ /* end_public_function */
18725
+
18726
+ /* begin_public_function
18727
+ id: community.membership.remove_member
18728
+ */
18729
+ /**
18730
+ * ```js
18731
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
18732
+ * const updated = await CommunityRepository.moderation.removeMembers(communityId, ['foo', 'bar'])
18733
+ * ```
18734
+ *
18735
+ * Removes a list of {@link Amity.InternalUser} from a {@link Amity.Community}
18736
+ *
18737
+ * @param communityId The ID of the {@link Amity.Community} to edit
18738
+ * @param userIds The list of IDs {@link Amity.InternalUser} to remove
18739
+ * @returns A success boolean if the list of {@link Amity.InternalUser} were removed from the {@link Amity.Community}
18740
+ *
18741
+ * @category Community API
18742
+ * @async
18743
+ */
18744
+ const removeMembers = async (communityId, userIds) => {
18745
+ const client = getActiveClient();
18746
+ client.log('community/moderation/removeMembers', communityId, userIds);
18747
+ const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
18748
+ fireEvent('community.userRemoved', payload);
18749
+ const data = prepareMembershipPayload(payload, 'communityUsers');
18750
+ if (client.cache)
18751
+ ingestInCache(data);
18752
+ const { communityUsers } = data;
18753
+ return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
18754
+ };
18755
+ /* end_public_function */
18756
+
18757
+ /**
18758
+ * TODO: handle cache receive cache option, and cache policy
18759
+ * TODO: check if querybyIds is supported
18760
+ */
18761
+ class CommunityMembersPaginationController extends PaginationController {
18762
+ async getRequest(queryParams, token) {
18763
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18764
+ const options = token ? { token } : { limit };
18765
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
18766
+ params: Object.assign(Object.assign({}, params), { options }),
18767
+ });
18768
+ return queryResponse;
18769
+ }
18770
+ }
18771
+
18772
+ class CommunityMembersQueryStreamController extends QueryStreamController {
18773
+ constructor(query, cacheKey, notifyChange, preparePayload) {
18774
+ super(query, cacheKey);
18775
+ this.notifyChange = notifyChange;
18776
+ this.preparePayload = preparePayload;
18777
+ }
18778
+ async saveToMainDB(response) {
18779
+ const processedPayload = await this.preparePayload(response);
18780
+ const client = getActiveClient();
18781
+ const cachedAt = client.cache && Date.now();
18782
+ if (client.cache) {
18783
+ ingestInCache(processedPayload, { cachedAt });
18784
+ }
18785
+ }
18786
+ appendToQueryStream(response, direction, refresh = false) {
18787
+ var _a, _b;
18788
+ if (refresh) {
18789
+ pushToCache(this.cacheKey, {
18790
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
18791
+ });
18792
+ }
18793
+ else {
18794
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18795
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18796
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
18797
+ ...new Set([
18798
+ ...communityUsers,
18799
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
18800
+ ]),
18801
+ ] }));
18802
+ }
18803
+ }
18804
+ reactor(action) {
18805
+ return (community, communityMembers) => {
18806
+ var _a;
18807
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18808
+ if (!collection)
18809
+ return;
18810
+ if (action === EnumCommunityMemberActions$1.OnCommunityUserRoleAdded &&
18811
+ this.query.sortBy === 'displayName') {
18812
+ return;
18813
+ }
18814
+ communityMembers.forEach(communityMember => {
18815
+ const communityMemberCacheId = getResolver('communityUsers')({
18816
+ communityId: this.query.communityId,
18817
+ userId: communityMember.userId,
18818
+ });
18819
+ if (communityMember.communityMembership === 'none') {
18820
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
18821
+ }
18822
+ else if (!collection.data.includes(communityMemberCacheId)) {
18823
+ collection.data = [communityMemberCacheId, ...collection.data];
18824
+ }
18825
+ });
18826
+ pushToCache(this.cacheKey, collection);
18827
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
18828
+ };
18829
+ }
18830
+ subscribeRTE(createSubscriber) {
18831
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
18832
+ }
18833
+ }
18834
+
18835
+ class CommunityMembersLiveCollectionController extends LiveCollectionController {
18577
18836
  constructor(query, callback) {
18578
18837
  const queryStreamId = hash__default["default"](query);
18579
- const cacheKey = ['community', 'collection', queryStreamId];
18580
- const paginationController = new CommunitiesPaginationController(query);
18838
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
18839
+ const paginationController = new CommunityMembersPaginationController(query);
18581
18840
  super(paginationController, queryStreamId, cacheKey, callback);
18582
18841
  this.query = query;
18583
- this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
18842
+ this.queryStreamController = new CommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
18584
18843
  this.callback = callback.bind(this);
18585
18844
  this.loadPage({ initial: true });
18586
18845
  }
@@ -18602,8 +18861,16 @@ class SearchCommunityLiveCollectionController extends LiveCollectionController {
18602
18861
  }
18603
18862
  startSubscription() {
18604
18863
  return this.queryStreamController.subscribeRTE([
18605
- { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
18606
- { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
18864
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
18865
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
18866
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions$1.OnCommunityUserBanned },
18867
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnCommunityUserChanged },
18868
+ { fn: onCommunityUserRoleAdded, action: EnumCommunityMemberActions$1.OnCommunityUserRoleAdded },
18869
+ {
18870
+ fn: onCommunityUserRoleRemoved,
18871
+ action: EnumCommunityMemberActions$1.OnCommunityUserRoleRemoved,
18872
+ },
18873
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions$1.OnCommunityUserUnbanned },
18607
18874
  ]);
18608
18875
  }
18609
18876
  notifyChange({ origin, loading, error }) {
@@ -18612,8 +18879,8 @@ class SearchCommunityLiveCollectionController extends LiveCollectionController {
18612
18879
  if (!collection)
18613
18880
  return;
18614
18881
  const data = this.applyFilter((_b = collection.data
18615
- .map(id => pullFromCache(['community', 'get', id]))
18616
- .filter(Boolean)
18882
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
18883
+ .filter(isNonNullable)
18617
18884
  .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
18618
18885
  if (!this.shouldNotify(data) && origin === 'event')
18619
18886
  return;
@@ -18626,108 +18893,392 @@ class SearchCommunityLiveCollectionController extends LiveCollectionController {
18626
18893
  });
18627
18894
  }
18628
18895
  applyFilter(data) {
18629
- const { userId } = getActiveClient();
18630
- let communities = data;
18631
- if (this.query.includeDeleted) {
18632
- communities = filterByPropEquality(communities, 'isDeleted', false);
18633
- }
18634
- if (this.query.categoryId) {
18635
- communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
18896
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
18897
+ if (this.query.memberships) {
18898
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
18899
+ const memberships = this.query.memberships || [];
18900
+ return memberships.includes(communityMembership);
18901
+ });
18636
18902
  }
18637
- if (this.query.tags) {
18638
- 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); }); });
18903
+ if (this.query.search) {
18904
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
18639
18905
  }
18640
- if (this.query.membership && userId) {
18641
- communities = filterByCommunityMembership(communities, this.query.membership, userId);
18906
+ switch (this.query.sortBy) {
18907
+ case 'firstCreated':
18908
+ communityMembers = communityMembers.sort(sortByFirstCreated);
18909
+ break;
18910
+ case 'displayName':
18911
+ communityMembers = communityMembers.sort((a, b) => {
18912
+ var _a, _b, _c, _d;
18913
+ 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)) {
18914
+ 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);
18915
+ }
18916
+ return 0;
18917
+ });
18918
+ break;
18919
+ case 'lastCreated':
18920
+ default:
18921
+ communityMembers = communityMembers.sort(sortByLastCreated);
18922
+ break;
18642
18923
  }
18643
- return communities;
18924
+ return communityMembers;
18644
18925
  }
18645
18926
  }
18646
18927
 
18928
+ /*
18929
+ * Exported for testing
18930
+ * @hidden
18931
+ */
18932
+ const applyFilter = (data, params) => {
18933
+ let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
18934
+ if (params.memberships) {
18935
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
18936
+ const membership = params.memberships;
18937
+ return membership.includes(communityMembership);
18938
+ });
18939
+ }
18940
+ if (params.search) {
18941
+ communityMembers = filterBySearchTerm(communityMembers, params.search);
18942
+ }
18943
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
18944
+ communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
18945
+ return communityMembers;
18946
+ };
18647
18947
  /* begin_public_function
18648
- id: community.query
18948
+ id: community.membership.query
18649
18949
  */
18650
18950
  /**
18651
18951
  * ```js
18652
- * import { CommunityRepository } from '@amityco/ts-sdk'
18952
+ * import { getMembers } from '@amityco/ts-sdk-react-native'
18653
18953
  *
18654
- * let communities = []
18655
- * const unsub = CommunityRepository.searchCommunities({
18656
- * displayName: Amity.Community['displayName'],
18657
- * }, response => merge(communities, response.data))
18954
+ * let communityMembers = []
18955
+ * const unsub = getMembers({
18956
+ * communityId: Amity.Community['communityId'],
18957
+ * }, response => merge(communityMembers, response.data))
18658
18958
  * ```
18659
18959
  *
18660
- * Observe all mutations on a list of {@link Amity.Community}s
18960
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
18661
18961
  *
18662
- * @param params for querying communities
18962
+ * @param params for querying community users
18663
18963
  * @param callback the function to call when new data are available
18664
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
18964
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
18665
18965
  *
18666
18966
  * @category Community Live Collection
18667
18967
  */
18668
- const searchCommunities = (params, callback, config) => {
18968
+ const getMembers = (params, callback, config) => {
18669
18969
  const { log, cache } = getActiveClient();
18670
18970
  if (!cache) {
18671
18971
  console.log(ENABLE_CACHE_MESSAGE);
18672
18972
  }
18673
18973
  const timestamp = Date.now();
18674
- log(`searchCommunities(tmpid: ${timestamp}) > listen`);
18675
- const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
18676
- const disposers = searchCommunitiesLiveCollection.startSubscription();
18677
- const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
18678
- disposers.push(() => dropFromCache(cacheKey));
18974
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
18975
+ const communityMemberLiveCollection = new CommunityMembersLiveCollectionController(params, resp => {
18976
+ console.log('resp', resp);
18977
+ callback(resp);
18978
+ });
18979
+ const disposers = communityMemberLiveCollection.startSubscription();
18980
+ const cacheKey = communityMemberLiveCollection.getCacheKey();
18981
+ disposers.push(() => {
18982
+ dropFromCache(cacheKey);
18983
+ });
18679
18984
  return () => {
18680
- log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
18985
+ log(`getMembers(tmpid: ${timestamp}) > dispose`);
18681
18986
  disposers.forEach(fn => fn());
18682
18987
  };
18683
18988
  };
18684
18989
  /* end_public_function */
18685
18990
 
18991
+ /**
18992
+ * TODO: handle cache receive cache option, and cache policy
18993
+ * TODO: check if querybyIds is supported
18994
+ */
18995
+ class SearchCommunityMembersPaginationController extends PaginationController {
18996
+ async getRequest(queryParams, token) {
18997
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18998
+ const options = token ? { token } : { limit };
18999
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
19000
+ params: Object.assign(Object.assign({}, params), { options }),
19001
+ });
19002
+ return queryResponse;
19003
+ }
19004
+ }
19005
+
19006
+ class SearchCommunityMembersQueryStreamController extends QueryStreamController {
19007
+ constructor(query, cacheKey, notifyChange, preparePayload) {
19008
+ super(query, cacheKey);
19009
+ this.notifyChange = notifyChange;
19010
+ this.preparePayload = preparePayload;
19011
+ }
19012
+ async saveToMainDB(response) {
19013
+ const processedPayload = await this.preparePayload(response);
19014
+ const client = getActiveClient();
19015
+ const cachedAt = client.cache && Date.now();
19016
+ if (client.cache) {
19017
+ ingestInCache(processedPayload, { cachedAt });
19018
+ }
19019
+ }
19020
+ appendToQueryStream(response, direction, refresh = false) {
19021
+ var _a, _b;
19022
+ if (refresh) {
19023
+ pushToCache(this.cacheKey, {
19024
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19025
+ });
19026
+ }
19027
+ else {
19028
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19029
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19030
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
19031
+ ...new Set([
19032
+ ...communityUsers,
19033
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19034
+ ]),
19035
+ ] }));
19036
+ }
19037
+ }
19038
+ reactor(action) {
19039
+ return (community, communityMembers) => {
19040
+ var _a;
19041
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19042
+ if (!collection)
19043
+ return;
19044
+ communityMembers.forEach(communityMember => {
19045
+ const communityMemberCacheId = getResolver('communityUsers')({
19046
+ communityId: this.query.communityId,
19047
+ userId: communityMember.userId,
19048
+ });
19049
+ if (communityMember.communityMembership === 'none') {
19050
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
19051
+ }
19052
+ });
19053
+ pushToCache(this.cacheKey, collection);
19054
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
19055
+ };
19056
+ }
19057
+ subscribeRTE(createSubscriber) {
19058
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
19059
+ }
19060
+ }
19061
+
19062
+ var EnumCommunityMemberActions;
19063
+ (function (EnumCommunityMemberActions) {
19064
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
19065
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
19066
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
19067
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
19068
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
19069
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
19070
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
19071
+ })(EnumCommunityMemberActions || (EnumCommunityMemberActions = {}));
19072
+
19073
+ /* eslint-disable no-use-before-define */
19074
+ class SearchCommunityMembersLiveCollectionController extends LiveCollectionController {
19075
+ constructor(query, callback) {
19076
+ const queryStreamId = hash__default["default"](query);
19077
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
19078
+ const paginationController = new SearchCommunityMembersPaginationController(query);
19079
+ super(paginationController, queryStreamId, cacheKey, callback);
19080
+ this.query = query;
19081
+ this.queryStreamController = new SearchCommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
19082
+ this.callback = callback.bind(this);
19083
+ this.loadPage({ initial: true });
19084
+ }
19085
+ setup() {
19086
+ var _a;
19087
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19088
+ if (!collection) {
19089
+ pushToCache(this.cacheKey, {
19090
+ data: [],
19091
+ params: {},
19092
+ });
19093
+ }
19094
+ }
19095
+ async persistModel(queryPayload) {
19096
+ await this.queryStreamController.saveToMainDB(queryPayload);
19097
+ }
19098
+ persistQueryStream({ response, direction, refresh, }) {
19099
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
19100
+ }
19101
+ startSubscription() {
19102
+ return this.queryStreamController.subscribeRTE([
19103
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions.OnCommunityJoined },
19104
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
19105
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
19106
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
19107
+ {
19108
+ fn: onCommunityUserRoleRemoved,
19109
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
19110
+ },
19111
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
19112
+ ]);
19113
+ }
19114
+ notifyChange({ origin, loading, error }) {
19115
+ var _a, _b;
19116
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19117
+ if (!collection)
19118
+ return;
19119
+ const data = this.applyFilter((_b = collection.data
19120
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
19121
+ .filter(isNonNullable)
19122
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
19123
+ if (!this.shouldNotify(data) && origin === 'event')
19124
+ return;
19125
+ this.callback({
19126
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
19127
+ data,
19128
+ hasNextPage: !!this.paginationController.getNextToken(),
19129
+ loading,
19130
+ error,
19131
+ });
19132
+ }
19133
+ applyFilter(data) {
19134
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
19135
+ if (this.query.memberships) {
19136
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
19137
+ const memberships = this.query.memberships || [];
19138
+ return memberships.includes(communityMembership);
19139
+ });
19140
+ }
19141
+ if (this.query.search) {
19142
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
19143
+ }
19144
+ return communityMembers;
19145
+ }
19146
+ }
19147
+
19148
+ /* begin_public_function
19149
+ id: community.membership.query
19150
+ */
18686
19151
  /**
18687
19152
  * ```js
18688
- * import { queryCommunities } from '@amityco/ts-sdk-react-native'
18689
- * const communities = await queryCommunities()
19153
+ * import { searchMembers } from '@amityco/ts-sdk-react-native'
19154
+ *
19155
+ * let communityMembers = []
19156
+ * const unsub = searchMembers({
19157
+ * communityId: Amity.Community['communityId'],
19158
+ * }, response => merge(communityMembers, response.data))
18690
19159
  * ```
18691
19160
  *
18692
- * Queries a paginable list of {@link Amity.Community} objects
18693
- * Search is performed by displayName such as `.startsWith(search)`
19161
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
18694
19162
  *
18695
- * @param query The query parameters
18696
- * @returns A page of {@link Amity.Community} objects
19163
+ * @param params for querying community users
19164
+ * @param callback the function to call when new data are available
19165
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
18697
19166
  *
18698
- * @category Community API
18699
- * @async
19167
+ * @category Community Live Collection
18700
19168
  */
18701
- const queryCommunities = async (query) => {
18702
- const client = getActiveClient();
18703
- client.log('channel/queryCommunities', query);
18704
- // safe decapsulation
18705
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit = 10 } = _a, params = __rest(_a, ["page", "limit"]);
18706
- const _b = params !== null && params !== void 0 ? params : {}, { displayName, membership, includeDeleted } = _b, restParams = __rest(_b, ["displayName", "membership", "includeDeleted"]);
18707
- const options = (() => {
18708
- if (page)
18709
- return { token: page };
18710
- if (limit)
18711
- return { limit };
18712
- return undefined;
18713
- })();
18714
- // API-FIX: parameters should be querystring.
18715
- // API-FIX: backend doesn't answer Amity.Response
18716
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
18717
- const { data } = await client.http.get(`/api/v3/communities`, {
18718
- params: Object.assign(Object.assign({}, restParams), { isDeleted: inferIsDeleted(includeDeleted), keyword: displayName, filter: membership, options }),
19169
+ const searchMembers = (params, callback, config) => {
19170
+ const { log, cache } = getActiveClient();
19171
+ if (!cache) {
19172
+ console.log(ENABLE_CACHE_MESSAGE);
19173
+ }
19174
+ const timestamp = Date.now();
19175
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
19176
+ const searchCommunityMemberLiveCollection = new SearchCommunityMembersLiveCollectionController(params, resp => {
19177
+ callback(resp);
18719
19178
  });
18720
- const { paging } = data, payload = __rest(data, ["paging"]);
18721
- const unpackedPayload = prepareCommunityPayload(payload);
18722
- const { communities } = unpackedPayload;
18723
- const cachedAt = client.cache && Date.now();
18724
- if (client.cache) {
18725
- ingestInCache(unpackedPayload, { cachedAt });
18726
- const cacheKey = ['community', 'query', Object.assign(Object.assign({}, params), { options })];
18727
- pushToCache(cacheKey, { communities: communities.map(getResolver('community')), paging });
19179
+ const disposers = searchCommunityMemberLiveCollection.startSubscription();
19180
+ const cacheKey = searchCommunityMemberLiveCollection.getCacheKey();
19181
+ disposers.push(() => {
19182
+ dropFromCache(cacheKey);
19183
+ });
19184
+ return () => {
19185
+ log(`getMembers(tmpid: ${timestamp}) > dispose`);
19186
+ disposers.forEach(fn => fn());
19187
+ };
19188
+ };
19189
+ /* end_public_function */
19190
+
19191
+ var index$a = /*#__PURE__*/Object.freeze({
19192
+ __proto__: null,
19193
+ addMembers: addMembers,
19194
+ removeMembers: removeMembers,
19195
+ applyFilter: applyFilter,
19196
+ getMembers: getMembers,
19197
+ searchMembers: searchMembers,
19198
+ onCommunityUserAdded: onCommunityUserAdded,
19199
+ onCommunityUserRemoved: onCommunityUserRemoved,
19200
+ onCommunityUserBanned: onCommunityUserBanned,
19201
+ onCommunityUserChanged: onCommunityUserChanged,
19202
+ onCommunityUserUnbanned: onCommunityUserUnbanned,
19203
+ onCommunityUserRoleAdded: onCommunityUserRoleAdded,
19204
+ onCommunityUserRoleRemoved: onCommunityUserRoleRemoved,
19205
+ onCommunityJoined: onCommunityJoined,
19206
+ onCommunityLeft: onCommunityLeft
19207
+ });
19208
+
19209
+ class SearchCommunityLiveCollectionController extends LiveCollectionController {
19210
+ constructor(query, callback) {
19211
+ const queryStreamId = hash__default["default"](query);
19212
+ const cacheKey = ['community', 'collection', queryStreamId];
19213
+ const paginationController = new CommunitiesPaginationController$1(query);
19214
+ super(paginationController, queryStreamId, cacheKey, callback);
19215
+ this.query = query;
19216
+ this.queryStreamController = new CommunitiesQueryStreamController$1(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
19217
+ this.callback = callback.bind(this);
19218
+ this.loadPage({ initial: true });
18728
19219
  }
18729
- return { data: communities, cachedAt, paging };
18730
- };
19220
+ setup() {
19221
+ var _a;
19222
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19223
+ if (!collection) {
19224
+ pushToCache(this.cacheKey, {
19225
+ data: [],
19226
+ params: {},
19227
+ });
19228
+ }
19229
+ }
19230
+ async persistModel(queryPayload) {
19231
+ await this.queryStreamController.saveToMainDB(queryPayload);
19232
+ }
19233
+ persistQueryStream({ response, direction, refresh, }) {
19234
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
19235
+ }
19236
+ startSubscription() {
19237
+ return this.queryStreamController.subscribeRTE([
19238
+ { fn: onCommunityDeleted, action: EnumCommunityActions$1.OnCommunityDeleted },
19239
+ { fn: onCommunityUpdated, action: EnumCommunityActions$1.OnCommunityUpdated },
19240
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
19241
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
19242
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnMemberCountChanged },
19243
+ ]);
19244
+ }
19245
+ notifyChange({ origin, loading, error }) {
19246
+ var _a, _b;
19247
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19248
+ if (!collection)
19249
+ return;
19250
+ const data = this.applyFilter((_b = collection.data
19251
+ .map(id => pullFromCache(['community', 'get', id]))
19252
+ .filter(Boolean)
19253
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
19254
+ if (!this.shouldNotify(data) && origin === 'event')
19255
+ return;
19256
+ this.callback({
19257
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
19258
+ data,
19259
+ hasNextPage: !!this.paginationController.getNextToken(),
19260
+ loading,
19261
+ error,
19262
+ });
19263
+ }
19264
+ applyFilter(data) {
19265
+ const { userId } = getActiveClient();
19266
+ let communities = data;
19267
+ if (this.query.includeDeleted) {
19268
+ communities = filterByPropEquality(communities, 'isDeleted', false);
19269
+ }
19270
+ if (this.query.categoryId) {
19271
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
19272
+ }
19273
+ if (this.query.tags) {
19274
+ 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); }); });
19275
+ }
19276
+ if (this.query.membership && userId) {
19277
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
19278
+ }
19279
+ return communities;
19280
+ }
19281
+ }
18731
19282
 
18732
19283
  /* begin_public_function
18733
19284
  id: community.query
@@ -18737,7 +19288,7 @@ const queryCommunities = async (query) => {
18737
19288
  * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
18738
19289
  *
18739
19290
  * let communities = []
18740
- * const unsub = CommunityRepository.getCommunities({
19291
+ * const unsub = CommunityRepository.searchCommunities({
18741
19292
  * displayName: Amity.Community['displayName'],
18742
19293
  * }, response => merge(communities, response.data))
18743
19294
  * ```
@@ -18750,99 +19301,217 @@ const queryCommunities = async (query) => {
18750
19301
  *
18751
19302
  * @category Community Live Collection
18752
19303
  */
18753
- const getCommunities = (params, callback, config) => {
18754
- const { log, cache, userId } = getActiveClient();
19304
+ const searchCommunities = (params, callback, config) => {
19305
+ const { log, cache } = getActiveClient();
18755
19306
  if (!cache) {
18756
19307
  console.log(ENABLE_CACHE_MESSAGE);
18757
19308
  }
18758
19309
  const timestamp = Date.now();
18759
- log(`getCommunities(tmpid: ${timestamp}) > listen`);
18760
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
18761
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
18762
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
18763
- const disposers = [];
18764
- const cacheKey = ['community', 'collection', queryParams];
18765
- const responder = (data) => {
19310
+ log(`searchCommunities(tmpid: ${timestamp}) > listen`);
19311
+ const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
19312
+ const disposers = searchCommunitiesLiveCollection.startSubscription();
19313
+ const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
19314
+ disposers.push(() => dropFromCache(cacheKey));
19315
+ return () => {
19316
+ log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
19317
+ disposers.forEach(fn => fn());
19318
+ };
19319
+ };
19320
+ /* end_public_function */
19321
+
19322
+ /**
19323
+ * TODO: handle cache receive cache option, and cache policy
19324
+ * TODO: check if querybyIds is supported
19325
+ */
19326
+ class CommunitiesPaginationController extends PaginationController {
19327
+ async getRequest(queryParams, token) {
19328
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
19329
+ const options = token ? { token } : { limit };
19330
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
19331
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
19332
+ });
19333
+ return queryResponse;
19334
+ }
19335
+ }
19336
+
19337
+ var EnumCommunityActions;
19338
+ (function (EnumCommunityActions) {
19339
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
19340
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
19341
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
19342
+ })(EnumCommunityActions || (EnumCommunityActions = {}));
19343
+
19344
+ class CommunitiesQueryStreamController extends QueryStreamController {
19345
+ constructor(query, cacheKey, notifyChange, preparePayload) {
19346
+ super(query, cacheKey);
19347
+ this.notifyChange = notifyChange;
19348
+ this.preparePayload = preparePayload;
19349
+ }
19350
+ async saveToMainDB(response) {
19351
+ const processedPayload = await this.preparePayload(response);
19352
+ const client = getActiveClient();
19353
+ const cachedAt = client.cache && Date.now();
19354
+ if (client.cache) {
19355
+ ingestInCache(processedPayload, { cachedAt });
19356
+ saveCommunityUsers(response.communities, response.communityUsers);
19357
+ }
19358
+ }
19359
+ appendToQueryStream(response, direction, refresh = false) {
18766
19360
  var _a, _b;
18767
- let communities = (_a = data.data
18768
- .map(communityId => pullFromCache(['community', 'get', communityId]))
19361
+ if (refresh) {
19362
+ pushToCache(this.cacheKey, {
19363
+ data: response.communities.map(getResolver('community')),
19364
+ });
19365
+ }
19366
+ else {
19367
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19368
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19369
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
19370
+ }
19371
+ }
19372
+ reactor(action) {
19373
+ return (community) => {
19374
+ var _a;
19375
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19376
+ if (!collection)
19377
+ return;
19378
+ if (this.query.displayName && action === EnumCommunityActions.OnCommunityCreated) {
19379
+ return;
19380
+ }
19381
+ /*
19382
+ * Simply update a collection and let responder decide what to do with data
19383
+ */
19384
+ collection.data = [...new Set([community.communityId, ...collection.data])];
19385
+ pushToCache(this.cacheKey, collection);
19386
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
19387
+ };
19388
+ }
19389
+ subscribeRTE(createSubscriber) {
19390
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
19391
+ }
19392
+ }
19393
+
19394
+ class CommunityLiveCollectionController extends LiveCollectionController {
19395
+ constructor(query, callback) {
19396
+ const queryStreamId = hash__default["default"](query);
19397
+ const cacheKey = ['community', 'collection', queryStreamId];
19398
+ const paginationController = new CommunitiesPaginationController(query);
19399
+ super(paginationController, queryStreamId, cacheKey, callback);
19400
+ this.query = query;
19401
+ this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
19402
+ this.callback = callback.bind(this);
19403
+ this.loadPage({ initial: true });
19404
+ }
19405
+ setup() {
19406
+ var _a;
19407
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19408
+ if (!collection) {
19409
+ pushToCache(this.cacheKey, {
19410
+ data: [],
19411
+ params: {},
19412
+ });
19413
+ }
19414
+ }
19415
+ async persistModel(queryPayload) {
19416
+ await this.queryStreamController.saveToMainDB(queryPayload);
19417
+ }
19418
+ persistQueryStream({ response, direction, refresh, }) {
19419
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
19420
+ }
19421
+ startSubscription() {
19422
+ return this.queryStreamController.subscribeRTE([
19423
+ { fn: onCommunityCreated, action: EnumCommunityActions.OnCommunityCreated },
19424
+ { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
19425
+ { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
19426
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
19427
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
19428
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnMemberCountChanged },
19429
+ ]);
19430
+ }
19431
+ notifyChange({ origin, loading, error }) {
19432
+ var _a, _b;
19433
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19434
+ if (!collection)
19435
+ return;
19436
+ const data = this.applyFilter((_b = collection.data
19437
+ .map(id => pullFromCache(['community', 'get', id]))
18769
19438
  .filter(Boolean)
18770
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
18771
- communities = filterByStringComparePartially(communities, 'displayName', params.displayName);
18772
- if (!params.includeDeleted) {
19439
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
19440
+ if (!this.shouldNotify(data) && origin === 'event')
19441
+ return;
19442
+ this.callback({
19443
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
19444
+ data,
19445
+ hasNextPage: !!this.paginationController.getNextToken(),
19446
+ loading,
19447
+ error,
19448
+ });
19449
+ }
19450
+ applyFilter(data) {
19451
+ const { userId } = getActiveClient();
19452
+ let communities = data;
19453
+ if (this.query.includeDeleted) {
18773
19454
  communities = filterByPropEquality(communities, 'isDeleted', false);
18774
19455
  }
18775
- if (params.categoryId) {
18776
- communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(params.categoryId); });
18777
- }
18778
- if (params.tags) {
18779
- 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); }); });
19456
+ if (this.query.categoryId) {
19457
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
18780
19458
  }
18781
- if (params.membership && userId) {
18782
- communities = filterByCommunityMembership(communities, params.membership, userId);
19459
+ if (this.query.tags) {
19460
+ 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); }); });
18783
19461
  }
18784
- const sortBy = params.sortBy || 'lastCreated';
18785
- if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
18786
- communities = communities.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
19462
+ if (this.query.membership && userId) {
19463
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
18787
19464
  }
18788
- /*
18789
- * The server returns communities with empty | null displayName's first before
18790
- * returning sorted list of communities with displayNames
18791
- *
18792
- * This section needs to be updated as displayNames can be null as well
18793
- */
18794
- if (sortBy === 'displayName') {
18795
- communities = communities
18796
- // this needs to be aligned with the backend data type
18797
- .map(c => (c.displayName ? c : Object.assign(Object.assign({}, c), { displayName: '' })))
18798
- // @ts-ignore
18799
- .sort(sortByDisplayName);
19465
+ if (!this.query.displayName) {
19466
+ const sortFn = (() => {
19467
+ switch (this.query.sortBy) {
19468
+ case 'firstCreated':
19469
+ return sortByFirstCreated;
19470
+ case 'lastCreated':
19471
+ return sortByLastCreated;
19472
+ case 'displayName':
19473
+ return sortByDisplayName;
19474
+ default:
19475
+ return sortByLastCreated;
19476
+ }
19477
+ })();
19478
+ communities = communities.sort(sortFn);
18800
19479
  }
18801
- callback({
18802
- onNextPage: onFetch,
18803
- data: communities,
18804
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
18805
- loading: data.loading,
18806
- error: data.error,
18807
- });
18808
- };
18809
- const realtimeRouter = (_) => (community) => {
18810
- var _a;
18811
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18812
- if (!collection)
18813
- return;
18814
- /*
18815
- * Simply update collection and let responder decide what to do with data
18816
- */
18817
- collection.data = [...new Set([community.communityId, ...collection.data])];
18818
- pushToCache(cacheKey, collection);
18819
- responder(collection);
18820
- };
18821
- const onFetch = (initial = false) => {
18822
- var _a, _b;
18823
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18824
- const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18825
- if (!initial && communities.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
18826
- return;
18827
- 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 }));
18828
- runQuery(query, ({ data: result, error, loading, paging }) => {
18829
- const data = {
18830
- loading,
18831
- error,
18832
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
18833
- data: communities,
18834
- };
18835
- if (result) {
18836
- data.data = initial
18837
- ? result.map(getResolver('community'))
18838
- : [...new Set([...communities, ...result.map(getResolver('community'))])];
18839
- }
18840
- pushToCache(cacheKey, data);
18841
- responder(data);
18842
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
18843
- };
18844
- disposers.push(onCommunityCreated(realtimeRouter()), onCommunityDeleted(realtimeRouter()), onCommunityUpdated(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityLeft(realtimeRouter()), onCommunityUserChanged(realtimeRouter()));
18845
- onFetch(true);
19480
+ return communities;
19481
+ }
19482
+ }
19483
+
19484
+ /* begin_public_function
19485
+ id: community.query
19486
+ */
19487
+ /**
19488
+ * ```js
19489
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
19490
+ *
19491
+ * let communities = []
19492
+ * const unsub = CommunityRepository.getCommunities({
19493
+ * displayName: Amity.Community['displayName'],
19494
+ * }, response => merge(communities, response.data))
19495
+ * ```
19496
+ *
19497
+ * Observe all mutations on a list of {@link Amity.Community}s
19498
+ *
19499
+ * @param params for querying communities
19500
+ * @param callback the function to call when new data are available
19501
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
19502
+ *
19503
+ * @category Community Live Collection
19504
+ */
19505
+ const getCommunities = (params, callback, config) => {
19506
+ const { log, cache } = getActiveClient();
19507
+ if (!cache) {
19508
+ console.log(ENABLE_CACHE_MESSAGE);
19509
+ }
19510
+ const timestamp = Date.now();
19511
+ log(`getCommunities(tmpid: ${timestamp}) > listen`);
19512
+ const communitiesLiveCollection = new CommunityLiveCollectionController(params, callback);
19513
+ const disposers = communitiesLiveCollection.startSubscription();
19514
+ const cacheKey = communitiesLiveCollection.getCacheKey();
18846
19515
  disposers.push(() => dropFromCache(cacheKey));
18847
19516
  return () => {
18848
19517
  log(`getCommunities(tmpid: ${timestamp}) > dispose`);
@@ -19300,7 +19969,7 @@ const unbanMembers = async (communityId, userIds) => {
19300
19969
  };
19301
19970
  /* end_public_function */
19302
19971
 
19303
- var index$a = /*#__PURE__*/Object.freeze({
19972
+ var index$9 = /*#__PURE__*/Object.freeze({
19304
19973
  __proto__: null,
19305
19974
  addRoles: addRoles,
19306
19975
  removeRoles: removeRoles,
@@ -19308,299 +19977,10 @@ var index$a = /*#__PURE__*/Object.freeze({
19308
19977
  unbanMembers: unbanMembers
19309
19978
  });
19310
19979
 
19311
- /* begin_public_function
19312
- id: community.membership.add_members
19313
- */
19314
- /**
19315
- * ```js
19316
- * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
19317
- * const updated = await CommunityRepository.moderation.addMembers(communityId, ['foo', 'bar'])
19318
- * ```
19319
- *
19320
- * Adds a list of {@link Amity.InternalUser} to a {@link Amity.Community} to add users to
19321
- *
19322
- * @param communityId The ID of the {@link Amity.Community} to perform
19323
- * @param userIds The list of IDs {@link Amity.InternalUser} to add
19324
- * @returns A success boolean if the {@link Amity.InternalUser} were added to the {@link Amity.Community}
19325
- *
19326
- * @category Community API
19327
- * @async
19328
- */
19329
- const addMembers = async (communityId, userIds) => {
19330
- const client = getActiveClient();
19331
- client.log('community/moderation/addMembers', communityId, userIds);
19332
- const { data: payload } = await client.http.post(`/api/v3/communities/${communityId}/users`, { communityId, userIds });
19333
- fireEvent('community.userAdded', payload);
19334
- const data = prepareMembershipPayload(payload, 'communityUsers');
19335
- if (client.cache)
19336
- ingestInCache(data);
19337
- const { communityUsers } = data;
19338
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership === 'member');
19339
- };
19340
- /* end_public_function */
19341
-
19342
- /* begin_public_function
19343
- id: community.membership.remove_member
19344
- */
19345
- /**
19346
- * ```js
19347
- * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
19348
- * const updated = await CommunityRepository.moderation.removeMembers(communityId, ['foo', 'bar'])
19349
- * ```
19350
- *
19351
- * Removes a list of {@link Amity.InternalUser} from a {@link Amity.Community}
19352
- *
19353
- * @param communityId The ID of the {@link Amity.Community} to edit
19354
- * @param userIds The list of IDs {@link Amity.InternalUser} to remove
19355
- * @returns A success boolean if the list of {@link Amity.InternalUser} were removed from the {@link Amity.Community}
19356
- *
19357
- * @category Community API
19358
- * @async
19359
- */
19360
- const removeMembers = async (communityId, userIds) => {
19361
- const client = getActiveClient();
19362
- client.log('community/moderation/removeMembers', communityId, userIds);
19363
- const { data: payload } = await client.http.delete(`/api/v3/communities/${communityId}/users`, { data: { communityId, userIds } });
19364
- fireEvent('community.userRemoved', payload);
19365
- const data = prepareMembershipPayload(payload, 'communityUsers');
19366
- if (client.cache)
19367
- ingestInCache(data);
19368
- const { communityUsers } = data;
19369
- return !!communityUsers.find(communityUser => communityUser.communityId === communityId && communityUser.communityMembership !== 'member');
19370
- };
19371
- /* end_public_function */
19372
-
19373
- /**
19374
- * ```js
19375
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
19376
- * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
19377
- * ```
19378
- *
19379
- * Queries a paginable list of {@link Amity.CommunityUser} objects
19380
- *
19381
- * @param query The query parameters
19382
- * @returns A page of {@link Amity.CommunityUser} objects
19383
- *
19384
- * @category Community API
19385
- * @async
19386
- * */
19387
- const queryCommunityMembers = async (query) => {
19388
- const client = getActiveClient();
19389
- client.log('community/queryCommunityMembers', query);
19390
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit } = _a, params = __rest(_a, ["page", "limit"]);
19391
- const options = (() => {
19392
- if (page)
19393
- return { token: page };
19394
- if (limit)
19395
- return { limit };
19396
- return undefined;
19397
- })();
19398
- const { data: queryPayload } = await client.http.get(`/api/v3/communities/${params.communityId}/users`, {
19399
- params: Object.assign(Object.assign({}, params), { options }),
19400
- });
19401
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
19402
- const preparedPayload = prepareMembershipPayload(payload, 'communityUsers');
19403
- const { communityUsers } = preparedPayload;
19404
- const cachedAt = client.cache && Date.now();
19405
- if (client.cache) {
19406
- ingestInCache(preparedPayload, { cachedAt });
19407
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
19408
- pushToCache(cacheKey, {
19409
- communityUsers: communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19410
- paging,
19411
- });
19412
- }
19413
- return { data: communityUsers, cachedAt, paging };
19414
- };
19415
- /**
19416
- * ```js
19417
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
19418
- * const communityMembers = await queryCommunityMembers(query)
19419
- * ```
19420
- *
19421
- * Queries a paginable list of {@link Amity.InternalPost} objects from cache
19422
- *
19423
- * @param query The query parameters
19424
- * @returns posts
19425
- *
19426
- * @category Post API
19427
- */
19428
- queryCommunityMembers.locally = (query) => {
19429
- var _a, _b;
19430
- const client = getActiveClient();
19431
- client.log('community/queryCommunityMembers', query);
19432
- if (!client.cache)
19433
- return;
19434
- const _c = query !== null && query !== void 0 ? query : {}, { page, limit } = _c, params = __rest(_c, ["page", "limit"]);
19435
- const options = (() => {
19436
- if (page)
19437
- return { token: page };
19438
- if (limit)
19439
- return { limit };
19440
- return undefined;
19441
- })();
19442
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
19443
- const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
19444
- if (!(data === null || data === void 0 ? void 0 : data.communityUsers.length))
19445
- return;
19446
- const communityUsers = data.communityUsers
19447
- .map(key => pullFromCache(['communityUsers', 'get', key]))
19448
- .filter(Boolean)
19449
- .map(({ data }) => data);
19450
- const { paging } = data;
19451
- return communityUsers.length === ((_b = data === null || data === void 0 ? void 0 : data.communityUsers) === null || _b === void 0 ? void 0 : _b.length)
19452
- ? { data: communityUsers, cachedAt, paging }
19453
- : undefined;
19454
- };
19455
-
19456
- /*
19457
- * Exported for testing
19458
- * @hidden
19459
- */
19460
- const applyFilter = (data, params) => {
19461
- let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
19462
- if (params.memberships) {
19463
- communityMembers = communityMembers.filter(({ communityMembership }) => {
19464
- const membership = params.memberships;
19465
- return membership.includes(communityMembership);
19466
- });
19467
- }
19468
- if (params.search) {
19469
- communityMembers = filterBySearchTerm(communityMembers, params.search);
19470
- }
19471
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
19472
- communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
19473
- return communityMembers;
19474
- };
19475
- /* begin_public_function
19476
- id: community.membership.query
19477
- */
19478
- /**
19479
- * ```js
19480
- * import { getMembers } from '@amityco/ts-sdk-react-native'
19481
- *
19482
- * let communityMembers = []
19483
- * const unsub = getMembers({
19484
- * communityId: Amity.Community['communityId'],
19485
- * }, response => merge(communityMembers, response.data))
19486
- * ```
19487
- *
19488
- * Observe all mutations on a list of {@link Amity.CommunityUser}s
19489
- *
19490
- * @param params for querying community users
19491
- * @param callback the function to call when new data are available
19492
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
19493
- *
19494
- * @category Community Live Collection
19495
- */
19496
- const getMembers = (params, callback, config) => {
19497
- const { log, cache } = getActiveClient();
19498
- if (!cache) {
19499
- console.log(ENABLE_CACHE_MESSAGE);
19500
- }
19501
- const timestamp = Date.now();
19502
- log(`getMembers(tmpid: ${timestamp}) > listen`);
19503
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
19504
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
19505
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
19506
- const disposers = [];
19507
- const cacheKey = ['communityUsers', 'collection', queryParams];
19508
- const cacheByCommunityIdKey = [
19509
- 'communityUsers',
19510
- 'collection',
19511
- { communityId: params.communityId },
19512
- ];
19513
- const responder = (data, isEventModel = false) => {
19514
- var _a, _b;
19515
- const communityMembers = (_a = data.data
19516
- .map(id => pullFromCache(['communityUsers', 'get', id]))
19517
- .filter(Boolean)
19518
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
19519
- callback({
19520
- onNextPage: onFetch,
19521
- data: isEventModel ? applyFilter(communityMembers, params) : communityMembers,
19522
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
19523
- loading: data.loading,
19524
- error: data.error,
19525
- });
19526
- };
19527
- const realtimeRouter = (_) => (_, communityMembers) => {
19528
- var _a;
19529
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19530
- if (!collection) {
19531
- return;
19532
- }
19533
- const communityMemberCacheIds = communityMembers
19534
- .map(communityMember => {
19535
- if (params.communityId !== communityMember.communityId) {
19536
- return;
19537
- }
19538
- const communityMemberCacheId = getResolver('communityUsers')({
19539
- communityId: params.communityId,
19540
- userId: communityMember.userId,
19541
- });
19542
- return communityMemberCacheId;
19543
- })
19544
- .filter(isNonNullable);
19545
- collection.data = [...new Set([...communityMemberCacheIds, ...collection.data])];
19546
- pushToCache(cacheKey, collection);
19547
- pushToCache(cacheByCommunityIdKey, collection);
19548
- responder(collection, true);
19549
- };
19550
- const onFetch = (initial = false) => {
19551
- var _a, _b;
19552
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19553
- const communityMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19554
- if (!initial && communityMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
19555
- return;
19556
- 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 }));
19557
- runQuery(query, ({ data: result, error, loading, paging }) => {
19558
- const data = {
19559
- loading,
19560
- error,
19561
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
19562
- data: communityMembers,
19563
- };
19564
- if (result) {
19565
- data.data = [
19566
- ...new Set([...communityMembers, ...result.map(getResolver('communityUsers'))]),
19567
- ];
19568
- }
19569
- pushToCache(cacheKey, data);
19570
- pushToCache(cacheByCommunityIdKey, data);
19571
- responder(data);
19572
- }, queryOptions(policy));
19573
- };
19574
- disposers.push(onCommunityLeft(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityUserBanned(realtimeRouter()), onCommunityUserUnbanned(realtimeRouter()), onCommunityUserChanged(realtimeRouter()), onCommunityUserRoleAdded(realtimeRouter()), onCommunityUserRoleRemoved(realtimeRouter()));
19575
- onFetch(true);
19576
- return () => {
19577
- log(`getMembers(tmpid: ${timestamp}) > dispose`);
19578
- disposers.forEach(fn => fn());
19579
- };
19580
- };
19581
- /* end_public_function */
19582
-
19583
- var index$9 = /*#__PURE__*/Object.freeze({
19584
- __proto__: null,
19585
- addMembers: addMembers,
19586
- removeMembers: removeMembers,
19587
- applyFilter: applyFilter,
19588
- getMembers: getMembers,
19589
- onCommunityUserAdded: onCommunityUserAdded,
19590
- onCommunityUserRemoved: onCommunityUserRemoved,
19591
- onCommunityUserBanned: onCommunityUserBanned,
19592
- onCommunityUserChanged: onCommunityUserChanged,
19593
- onCommunityUserUnbanned: onCommunityUserUnbanned,
19594
- onCommunityUserRoleAdded: onCommunityUserRoleAdded,
19595
- onCommunityUserRoleRemoved: onCommunityUserRoleRemoved,
19596
- onCommunityJoined: onCommunityJoined,
19597
- onCommunityLeft: onCommunityLeft
19598
- });
19599
-
19600
19980
  var index$8 = /*#__PURE__*/Object.freeze({
19601
19981
  __proto__: null,
19602
- Moderation: index$a,
19603
- Membership: index$9,
19982
+ Moderation: index$9,
19983
+ Membership: index$a,
19604
19984
  getCommunityByIds: getCommunities$1,
19605
19985
  createCommunity: createCommunity,
19606
19986
  updateCommunity: updateCommunity,