@amityco/ts-sdk-react-native 6.23.0 → 6.23.1-d8b4c4c.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 (214) hide show
  1. package/.env +26 -26
  2. package/dist/@types/core/events.d.ts +7 -0
  3. package/dist/@types/core/events.d.ts.map +1 -1
  4. package/dist/@types/core/model.d.ts +4 -2
  5. package/dist/@types/core/model.d.ts.map +1 -1
  6. package/dist/@types/core/payload.d.ts +2 -1
  7. package/dist/@types/core/payload.d.ts.map +1 -1
  8. package/dist/@types/domains/community.d.ts +30 -1
  9. package/dist/@types/domains/community.d.ts.map +1 -1
  10. package/dist/@types/domains/stream.d.ts +19 -3
  11. package/dist/@types/domains/stream.d.ts.map +1 -1
  12. package/dist/client/api/secureLogout.d.ts +1 -1
  13. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  14. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  15. package/dist/commentRepository/internalApi/createComment.d.ts.map +1 -1
  16. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  17. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  18. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  19. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  20. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  21. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts +14 -0
  22. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts.map +1 -0
  23. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts +9 -0
  24. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts.map +1 -0
  25. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +15 -0
  26. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -0
  27. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts +10 -0
  28. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts.map +1 -0
  29. package/dist/communityRepository/communityMembership/observers/getMembers.d.ts.map +1 -1
  30. package/dist/communityRepository/communityMembership/observers/index.d.ts +1 -0
  31. package/dist/communityRepository/communityMembership/observers/index.d.ts.map +1 -1
  32. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.d.ts +14 -0
  33. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.d.ts.map +1 -0
  34. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts +9 -0
  35. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts.map +1 -0
  36. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts +15 -0
  37. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts.map +1 -0
  38. package/dist/communityRepository/communityMembership/observers/searchMembers/enums.d.ts +10 -0
  39. package/dist/communityRepository/communityMembership/observers/searchMembers/enums.d.ts.map +1 -0
  40. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts +20 -0
  41. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts.map +1 -0
  42. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts +14 -0
  43. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -0
  44. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts +9 -0
  45. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts.map +1 -0
  46. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +15 -0
  47. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -0
  48. package/dist/communityRepository/observers/getCommunities/enums.d.ts +6 -0
  49. package/dist/communityRepository/observers/getCommunities/enums.d.ts.map +1 -0
  50. package/dist/communityRepository/observers/getCommunities.d.ts.map +1 -1
  51. package/dist/communityRepository/observers/index.d.ts +1 -0
  52. package/dist/communityRepository/observers/index.d.ts.map +1 -1
  53. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts +14 -0
  54. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts.map +1 -0
  55. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts +9 -0
  56. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -0
  57. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +15 -0
  58. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -0
  59. package/dist/communityRepository/observers/searchCommunities/enums.d.ts +6 -0
  60. package/dist/communityRepository/observers/searchCommunities/enums.d.ts.map +1 -0
  61. package/dist/communityRepository/observers/searchCommunities.d.ts +20 -0
  62. package/dist/communityRepository/observers/searchCommunities.d.ts.map +1 -0
  63. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  64. package/dist/communityRepository/utils/saveCommunityUsers.d.ts +2 -0
  65. package/dist/communityRepository/utils/saveCommunityUsers.d.ts.map +1 -0
  66. package/dist/core/events.d.ts +3 -3
  67. package/dist/core/events.d.ts.map +1 -1
  68. package/dist/core/liveCollection/LiveCollectionController.d.ts +4 -1
  69. package/dist/core/liveCollection/LiveCollectionController.d.ts.map +1 -1
  70. package/dist/core/model/idResolvers.d.ts.map +1 -1
  71. package/dist/core/model/index.d.ts.map +1 -1
  72. package/dist/index.cjs.js +1604 -977
  73. package/dist/index.esm.js +1372 -745
  74. package/dist/index.umd.js +4 -4
  75. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts +12 -0
  76. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts.map +1 -0
  77. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts +12 -0
  78. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts.map +1 -0
  79. package/dist/marker/events/onUserFeedMarkerUpdated.d.ts.map +1 -1
  80. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts +1 -1
  81. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts.map +1 -1
  82. package/dist/postRepository/observers/getPost.d.ts.map +1 -1
  83. package/dist/postRepository/observers/getPosts.d.ts.map +1 -1
  84. package/dist/streamRepository/api/createStream.d.ts +4 -4
  85. package/dist/streamRepository/api/createStream.d.ts.map +1 -1
  86. package/dist/streamRepository/api/deleteStream.d.ts +4 -4
  87. package/dist/streamRepository/api/deleteStream.d.ts.map +1 -1
  88. package/dist/streamRepository/api/disposeStream.d.ts +4 -4
  89. package/dist/streamRepository/api/disposeStream.d.ts.map +1 -1
  90. package/dist/streamRepository/api/queryStreams.d.ts +4 -4
  91. package/dist/streamRepository/api/queryStreams.d.ts.map +1 -1
  92. package/dist/streamRepository/api/updateStream.d.ts.map +1 -1
  93. package/dist/streamRepository/events/index.d.ts +2 -0
  94. package/dist/streamRepository/events/index.d.ts.map +1 -1
  95. package/dist/streamRepository/events/onStreamFlagged.d.ts +17 -0
  96. package/dist/streamRepository/events/onStreamFlagged.d.ts.map +1 -0
  97. package/dist/streamRepository/events/onStreamRecorded.d.ts +2 -2
  98. package/dist/streamRepository/events/onStreamRecorded.d.ts.map +1 -1
  99. package/dist/streamRepository/events/onStreamStarted.d.ts +2 -2
  100. package/dist/streamRepository/events/onStreamStarted.d.ts.map +1 -1
  101. package/dist/streamRepository/events/onStreamStopped.d.ts +2 -2
  102. package/dist/streamRepository/events/onStreamStopped.d.ts.map +1 -1
  103. package/dist/streamRepository/events/onStreamTerminated.d.ts +17 -0
  104. package/dist/streamRepository/events/onStreamTerminated.d.ts.map +1 -0
  105. package/dist/streamRepository/internalApi/queryStreams.d.ts +3 -3
  106. package/dist/streamRepository/internalApi/queryStreams.d.ts.map +1 -1
  107. package/dist/streamRepository/observers/getStreamById.d.ts +1 -0
  108. package/dist/streamRepository/observers/getStreamById.d.ts.map +1 -1
  109. package/dist/streamRepository/observers/getStreams/GetStreamsLiveCollectionController.d.ts +14 -0
  110. package/dist/streamRepository/observers/getStreams/GetStreamsLiveCollectionController.d.ts.map +1 -0
  111. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts +14 -0
  112. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts.map +1 -0
  113. package/dist/streamRepository/observers/getStreams/GetStreamsQueryStreamController.d.ts +15 -0
  114. package/dist/streamRepository/observers/getStreams/GetStreamsQueryStreamController.d.ts.map +1 -0
  115. package/dist/streamRepository/observers/getStreams/getStreams.d.ts +2 -0
  116. package/dist/streamRepository/observers/getStreams/getStreams.d.ts.map +1 -0
  117. package/dist/streamRepository/observers/getStreams/index.d.ts +2 -0
  118. package/dist/streamRepository/observers/getStreams/index.d.ts.map +1 -0
  119. package/dist/utils/linkedObject/index.d.ts +1 -0
  120. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  121. package/dist/utils/linkedObject/streamLinkedObject.d.ts +2 -0
  122. package/dist/utils/linkedObject/streamLinkedObject.d.ts.map +1 -0
  123. package/dist/utils/liveObject.d.ts +3 -0
  124. package/dist/utils/liveObject.d.ts.map +1 -1
  125. package/package.json +1 -1
  126. package/src/@types/core/events.ts +12 -0
  127. package/src/@types/core/model.ts +4 -2
  128. package/src/@types/core/payload.ts +2 -1
  129. package/src/@types/domains/community.ts +50 -1
  130. package/src/@types/domains/stream.ts +23 -3
  131. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +2 -2
  132. package/src/channelRepository/observers/getChannel.ts +2 -2
  133. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +7 -7
  134. package/src/client/api/secureLogout.ts +1 -1
  135. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +6 -3
  136. package/src/commentRepository/api/createComment.ts +2 -2
  137. package/src/commentRepository/api/deleteComment.ts +2 -4
  138. package/src/commentRepository/events/utils.ts +1 -1
  139. package/src/commentRepository/internalApi/createComment.ts +3 -2
  140. package/src/commentRepository/internalApi/deleteComment.ts +2 -2
  141. package/src/communityRepository/api/createCommunity.ts +5 -2
  142. package/src/communityRepository/api/getCommunities.ts +5 -1
  143. package/src/communityRepository/api/getCommunity.ts +5 -1
  144. package/src/communityRepository/api/queryCommunities.ts +2 -2
  145. package/src/communityRepository/api/updateCommunity.ts +5 -1
  146. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +152 -0
  147. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.ts +26 -0
  148. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +114 -0
  149. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +9 -0
  150. package/src/communityRepository/communityMembership/observers/getMembers.ts +15 -128
  151. package/src/communityRepository/communityMembership/observers/index.ts +1 -0
  152. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.ts +130 -0
  153. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.ts +29 -0
  154. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.ts +105 -0
  155. package/src/communityRepository/communityMembership/observers/searchMembers/enums.ts +9 -0
  156. package/src/communityRepository/communityMembership/observers/searchMembers.ts +60 -0
  157. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +147 -0
  158. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +31 -0
  159. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +86 -0
  160. package/src/communityRepository/observers/getCommunities/enums.ts +5 -0
  161. package/src/communityRepository/observers/getCommunities.ts +7 -150
  162. package/src/communityRepository/observers/index.ts +1 -0
  163. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +129 -0
  164. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +31 -0
  165. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +81 -0
  166. package/src/communityRepository/observers/searchCommunities/enums.ts +5 -0
  167. package/src/communityRepository/observers/searchCommunities.ts +56 -0
  168. package/src/communityRepository/utils/payload.ts +35 -1
  169. package/src/communityRepository/utils/saveCommunityUsers.ts +16 -0
  170. package/src/core/liveCollection/LiveCollectionController.ts +6 -3
  171. package/src/core/model/idResolvers.ts +1 -0
  172. package/src/core/model/index.ts +1 -0
  173. package/src/marker/events/onChannelUnreadUpdatedLocal.ts +29 -0
  174. package/src/marker/events/onSubChannelMarkerFetched.ts +1 -1
  175. package/src/marker/events/onSubChannelUnreadUpdatedLocal.ts +29 -0
  176. package/src/marker/events/onUserFeedMarkerUpdated.ts +3 -4
  177. package/src/marker/utils/reCalculateChannelUnreadInfo.ts +7 -3
  178. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +3 -3
  179. package/src/postRepository/api/editPost.ts +1 -1
  180. package/src/postRepository/api/updatePost.ts +1 -1
  181. package/src/postRepository/observers/getPost.ts +26 -0
  182. package/src/postRepository/observers/getPosts.ts +31 -0
  183. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +2 -2
  184. package/src/storyRepository/observers/getStoriesByTargetIds/StoryLiveCollectionController.ts +1 -1
  185. package/src/streamRepository/api/createStream.ts +8 -5
  186. package/src/streamRepository/api/deleteStream.ts +6 -4
  187. package/src/streamRepository/api/disposeStream.ts +5 -5
  188. package/src/streamRepository/api/queryStreams.ts +4 -4
  189. package/src/streamRepository/api/updateStream.ts +2 -1
  190. package/src/streamRepository/events/index.ts +2 -0
  191. package/src/streamRepository/events/onStreamFlagged.ts +37 -0
  192. package/src/streamRepository/events/onStreamRecorded.ts +4 -2
  193. package/src/streamRepository/events/onStreamStarted.ts +4 -2
  194. package/src/streamRepository/events/onStreamStopped.ts +4 -2
  195. package/src/streamRepository/events/onStreamTerminated.ts +37 -0
  196. package/src/streamRepository/internalApi/queryStreams.ts +3 -3
  197. package/src/streamRepository/observers/getStreamById.ts +18 -5
  198. package/src/streamRepository/observers/getStreams/GetStreamsLiveCollectionController.ts +114 -0
  199. package/src/streamRepository/observers/getStreams/GetStreamsPageController.ts +23 -0
  200. package/src/streamRepository/observers/getStreams/GetStreamsQueryStreamController.ts +83 -0
  201. package/src/streamRepository/observers/getStreams/getStreams.ts +32 -0
  202. package/src/streamRepository/observers/getStreams/index.ts +1 -0
  203. package/src/streamRepository/observers/tests/getStreamById.test.ts +1 -1
  204. package/src/subChannelRepository/observers/getSubChannel.ts +2 -2
  205. package/src/subChannelRepository/observers/getSubChannels/SubChannelLiveCollectionController.ts +4 -4
  206. package/src/utils/linkedObject/index.ts +2 -0
  207. package/src/utils/linkedObject/streamLinkedObject.ts +11 -0
  208. package/src/utils/liveObject.ts +3 -0
  209. package/dist/streamRepository/api/getStreams.d.ts +0 -39
  210. package/dist/streamRepository/api/getStreams.d.ts.map +0 -1
  211. package/dist/streamRepository/observers/getStreams.d.ts +0 -17
  212. package/dist/streamRepository/observers/getStreams.d.ts.map +0 -1
  213. package/src/streamRepository/api/getStreams.ts +0 -81
  214. package/src/streamRepository/observers/getStreams.ts +0 -152
package/dist/index.cjs.js CHANGED
@@ -546,6 +546,7 @@ const idResolvers = {
546
546
  reaction: ({ referenceType, referenceId }) => `${referenceType}#${referenceId}`,
547
547
  reactor: ({ reactionId }) => reactionId,
548
548
  stream: ({ streamId }) => streamId,
549
+ streamModeration: ({ streamId }) => streamId,
549
550
  follow: ({ from, to }) => `${from}#${to}`,
550
551
  followInfo: ({ userId }) => userId,
551
552
  followCount: ({ userId }) => userId,
@@ -595,6 +596,7 @@ const PAYLOAD2MODEL = {
595
596
  reactors: 'reactor',
596
597
  reactions: 'reaction',
597
598
  videoStreamings: 'stream',
599
+ videoStreamModerations: 'streamModeration',
598
600
  follows: 'follow',
599
601
  followCounts: 'followCount',
600
602
  feeds: 'feed',
@@ -5269,6 +5271,13 @@ const storyLinkedObject = (story) => {
5269
5271
  } });
5270
5272
  };
5271
5273
 
5274
+ const streamLinkedObject = (stream) => {
5275
+ return Object.assign(Object.assign({}, stream), { get moderation() {
5276
+ var _a;
5277
+ return (_a = pullFromCache(['streamModeration', 'get', stream.streamId])) === null || _a === void 0 ? void 0 : _a.data;
5278
+ } });
5279
+ };
5280
+
5272
5281
  const categoryLinkedObject = (category) => {
5273
5282
  return Object.assign(Object.assign({}, category), { get avatar() {
5274
5283
  var _a;
@@ -5428,7 +5437,7 @@ const markAsReadBySegment = async ({ subChannelId, readToSegment, }) => {
5428
5437
  }
5429
5438
  };
5430
5439
 
5431
- const reCalculateChannelUnreadInfo = async (channelId) => {
5440
+ const reCalculateChannelUnreadInfo = (channelId) => {
5432
5441
  var _a;
5433
5442
  const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
5434
5443
  const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
@@ -5445,10 +5454,12 @@ const reCalculateChannelUnreadInfo = async (channelId) => {
5445
5454
  .reduce((acc, cur) => acc + cur, 0);
5446
5455
  isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
5447
5456
  }
5448
- pushToCache(cacheKeyChannelUnread, Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
5457
+ const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
5449
5458
  channelId,
5450
5459
  createdAt: new Date().toISOString(),
5451
- })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned }));
5460
+ })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
5461
+ pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
5462
+ return channelUnreadInfo;
5452
5463
  };
5453
5464
 
5454
5465
  class MessageReadReceiptSyncEngine {
@@ -5593,9 +5604,11 @@ class MessageReadReceiptSyncEngine {
5593
5604
  if (subChannelUnreadInfo && segment > subChannelUnreadInfo.readToSegment) {
5594
5605
  subChannelUnreadInfo.readToSegment = segment;
5595
5606
  subChannelUnreadInfo.unreadCount = Math.max(subChannelUnreadInfo.lastSegment - segment, 0);
5596
- reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
5607
+ const channelUnreadInfo = reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
5608
+ fireEvent('local.channelUnread.updated', channelUnreadInfo);
5609
+ pushToCache(cacheKey, subChannelUnreadInfo);
5610
+ fireEvent('local.subChannelUnread.updated', subChannelUnreadInfo);
5597
5611
  }
5598
- pushToCache(cacheKey, subChannelUnreadInfo);
5599
5612
  // Step 2: Enqueue the read receipt
5600
5613
  this.enqueueReadReceipt(subChannelId, segment);
5601
5614
  }
@@ -5733,6 +5746,7 @@ const LinkedObject = {
5733
5746
  post: postLinkedObject,
5734
5747
  user: userLinkedObject,
5735
5748
  category: categoryLinkedObject,
5749
+ stream: streamLinkedObject,
5736
5750
  story: storyLinkedObject,
5737
5751
  storyTarget: storyTargetLinkedObject,
5738
5752
  message: messageLinkedObject,
@@ -8590,9 +8604,9 @@ const enableUnreadCount = () => {
8590
8604
  const onUserFeedMarkerUpdated = (callback) => {
8591
8605
  const client = getActiveClient();
8592
8606
  const filter = (payload) => {
8593
- // update sub channel unread info and channel unread info in cache
8594
- persistUnreadCountInfo(payload);
8595
- callback(payload.feedMarkers[0]);
8607
+ payload.feedMarkers.forEach(feedMarker => {
8608
+ callback(feedMarker);
8609
+ });
8596
8610
  };
8597
8611
  return createEventSubscriber(client, 'feedMarker/onUserFeedMarkerUpdated', 'marker.userFeed-updated', filter);
8598
8612
  };
@@ -9102,7 +9116,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
9102
9116
  */
9103
9117
  /**
9104
9118
  * ```js
9105
- * import { Client } from '@amityco/ts-sdk'
9119
+ * import { Client } from '@amityco/ts-sdk-react-native'
9106
9120
  * const success = await Client.secureLogout()
9107
9121
  * ```
9108
9122
  *
@@ -9188,7 +9202,7 @@ const onChannelMarkerFetched = (callback) => {
9188
9202
  const onSubChannelMarkerFetched = (callback) => {
9189
9203
  const client = getActiveClient();
9190
9204
  const filter = (payload) => {
9191
- callback(payload.userFeedMarkers[0]);
9205
+ payload.userFeedMarkers.forEach(callback);
9192
9206
  };
9193
9207
  return createEventSubscriber(client, 'subChannelMarker/onSubChannelMarkerFetched', 'local.subChannelMarker.fetched', filter);
9194
9208
  };
@@ -9458,6 +9472,9 @@ function isEqual(x, y) {
9458
9472
  }));
9459
9473
  }
9460
9474
 
9475
+ /**
9476
+ * @deprecated This function is deprecated
9477
+ */
9461
9478
  const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
9462
9479
  const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
9463
9480
  const { cache } = getActiveClient();
@@ -15443,7 +15460,7 @@ class LiveCollectionController {
15443
15460
  this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
15444
15461
  }
15445
15462
  }
15446
- loadPage(initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
15463
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
15447
15464
  this.setup();
15448
15465
  this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
15449
15466
  if (initial) {
@@ -15513,7 +15530,7 @@ class MessageLiveCollectionController extends LiveCollectionController {
15513
15530
  this.query = query;
15514
15531
  this.queryStreamController = new MessageQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMessagePayload, this.paginationController);
15515
15532
  this.callback = callback.bind(this);
15516
- this.loadPage(true);
15533
+ this.loadPage({ initial: true });
15517
15534
  }
15518
15535
  setup() {
15519
15536
  var _a;
@@ -15561,8 +15578,8 @@ class MessageLiveCollectionController extends LiveCollectionController {
15561
15578
  if (!this.shouldNotify(data) && origin === 'event')
15562
15579
  return;
15563
15580
  this.callback({
15564
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
15565
- onPrevPage: () => this.loadPage(false, "prev" /* Amity.LiveCollectionPageDirection.PREV */),
15581
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
15582
+ onPrevPage: () => this.loadPage({ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */ }),
15566
15583
  data,
15567
15584
  hasNextPage: !!this.paginationController.getNextToken(),
15568
15585
  hasPrevPage: !!this.paginationController.getPrevToken(),
@@ -15844,6 +15861,24 @@ var index$f = /*#__PURE__*/Object.freeze({
15844
15861
  convertQueryParams: convertQueryParams$1
15845
15862
  });
15846
15863
 
15864
+ /**
15865
+ * Internal used only
15866
+ *
15867
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
15868
+ *
15869
+ * @param callback The function to call when the event was fired
15870
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
15871
+ *
15872
+ * @category MessageMarker Events
15873
+ */
15874
+ const onSubChannelUnreadUpdatedLocal = (callback) => {
15875
+ const client = getActiveClient();
15876
+ const filter = (payload) => {
15877
+ callback(payload);
15878
+ };
15879
+ return createEventSubscriber(client, 'subChannelMarker/onSubChannelUnreadUpdatedLocal', 'local.subChannelUnread.updated', filter);
15880
+ };
15881
+
15847
15882
  /* begin_public_function
15848
15883
  id: subchannel.get
15849
15884
  */
@@ -15996,7 +16031,7 @@ const getSubChannel = (subChannelId, callback) => {
15996
16031
  };
15997
16032
  return onMessageDeleted(updateMessagePreview);
15998
16033
  }, 'subChannelId', 'subChannel'),
15999
- convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
16034
+ convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
16000
16035
  ], {
16001
16036
  forceDispatch: true,
16002
16037
  });
@@ -16086,7 +16121,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16086
16121
  this.query = query;
16087
16122
  this.queryStreamController = new SubChannelQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareSubChannelPayload);
16088
16123
  this.callback = callback.bind(this);
16089
- this.loadPage(true);
16124
+ this.loadPage({ initial: true });
16090
16125
  }
16091
16126
  setup() {
16092
16127
  var _a;
@@ -16263,7 +16298,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16263
16298
  action: 'onUpdate',
16264
16299
  },
16265
16300
  {
16266
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
16301
+ fn: convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
16267
16302
  action: 'onUpdate',
16268
16303
  },
16269
16304
  ]);
@@ -16281,7 +16316,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16281
16316
  if (!this.shouldNotify(data) && origin === 'event')
16282
16317
  return;
16283
16318
  this.callback({
16284
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
16319
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
16285
16320
  data,
16286
16321
  hasNextPage: !!this.paginationController.getNextToken(),
16287
16322
  loading,
@@ -16421,6 +16456,24 @@ var index$e = /*#__PURE__*/Object.freeze({
16421
16456
  stopMessageReceiptSync: stopMessageReceiptSync
16422
16457
  });
16423
16458
 
16459
+ /**
16460
+ * Internal used only
16461
+ *
16462
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
16463
+ *
16464
+ * @param callback The function to call when the event was fired
16465
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
16466
+ *
16467
+ * @category MessageMarker Events
16468
+ */
16469
+ const onChannelUnreadUpdatedLocal = (callback) => {
16470
+ const client = getActiveClient();
16471
+ const filter = (payload) => {
16472
+ callback(payload);
16473
+ };
16474
+ return createEventSubscriber(client, 'channelMarker/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
16475
+ };
16476
+
16424
16477
  /* begin_public_function
16425
16478
  id: channel.get
16426
16479
  */
@@ -16596,7 +16649,7 @@ const getChannel = (channelId, callback) => {
16596
16649
  return onSubChannelUpdated(updateMessagePreview);
16597
16650
  }, 'channelId', 'channel'),
16598
16651
  convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
16599
- convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
16652
+ convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
16600
16653
  ], {
16601
16654
  forceDispatch: true,
16602
16655
  });
@@ -16756,7 +16809,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
16756
16809
  }, paginationController);
16757
16810
  this.paginationController = paginationController;
16758
16811
  this.callback = callback.bind(this);
16759
- this.loadPage(true);
16812
+ this.loadPage({ initial: true });
16760
16813
  }
16761
16814
  setup() {
16762
16815
  var _a;
@@ -16795,7 +16848,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
16795
16848
  return;
16796
16849
  this.callback({
16797
16850
  onNextPage: this.paginationController instanceof ChannelPaginationController
16798
- ? () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */)
16851
+ ? () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ })
16799
16852
  : undefined,
16800
16853
  data,
16801
16854
  hasNextPage: this.paginationController instanceof ChannelPaginationController
@@ -17075,10 +17128,6 @@ class ChannelLiveCollectionController extends LiveCollectionController {
17075
17128
  }, 'channelId', 'channel'),
17076
17129
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17077
17130
  },
17078
- {
17079
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
17080
- action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17081
- },
17082
17131
  {
17083
17132
  fn: convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
17084
17133
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -17104,6 +17153,10 @@ class ChannelLiveCollectionController extends LiveCollectionController {
17104
17153
  },
17105
17154
  action: "onResolve" /* Amity.ChannelActionType.OnResolve */,
17106
17155
  },
17156
+ {
17157
+ fn: convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
17158
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17159
+ },
17107
17160
  ];
17108
17161
  if (this.paginationController instanceof PaginationController) {
17109
17162
  return [
@@ -17318,7 +17371,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
17318
17371
  this.query = query;
17319
17372
  this.queryStreamController = new ChannelMemberQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareChannelPayload);
17320
17373
  this.callback = callback.bind(this);
17321
- this.loadPage(true);
17374
+ this.loadPage({ initial: true });
17322
17375
  }
17323
17376
  setup() {
17324
17377
  var _a;
@@ -17360,7 +17413,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
17360
17413
  if (!this.shouldNotify(data) && origin === 'event')
17361
17414
  return;
17362
17415
  this.callback({
17363
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
17416
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
17364
17417
  data,
17365
17418
  hasNextPage: !!this.paginationController.getNextToken(),
17366
17419
  loading,
@@ -17496,7 +17549,7 @@ const getMembers$1 = (params, callback, config) => {
17496
17549
  *
17497
17550
  * @category Channel Live Collection
17498
17551
  */
17499
- const searchMembers = (params, callback, config) => {
17552
+ const searchMembers$1 = (params, callback, config) => {
17500
17553
  return getMembers$1(params, callback);
17501
17554
  };
17502
17555
  /* end_public_function */
@@ -17507,7 +17560,7 @@ var index$d = /*#__PURE__*/Object.freeze({
17507
17560
  removeMembers: removeMembers$1,
17508
17561
  applyFilter: applyFilter$1,
17509
17562
  getMembers: getMembers$1,
17510
- searchMembers: searchMembers
17563
+ searchMembers: searchMembers$1
17511
17564
  });
17512
17565
 
17513
17566
  /* begin_public_function
@@ -17750,12 +17803,30 @@ var index$b = /*#__PURE__*/Object.freeze({
17750
17803
  prepareChannelPayload: prepareChannelPayload
17751
17804
  });
17752
17805
 
17806
+ const saveCommunityUsers = (communities, communityUsers) => {
17807
+ if (communities.length === 0 || communityUsers.length === 0)
17808
+ return;
17809
+ communities.forEach(({ communityId }) => {
17810
+ const collection = communityUsers.filter(({ communityId: userCommunityId }) => communityId === userCommunityId);
17811
+ pushToCache(['communityUsers', 'collection', communityId], collection);
17812
+ });
17813
+ };
17814
+
17753
17815
  const getMatchPostSetting = (value) => {
17754
17816
  var _a;
17755
17817
  return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
17756
17818
  CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
17757
17819
  value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
17758
17820
  };
17821
+ const convertCommunityUsersToUniqueObject = (communityUsers) => {
17822
+ if (!communityUsers)
17823
+ return communityUsers;
17824
+ const result = {};
17825
+ communityUsers.forEach(user => {
17826
+ result[user.userId] = user;
17827
+ });
17828
+ return result;
17829
+ };
17759
17830
  const prepareCommunityPayload = (rawPayload) => {
17760
17831
  // Unpack community payload by mapping payload field to postSetting value.
17761
17832
  const communities = rawPayload.communities.map((_a) => {
@@ -17765,7 +17836,18 @@ const prepareCommunityPayload = (rawPayload) => {
17765
17836
  onlyAdminCanPost,
17766
17837
  }) }, restCommunityPayload));
17767
17838
  });
17768
- const communityUsers = withUsers(rawPayload.communityUsers);
17839
+ const mergeCommunityUsers = communities.reduce((acc, { communityId }) => {
17840
+ var _a;
17841
+ const users = (_a = pullFromCache([
17842
+ 'communityUsers',
17843
+ 'collection',
17844
+ communityId,
17845
+ ])) === null || _a === void 0 ? void 0 : _a.data;
17846
+ if (!users)
17847
+ return acc;
17848
+ return Object.assign(Object.assign({}, convertCommunityUsersToUniqueObject(users)), acc);
17849
+ }, convertCommunityUsersToUniqueObject(rawPayload.communityUsers));
17850
+ const communityUsers = withUsers(Object.values(mergeCommunityUsers));
17769
17851
  const communityWithMembershipStatus = updateMembershipStatus(communities, communityUsers);
17770
17852
  return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers });
17771
17853
  };
@@ -17799,8 +17881,10 @@ const getCommunities$1 = async (communityIds) => {
17799
17881
  });
17800
17882
  const data = prepareCommunityPayload(payload);
17801
17883
  const cachedAt = client.cache && Date.now();
17802
- if (client.cache)
17884
+ if (client.cache) {
17803
17885
  ingestInCache(data, { cachedAt });
17886
+ saveCommunityUsers(data.communities, data.communityUsers);
17887
+ }
17804
17888
  return {
17805
17889
  data: data.communities,
17806
17890
  cachedAt,
@@ -17862,8 +17946,10 @@ const createCommunity = async (bundle) => {
17862
17946
  fireEvent('community.created', payload);
17863
17947
  const data = prepareCommunityPayload(payload);
17864
17948
  const cachedAt = client.cache && Date.now();
17865
- if (client.cache)
17949
+ if (client.cache) {
17866
17950
  ingestInCache(data, { cachedAt });
17951
+ saveCommunityUsers(data.communities, data.communityUsers);
17952
+ }
17867
17953
  const { communities } = data;
17868
17954
  return {
17869
17955
  data: communities[0],
@@ -17897,8 +17983,10 @@ const updateCommunity = async (communityId, patch) => {
17897
17983
  fireEvent('community.updated', payload);
17898
17984
  const data = prepareCommunityPayload(payload);
17899
17985
  const cachedAt = client.cache && Date.now();
17900
- if (client.cache)
17986
+ if (client.cache) {
17901
17987
  ingestInCache(data, { cachedAt });
17988
+ saveCommunityUsers(data.communities, data.communityUsers);
17989
+ }
17902
17990
  const { communities } = data;
17903
17991
  return {
17904
17992
  data: communities.find(community => community.communityId === communityId),
@@ -17928,8 +18016,10 @@ const getCommunity$1 = async (communityId) => {
17928
18016
  const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
17929
18017
  const data = prepareCommunityPayload(payload);
17930
18018
  const cachedAt = client.cache && Date.now();
17931
- if (client.cache)
18019
+ if (client.cache) {
17932
18020
  ingestInCache(data, { cachedAt });
18021
+ saveCommunityUsers(data.communities, data.communityUsers);
18022
+ }
17933
18023
  const { communities } = data;
17934
18024
  return {
17935
18025
  data: communities.find(community => community.communityId === communityId),
@@ -18469,50 +18559,140 @@ const observeCommunity = (communityId, callback) => {
18469
18559
  };
18470
18560
 
18471
18561
  /**
18472
- * ```js
18473
- * import { queryCommunities } from '@amityco/ts-sdk-react-native'
18474
- * const communities = await queryCommunities()
18475
- * ```
18476
- *
18477
- * Queries a paginable list of {@link Amity.Community} objects
18478
- * Search is performed by displayName such as `.startsWith(search)`
18479
- *
18480
- * @param query The query parameters
18481
- * @returns A page of {@link Amity.Community} objects
18482
- *
18483
- * @category Community API
18484
- * @async
18562
+ * TODO: handle cache receive cache option, and cache policy
18563
+ * TODO: check if querybyIds is supported
18485
18564
  */
18486
- const queryCommunities = async (query) => {
18487
- const client = getActiveClient();
18488
- client.log('channel/queryCommunities', query);
18489
- // safe decapsulation
18490
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit = 10 } = _a, params = __rest(_a, ["page", "limit"]);
18491
- const _b = params !== null && params !== void 0 ? params : {}, { displayName, membership, includeDeleted } = _b, restParams = __rest(_b, ["displayName", "membership", "includeDeleted"]);
18492
- const options = (() => {
18493
- if (page)
18494
- return { token: page };
18495
- if (limit)
18496
- return { limit };
18497
- return undefined;
18498
- })();
18499
- // API-FIX: parameters should be querystring.
18500
- // API-FIX: backend doesn't answer Amity.Response
18501
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
18502
- const { data } = await client.http.get(`/api/v3/communities`, {
18503
- params: Object.assign(Object.assign({}, restParams), { isDeleted: inferIsDeleted(includeDeleted), keyword: displayName, filter: membership, options }),
18504
- });
18505
- const { paging } = data, payload = __rest(data, ["paging"]);
18506
- const unpackedPayload = prepareCommunityPayload(payload);
18507
- const { communities } = unpackedPayload;
18508
- const cachedAt = client.cache && Date.now();
18509
- if (client.cache) {
18510
- ingestInCache(unpackedPayload, { cachedAt });
18511
- const cacheKey = ['community', 'query', Object.assign(Object.assign({}, params), { options })];
18512
- pushToCache(cacheKey, { communities: communities.map(getResolver('community')), paging });
18565
+ class CommunitiesPaginationController$1 extends PaginationController {
18566
+ async getRequest(queryParams, token) {
18567
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18568
+ const options = token ? { token } : { limit };
18569
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
18570
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
18571
+ });
18572
+ return queryResponse;
18513
18573
  }
18514
- return { data: communities, cachedAt, paging };
18515
- };
18574
+ }
18575
+
18576
+ class CommunitiesQueryStreamController$1 extends QueryStreamController {
18577
+ constructor(query, cacheKey, notifyChange, preparePayload) {
18578
+ super(query, cacheKey);
18579
+ this.notifyChange = notifyChange;
18580
+ this.preparePayload = preparePayload;
18581
+ }
18582
+ async saveToMainDB(response) {
18583
+ const processedPayload = await this.preparePayload(response);
18584
+ const client = getActiveClient();
18585
+ const cachedAt = client.cache && Date.now();
18586
+ if (client.cache) {
18587
+ ingestInCache(processedPayload, { cachedAt });
18588
+ }
18589
+ }
18590
+ appendToQueryStream(response, direction, refresh = false) {
18591
+ var _a, _b;
18592
+ if (refresh) {
18593
+ pushToCache(this.cacheKey, {
18594
+ data: response.communities.map(getResolver('community')),
18595
+ });
18596
+ }
18597
+ else {
18598
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18599
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18600
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
18601
+ }
18602
+ }
18603
+ reactor(action) {
18604
+ return (community) => {
18605
+ var _a;
18606
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18607
+ if (!collection)
18608
+ return;
18609
+ pushToCache(this.cacheKey, collection);
18610
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
18611
+ };
18612
+ }
18613
+ subscribeRTE(createSubscriber) {
18614
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
18615
+ }
18616
+ }
18617
+
18618
+ var EnumCommunityActions$1;
18619
+ (function (EnumCommunityActions) {
18620
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
18621
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
18622
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
18623
+ })(EnumCommunityActions$1 || (EnumCommunityActions$1 = {}));
18624
+
18625
+ /* eslint-disable no-use-before-define */
18626
+ class SearchCommunityLiveCollectionController extends LiveCollectionController {
18627
+ constructor(query, callback) {
18628
+ const queryStreamId = hash__default["default"](query);
18629
+ const cacheKey = ['community', 'collection', queryStreamId];
18630
+ const paginationController = new CommunitiesPaginationController$1(query);
18631
+ super(paginationController, queryStreamId, cacheKey, callback);
18632
+ this.query = query;
18633
+ this.queryStreamController = new CommunitiesQueryStreamController$1(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
18634
+ this.callback = callback.bind(this);
18635
+ this.loadPage({ initial: true });
18636
+ }
18637
+ setup() {
18638
+ var _a;
18639
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18640
+ if (!collection) {
18641
+ pushToCache(this.cacheKey, {
18642
+ data: [],
18643
+ params: {},
18644
+ });
18645
+ }
18646
+ }
18647
+ async persistModel(queryPayload) {
18648
+ await this.queryStreamController.saveToMainDB(queryPayload);
18649
+ }
18650
+ persistQueryStream({ response, direction, refresh, }) {
18651
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
18652
+ }
18653
+ startSubscription() {
18654
+ return this.queryStreamController.subscribeRTE([
18655
+ { fn: onCommunityDeleted, action: EnumCommunityActions$1.OnCommunityDeleted },
18656
+ { fn: onCommunityUpdated, action: EnumCommunityActions$1.OnCommunityUpdated },
18657
+ ]);
18658
+ }
18659
+ notifyChange({ origin, loading, error }) {
18660
+ var _a, _b;
18661
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18662
+ if (!collection)
18663
+ return;
18664
+ const data = this.applyFilter((_b = collection.data
18665
+ .map(id => pullFromCache(['community', 'get', id]))
18666
+ .filter(Boolean)
18667
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
18668
+ if (!this.shouldNotify(data) && origin === 'event')
18669
+ return;
18670
+ this.callback({
18671
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
18672
+ data,
18673
+ hasNextPage: !!this.paginationController.getNextToken(),
18674
+ loading,
18675
+ error,
18676
+ });
18677
+ }
18678
+ applyFilter(data) {
18679
+ const { userId } = getActiveClient();
18680
+ let communities = data;
18681
+ if (this.query.includeDeleted) {
18682
+ communities = filterByPropEquality(communities, 'isDeleted', false);
18683
+ }
18684
+ if (this.query.categoryId) {
18685
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
18686
+ }
18687
+ if (this.query.tags) {
18688
+ 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); }); });
18689
+ }
18690
+ if (this.query.membership && userId) {
18691
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
18692
+ }
18693
+ return communities;
18694
+ }
18695
+ }
18516
18696
 
18517
18697
  /* begin_public_function
18518
18698
  id: community.query
@@ -18522,7 +18702,7 @@ const queryCommunities = async (query) => {
18522
18702
  * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
18523
18703
  *
18524
18704
  * let communities = []
18525
- * const unsub = CommunityRepository.getCommunities({
18705
+ * const unsub = CommunityRepository.searchCommunities({
18526
18706
  * displayName: Amity.Community['displayName'],
18527
18707
  * }, response => merge(communities, response.data))
18528
18708
  * ```
@@ -18535,99 +18715,214 @@ const queryCommunities = async (query) => {
18535
18715
  *
18536
18716
  * @category Community Live Collection
18537
18717
  */
18538
- const getCommunities = (params, callback, config) => {
18539
- const { log, cache, userId } = getActiveClient();
18718
+ const searchCommunities = (params, callback, config) => {
18719
+ const { log, cache } = getActiveClient();
18540
18720
  if (!cache) {
18541
18721
  console.log(ENABLE_CACHE_MESSAGE);
18542
18722
  }
18543
18723
  const timestamp = Date.now();
18544
- log(`getCommunities(tmpid: ${timestamp}) > listen`);
18545
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
18546
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
18547
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
18548
- const disposers = [];
18549
- const cacheKey = ['community', 'collection', queryParams];
18550
- const responder = (data) => {
18551
- var _a, _b;
18552
- let communities = (_a = data.data
18553
- .map(communityId => pullFromCache(['community', 'get', communityId]))
18554
- .filter(Boolean)
18555
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
18556
- communities = filterByStringComparePartially(communities, 'displayName', params.displayName);
18557
- if (!params.includeDeleted) {
18558
- communities = filterByPropEquality(communities, 'isDeleted', false);
18559
- }
18560
- if (params.categoryId) {
18561
- communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(params.categoryId); });
18562
- }
18563
- if (params.tags) {
18564
- 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); }); });
18724
+ log(`searchCommunities(tmpid: ${timestamp}) > listen`);
18725
+ const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
18726
+ const disposers = searchCommunitiesLiveCollection.startSubscription();
18727
+ const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
18728
+ disposers.push(() => dropFromCache(cacheKey));
18729
+ return () => {
18730
+ log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
18731
+ disposers.forEach(fn => fn());
18732
+ };
18733
+ };
18734
+ /* end_public_function */
18735
+
18736
+ /**
18737
+ * TODO: handle cache receive cache option, and cache policy
18738
+ * TODO: check if querybyIds is supported
18739
+ */
18740
+ class CommunitiesPaginationController extends PaginationController {
18741
+ async getRequest(queryParams, token) {
18742
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18743
+ const options = token ? { token } : { limit };
18744
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
18745
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
18746
+ });
18747
+ return queryResponse;
18748
+ }
18749
+ }
18750
+
18751
+ var EnumCommunityActions;
18752
+ (function (EnumCommunityActions) {
18753
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
18754
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
18755
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
18756
+ })(EnumCommunityActions || (EnumCommunityActions = {}));
18757
+
18758
+ class CommunitiesQueryStreamController extends QueryStreamController {
18759
+ constructor(query, cacheKey, notifyChange, preparePayload) {
18760
+ super(query, cacheKey);
18761
+ this.notifyChange = notifyChange;
18762
+ this.preparePayload = preparePayload;
18763
+ }
18764
+ async saveToMainDB(response) {
18765
+ const processedPayload = await this.preparePayload(response);
18766
+ const client = getActiveClient();
18767
+ const cachedAt = client.cache && Date.now();
18768
+ if (client.cache) {
18769
+ ingestInCache(processedPayload, { cachedAt });
18565
18770
  }
18566
- if (params.membership && userId) {
18567
- communities = filterByCommunityMembership(communities, params.membership, userId);
18771
+ }
18772
+ appendToQueryStream(response, direction, refresh = false) {
18773
+ var _a, _b;
18774
+ if (refresh) {
18775
+ pushToCache(this.cacheKey, {
18776
+ data: response.communities.map(getResolver('community')),
18777
+ });
18568
18778
  }
18569
- const sortBy = params.sortBy || 'lastCreated';
18570
- if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
18571
- communities = communities.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
18779
+ else {
18780
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18781
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18782
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
18572
18783
  }
18573
- /*
18574
- * The server returns communities with empty | null displayName's first before
18575
- * returning sorted list of communities with displayNames
18576
- *
18577
- * This section needs to be updated as displayNames can be null as well
18578
- */
18579
- if (sortBy === 'displayName') {
18580
- communities = communities
18581
- // this needs to be aligned with the backend data type
18582
- .map(c => (c.displayName ? c : Object.assign(Object.assign({}, c), { displayName: '' })))
18583
- // @ts-ignore
18584
- .sort(sortByDisplayName);
18585
- }
18586
- callback({
18587
- onNextPage: onFetch,
18588
- data: communities,
18589
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
18590
- loading: data.loading,
18591
- error: data.error,
18592
- });
18593
- };
18594
- const realtimeRouter = (_) => (community) => {
18784
+ }
18785
+ reactor(action) {
18786
+ return (community) => {
18787
+ var _a;
18788
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18789
+ if (!collection)
18790
+ return;
18791
+ if (this.query.displayName && action === EnumCommunityActions.OnCommunityCreated) {
18792
+ return;
18793
+ }
18794
+ /*
18795
+ * Simply update collection and let responder decide what to do with data
18796
+ */
18797
+ collection.data = [...new Set([community.communityId, ...collection.data])];
18798
+ pushToCache(this.cacheKey, collection);
18799
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
18800
+ };
18801
+ }
18802
+ subscribeRTE(createSubscriber) {
18803
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
18804
+ }
18805
+ }
18806
+
18807
+ /* eslint-disable no-use-before-define */
18808
+ class CommunityLiveCollectionController extends LiveCollectionController {
18809
+ constructor(query, callback) {
18810
+ const queryStreamId = hash__default["default"](query);
18811
+ const cacheKey = ['community', 'collection', queryStreamId];
18812
+ const paginationController = new CommunitiesPaginationController(query);
18813
+ super(paginationController, queryStreamId, cacheKey, callback);
18814
+ this.query = query;
18815
+ this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
18816
+ this.callback = callback.bind(this);
18817
+ this.loadPage({ initial: true });
18818
+ }
18819
+ setup() {
18595
18820
  var _a;
18596
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18821
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18822
+ if (!collection) {
18823
+ pushToCache(this.cacheKey, {
18824
+ data: [],
18825
+ params: {},
18826
+ });
18827
+ }
18828
+ }
18829
+ async persistModel(queryPayload) {
18830
+ await this.queryStreamController.saveToMainDB(queryPayload);
18831
+ }
18832
+ persistQueryStream({ response, direction, refresh, }) {
18833
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
18834
+ }
18835
+ startSubscription() {
18836
+ return this.queryStreamController.subscribeRTE([
18837
+ { fn: onCommunityCreated, action: EnumCommunityActions.OnCommunityCreated },
18838
+ { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
18839
+ { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
18840
+ ]);
18841
+ }
18842
+ notifyChange({ origin, loading, error }) {
18843
+ var _a, _b;
18844
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18597
18845
  if (!collection)
18598
18846
  return;
18599
- /*
18600
- * Simply update collection and let responder decide what to do with data
18601
- */
18602
- collection.data = [...new Set([community.communityId, ...collection.data])];
18603
- pushToCache(cacheKey, collection);
18604
- responder(collection);
18605
- };
18606
- const onFetch = (initial = false) => {
18607
- var _a, _b;
18608
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18609
- const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18610
- if (!initial && communities.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
18847
+ const data = this.applyFilter((_b = collection.data
18848
+ .map(id => pullFromCache(['community', 'get', id]))
18849
+ .filter(Boolean)
18850
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
18851
+ if (!this.shouldNotify(data) && origin === 'event')
18611
18852
  return;
18612
- 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 }));
18613
- runQuery(query, ({ data: result, error, loading, paging }) => {
18614
- const data = {
18615
- loading,
18616
- error,
18617
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
18618
- data: communities,
18619
- };
18620
- if (result) {
18621
- data.data = initial
18622
- ? result.map(getResolver('community'))
18623
- : [...new Set([...communities, ...result.map(getResolver('community'))])];
18624
- }
18625
- pushToCache(cacheKey, data);
18626
- responder(data);
18627
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
18628
- };
18629
- disposers.push(onCommunityCreated(realtimeRouter()), onCommunityDeleted(realtimeRouter()), onCommunityUpdated(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityLeft(realtimeRouter()), onCommunityUserChanged(realtimeRouter()));
18630
- onFetch(true);
18853
+ this.callback({
18854
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
18855
+ data,
18856
+ hasNextPage: !!this.paginationController.getNextToken(),
18857
+ loading,
18858
+ error,
18859
+ });
18860
+ }
18861
+ applyFilter(data) {
18862
+ const { userId } = getActiveClient();
18863
+ let communities = data;
18864
+ if (this.query.includeDeleted) {
18865
+ communities = filterByPropEquality(communities, 'isDeleted', false);
18866
+ }
18867
+ if (this.query.categoryId) {
18868
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
18869
+ }
18870
+ if (this.query.tags) {
18871
+ 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); }); });
18872
+ }
18873
+ if (this.query.membership && userId) {
18874
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
18875
+ }
18876
+ if (!this.query.displayName) {
18877
+ const sortFn = (() => {
18878
+ switch (this.query.sortBy) {
18879
+ case 'firstCreated':
18880
+ return sortByFirstCreated;
18881
+ case 'lastCreated':
18882
+ return sortByLastCreated;
18883
+ case 'displayName':
18884
+ return sortByDisplayName;
18885
+ default:
18886
+ return sortByLastCreated;
18887
+ }
18888
+ })();
18889
+ communities = communities.sort(sortFn);
18890
+ }
18891
+ return communities;
18892
+ }
18893
+ }
18894
+
18895
+ /* begin_public_function
18896
+ id: community.query
18897
+ */
18898
+ /**
18899
+ * ```js
18900
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
18901
+ *
18902
+ * let communities = []
18903
+ * const unsub = CommunityRepository.getCommunities({
18904
+ * displayName: Amity.Community['displayName'],
18905
+ * }, response => merge(communities, response.data))
18906
+ * ```
18907
+ *
18908
+ * Observe all mutations on a list of {@link Amity.Community}s
18909
+ *
18910
+ * @param params for querying communities
18911
+ * @param callback the function to call when new data are available
18912
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
18913
+ *
18914
+ * @category Community Live Collection
18915
+ */
18916
+ const getCommunities = (params, callback, config) => {
18917
+ const { log, cache } = getActiveClient();
18918
+ if (!cache) {
18919
+ console.log(ENABLE_CACHE_MESSAGE);
18920
+ }
18921
+ const timestamp = Date.now();
18922
+ log(`getCommunities(tmpid: ${timestamp}) > listen`);
18923
+ const communitiesLiveCollection = new CommunityLiveCollectionController(params, callback);
18924
+ const disposers = communitiesLiveCollection.startSubscription();
18925
+ const cacheKey = communitiesLiveCollection.getCacheKey();
18631
18926
  disposers.push(() => dropFromCache(cacheKey));
18632
18927
  return () => {
18633
18928
  log(`getCommunities(tmpid: ${timestamp}) > dispose`);
@@ -19156,208 +19451,444 @@ const removeMembers = async (communityId, userIds) => {
19156
19451
  /* end_public_function */
19157
19452
 
19158
19453
  /**
19159
- * ```js
19160
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
19161
- * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
19162
- * ```
19163
- *
19164
- * Queries a paginable list of {@link Amity.CommunityUser} objects
19165
- *
19166
- * @param query The query parameters
19167
- * @returns A page of {@link Amity.CommunityUser} objects
19168
- *
19169
- * @category Community API
19170
- * @async
19171
- * */
19172
- const queryCommunityMembers = async (query) => {
19173
- const client = getActiveClient();
19174
- client.log('community/queryCommunityMembers', query);
19175
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit } = _a, params = __rest(_a, ["page", "limit"]);
19176
- const options = (() => {
19177
- if (page)
19178
- return { token: page };
19179
- if (limit)
19180
- return { limit };
19181
- return undefined;
19182
- })();
19183
- const { data: queryPayload } = await client.http.get(`/api/v3/communities/${params.communityId}/users`, {
19184
- params: Object.assign(Object.assign({}, params), { options }),
19185
- });
19186
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
19187
- const preparedPayload = prepareMembershipPayload(payload, 'communityUsers');
19188
- const { communityUsers } = preparedPayload;
19189
- const cachedAt = client.cache && Date.now();
19190
- if (client.cache) {
19191
- ingestInCache(preparedPayload, { cachedAt });
19192
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
19193
- pushToCache(cacheKey, {
19194
- communityUsers: communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19195
- paging,
19454
+ * TODO: handle cache receive cache option, and cache policy
19455
+ * TODO: check if querybyIds is supported
19456
+ */
19457
+ class CommunityMembersPaginationController extends PaginationController {
19458
+ async getRequest(queryParams, token) {
19459
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
19460
+ const options = token ? { token } : { limit };
19461
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
19462
+ params: Object.assign(Object.assign({}, params), { options }),
19196
19463
  });
19464
+ return queryResponse;
19197
19465
  }
19198
- return { data: communityUsers, cachedAt, paging };
19199
- };
19200
- /**
19201
- * ```js
19202
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
19203
- * const communityMembers = await queryCommunityMembers(query)
19204
- * ```
19205
- *
19206
- * Queries a paginable list of {@link Amity.InternalPost} objects from cache
19207
- *
19208
- * @param query The query parameters
19209
- * @returns posts
19210
- *
19211
- * @category Post API
19212
- */
19213
- queryCommunityMembers.locally = (query) => {
19214
- var _a, _b;
19215
- const client = getActiveClient();
19216
- client.log('community/queryCommunityMembers', query);
19217
- if (!client.cache)
19218
- return;
19219
- const _c = query !== null && query !== void 0 ? query : {}, { page, limit } = _c, params = __rest(_c, ["page", "limit"]);
19220
- const options = (() => {
19221
- if (page)
19222
- return { token: page };
19223
- if (limit)
19224
- return { limit };
19225
- return undefined;
19226
- })();
19227
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
19228
- const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
19229
- if (!(data === null || data === void 0 ? void 0 : data.communityUsers.length))
19230
- return;
19231
- const communityUsers = data.communityUsers
19232
- .map(key => pullFromCache(['communityUsers', 'get', key]))
19233
- .filter(Boolean)
19234
- .map(({ data }) => data);
19235
- const { paging } = data;
19236
- return communityUsers.length === ((_b = data === null || data === void 0 ? void 0 : data.communityUsers) === null || _b === void 0 ? void 0 : _b.length)
19237
- ? { data: communityUsers, cachedAt, paging }
19238
- : undefined;
19239
- };
19466
+ }
19240
19467
 
19241
- /*
19242
- * Exported for testing
19243
- * @hidden
19244
- */
19245
- const applyFilter = (data, params) => {
19246
- let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
19247
- if (params.memberships) {
19248
- communityMembers = communityMembers.filter(({ communityMembership }) => {
19249
- const membership = params.memberships;
19250
- return membership.includes(communityMembership);
19251
- });
19468
+ var EnumCommunityMemberActions$1;
19469
+ (function (EnumCommunityMemberActions) {
19470
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
19471
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
19472
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
19473
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
19474
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
19475
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
19476
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
19477
+ })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
19478
+
19479
+ class CommunityMembersQueryStreamController extends QueryStreamController {
19480
+ constructor(query, cacheKey, notifyChange, preparePayload) {
19481
+ super(query, cacheKey);
19482
+ this.notifyChange = notifyChange;
19483
+ this.preparePayload = preparePayload;
19252
19484
  }
19253
- if (params.search) {
19254
- communityMembers = filterBySearchTerm(communityMembers, params.search);
19485
+ async saveToMainDB(response) {
19486
+ const processedPayload = await this.preparePayload(response);
19487
+ const client = getActiveClient();
19488
+ const cachedAt = client.cache && Date.now();
19489
+ if (client.cache) {
19490
+ ingestInCache(processedPayload, { cachedAt });
19491
+ }
19255
19492
  }
19256
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
19257
- communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
19258
- return communityMembers;
19259
- };
19260
- /* begin_public_function
19261
- id: community.membership.query
19262
- */
19263
- /**
19264
- * ```js
19265
- * import { getMembers } from '@amityco/ts-sdk-react-native'
19266
- *
19267
- * let communityMembers = []
19268
- * const unsub = getMembers({
19269
- * communityId: Amity.Community['communityId'],
19270
- * }, response => merge(communityMembers, response.data))
19271
- * ```
19272
- *
19273
- * Observe all mutations on a list of {@link Amity.CommunityUser}s
19274
- *
19275
- * @param params for querying community users
19276
- * @param callback the function to call when new data are available
19277
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
19278
- *
19279
- * @category Community Live Collection
19280
- */
19281
- const getMembers = (params, callback, config) => {
19282
- const { log, cache } = getActiveClient();
19283
- if (!cache) {
19284
- console.log(ENABLE_CACHE_MESSAGE);
19493
+ appendToQueryStream(response, direction, refresh = false) {
19494
+ var _a, _b;
19495
+ if (refresh) {
19496
+ pushToCache(this.cacheKey, {
19497
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19498
+ });
19499
+ }
19500
+ else {
19501
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19502
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19503
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
19504
+ ...new Set([
19505
+ ...communityUsers,
19506
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19507
+ ]),
19508
+ ] }));
19509
+ }
19285
19510
  }
19286
- const timestamp = Date.now();
19287
- log(`getMembers(tmpid: ${timestamp}) > listen`);
19288
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
19289
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
19290
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
19291
- const disposers = [];
19292
- const cacheKey = ['communityUsers', 'collection', queryParams];
19293
- const cacheByCommunityIdKey = [
19294
- 'communityUsers',
19295
- 'collection',
19296
- { communityId: params.communityId },
19297
- ];
19298
- const responder = (data, isEventModel = false) => {
19511
+ reactor(action) {
19512
+ return (community, communityMembers) => {
19513
+ var _a;
19514
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19515
+ if (!collection)
19516
+ return;
19517
+ if (action === EnumCommunityMemberActions$1.OnCommunityUserRoleAdded &&
19518
+ this.query.sortBy === 'displayName') {
19519
+ return;
19520
+ }
19521
+ communityMembers.forEach(communityMember => {
19522
+ const communityMemberCacheId = getResolver('communityUsers')({
19523
+ communityId: this.query.communityId,
19524
+ userId: communityMember.userId,
19525
+ });
19526
+ if (communityMember.communityMembership === 'none') {
19527
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
19528
+ }
19529
+ else if (!collection.data.includes(communityMemberCacheId)) {
19530
+ collection.data = [communityMemberCacheId, ...collection.data];
19531
+ }
19532
+ });
19533
+ pushToCache(this.cacheKey, collection);
19534
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
19535
+ };
19536
+ }
19537
+ subscribeRTE(createSubscriber) {
19538
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
19539
+ }
19540
+ }
19541
+
19542
+ /* eslint-disable no-use-before-define */
19543
+ class CommunityMembersLiveCollectionController extends LiveCollectionController {
19544
+ constructor(query, callback) {
19545
+ const queryStreamId = hash__default["default"](query);
19546
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
19547
+ const paginationController = new CommunityMembersPaginationController(query);
19548
+ super(paginationController, queryStreamId, cacheKey, callback);
19549
+ this.query = query;
19550
+ this.queryStreamController = new CommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
19551
+ this.callback = callback.bind(this);
19552
+ this.loadPage({ initial: true });
19553
+ }
19554
+ setup() {
19555
+ var _a;
19556
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19557
+ if (!collection) {
19558
+ pushToCache(this.cacheKey, {
19559
+ data: [],
19560
+ params: {},
19561
+ });
19562
+ }
19563
+ }
19564
+ async persistModel(queryPayload) {
19565
+ await this.queryStreamController.saveToMainDB(queryPayload);
19566
+ }
19567
+ persistQueryStream({ response, direction, refresh, }) {
19568
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
19569
+ }
19570
+ startSubscription() {
19571
+ return this.queryStreamController.subscribeRTE([
19572
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
19573
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
19574
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions$1.OnCommunityUserBanned },
19575
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnCommunityUserChanged },
19576
+ { fn: onCommunityUserRoleAdded, action: EnumCommunityMemberActions$1.OnCommunityUserRoleAdded },
19577
+ {
19578
+ fn: onCommunityUserRoleRemoved,
19579
+ action: EnumCommunityMemberActions$1.OnCommunityUserRoleRemoved,
19580
+ },
19581
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions$1.OnCommunityUserUnbanned },
19582
+ ]);
19583
+ }
19584
+ notifyChange({ origin, loading, error }) {
19299
19585
  var _a, _b;
19300
- const communityMembers = (_a = data.data
19586
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19587
+ if (!collection)
19588
+ return;
19589
+ const data = this.applyFilter((_b = collection.data
19301
19590
  .map(id => pullFromCache(['communityUsers', 'get', id]))
19302
- .filter(Boolean)
19303
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
19304
- callback({
19305
- onNextPage: onFetch,
19306
- data: isEventModel ? applyFilter(communityMembers, params) : communityMembers,
19307
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
19308
- loading: data.loading,
19309
- error: data.error,
19591
+ .filter(isNonNullable)
19592
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
19593
+ if (!this.shouldNotify(data) && origin === 'event')
19594
+ return;
19595
+ this.callback({
19596
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
19597
+ data,
19598
+ hasNextPage: !!this.paginationController.getNextToken(),
19599
+ loading,
19600
+ error,
19310
19601
  });
19602
+ }
19603
+ applyFilter(data) {
19604
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
19605
+ if (this.query.memberships) {
19606
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
19607
+ const memberships = this.query.memberships || [];
19608
+ return memberships.includes(communityMembership);
19609
+ });
19610
+ }
19611
+ if (this.query.search) {
19612
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
19613
+ }
19614
+ switch (this.query.sortBy) {
19615
+ case 'firstCreated':
19616
+ communityMembers = communityMembers.sort(sortByFirstCreated);
19617
+ break;
19618
+ case 'displayName':
19619
+ communityMembers = communityMembers.sort((a, b) => {
19620
+ var _a, _b, _c, _d;
19621
+ 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)) {
19622
+ 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);
19623
+ }
19624
+ return 0;
19625
+ });
19626
+ break;
19627
+ case 'lastCreated':
19628
+ default:
19629
+ communityMembers = communityMembers.sort(sortByLastCreated);
19630
+ break;
19631
+ }
19632
+ return communityMembers;
19633
+ }
19634
+ }
19635
+
19636
+ /*
19637
+ * Exported for testing
19638
+ * @hidden
19639
+ */
19640
+ const applyFilter = (data, params) => {
19641
+ let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
19642
+ if (params.memberships) {
19643
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
19644
+ const membership = params.memberships;
19645
+ return membership.includes(communityMembership);
19646
+ });
19647
+ }
19648
+ if (params.search) {
19649
+ communityMembers = filterBySearchTerm(communityMembers, params.search);
19650
+ }
19651
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
19652
+ communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
19653
+ return communityMembers;
19654
+ };
19655
+ /* begin_public_function
19656
+ id: community.membership.query
19657
+ */
19658
+ /**
19659
+ * ```js
19660
+ * import { getMembers } from '@amityco/ts-sdk-react-native'
19661
+ *
19662
+ * let communityMembers = []
19663
+ * const unsub = getMembers({
19664
+ * communityId: Amity.Community['communityId'],
19665
+ * }, response => merge(communityMembers, response.data))
19666
+ * ```
19667
+ *
19668
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
19669
+ *
19670
+ * @param params for querying community users
19671
+ * @param callback the function to call when new data are available
19672
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
19673
+ *
19674
+ * @category Community Live Collection
19675
+ */
19676
+ const getMembers = (params, callback, config) => {
19677
+ const { log, cache } = getActiveClient();
19678
+ if (!cache) {
19679
+ console.log(ENABLE_CACHE_MESSAGE);
19680
+ }
19681
+ const timestamp = Date.now();
19682
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
19683
+ const communityMemberLiveCollection = new CommunityMembersLiveCollectionController(params, resp => {
19684
+ console.log('resp', resp);
19685
+ callback(resp);
19686
+ });
19687
+ const disposers = communityMemberLiveCollection.startSubscription();
19688
+ const cacheKey = communityMemberLiveCollection.getCacheKey();
19689
+ disposers.push(() => {
19690
+ dropFromCache(cacheKey);
19691
+ });
19692
+ return () => {
19693
+ log(`getMembers(tmpid: ${timestamp}) > dispose`);
19694
+ disposers.forEach(fn => fn());
19311
19695
  };
19312
- const realtimeRouter = (_) => (_, communityMembers) => {
19313
- var _a;
19314
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19315
- if (!collection) {
19316
- return;
19696
+ };
19697
+ /* end_public_function */
19698
+
19699
+ /**
19700
+ * TODO: handle cache receive cache option, and cache policy
19701
+ * TODO: check if querybyIds is supported
19702
+ */
19703
+ class SearchCommunityMembersPaginationController extends PaginationController {
19704
+ async getRequest(queryParams, token) {
19705
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
19706
+ const options = token ? { token } : { limit };
19707
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
19708
+ params: Object.assign(Object.assign({}, params), { options }),
19709
+ });
19710
+ return queryResponse;
19711
+ }
19712
+ }
19713
+
19714
+ class SearchCommunityMembersQueryStreamController extends QueryStreamController {
19715
+ constructor(query, cacheKey, notifyChange, preparePayload) {
19716
+ super(query, cacheKey);
19717
+ this.notifyChange = notifyChange;
19718
+ this.preparePayload = preparePayload;
19719
+ }
19720
+ async saveToMainDB(response) {
19721
+ const processedPayload = await this.preparePayload(response);
19722
+ const client = getActiveClient();
19723
+ const cachedAt = client.cache && Date.now();
19724
+ if (client.cache) {
19725
+ ingestInCache(processedPayload, { cachedAt });
19726
+ }
19727
+ }
19728
+ appendToQueryStream(response, direction, refresh = false) {
19729
+ var _a, _b;
19730
+ if (refresh) {
19731
+ pushToCache(this.cacheKey, {
19732
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19733
+ });
19734
+ }
19735
+ else {
19736
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19737
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19738
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
19739
+ ...new Set([
19740
+ ...communityUsers,
19741
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19742
+ ]),
19743
+ ] }));
19317
19744
  }
19318
- const communityMemberCacheIds = communityMembers
19319
- .map(communityMember => {
19320
- if (params.communityId !== communityMember.communityId) {
19745
+ }
19746
+ reactor(action) {
19747
+ return (community, communityMembers) => {
19748
+ var _a;
19749
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19750
+ if (!collection)
19321
19751
  return;
19322
- }
19323
- const communityMemberCacheId = getResolver('communityUsers')({
19324
- communityId: params.communityId,
19325
- userId: communityMember.userId,
19752
+ communityMembers.forEach(communityMember => {
19753
+ const communityMemberCacheId = getResolver('communityUsers')({
19754
+ communityId: this.query.communityId,
19755
+ userId: communityMember.userId,
19756
+ });
19757
+ if (communityMember.communityMembership === 'none') {
19758
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
19759
+ }
19326
19760
  });
19327
- return communityMemberCacheId;
19328
- })
19329
- .filter(isNonNullable);
19330
- collection.data = [...new Set([...communityMemberCacheIds, ...collection.data])];
19331
- pushToCache(cacheKey, collection);
19332
- pushToCache(cacheByCommunityIdKey, collection);
19333
- responder(collection, true);
19334
- };
19335
- const onFetch = (initial = false) => {
19761
+ pushToCache(this.cacheKey, collection);
19762
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
19763
+ };
19764
+ }
19765
+ subscribeRTE(createSubscriber) {
19766
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
19767
+ }
19768
+ }
19769
+
19770
+ var EnumCommunityMemberActions;
19771
+ (function (EnumCommunityMemberActions) {
19772
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
19773
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
19774
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
19775
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
19776
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
19777
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
19778
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
19779
+ })(EnumCommunityMemberActions || (EnumCommunityMemberActions = {}));
19780
+
19781
+ /* eslint-disable no-use-before-define */
19782
+ class SearchCommunityMembersLiveCollectionController extends LiveCollectionController {
19783
+ constructor(query, callback) {
19784
+ const queryStreamId = hash__default["default"](query);
19785
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
19786
+ const paginationController = new SearchCommunityMembersPaginationController(query);
19787
+ super(paginationController, queryStreamId, cacheKey, callback);
19788
+ this.query = query;
19789
+ this.queryStreamController = new SearchCommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
19790
+ this.callback = callback.bind(this);
19791
+ this.loadPage({ initial: true });
19792
+ }
19793
+ setup() {
19794
+ var _a;
19795
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19796
+ if (!collection) {
19797
+ pushToCache(this.cacheKey, {
19798
+ data: [],
19799
+ params: {},
19800
+ });
19801
+ }
19802
+ }
19803
+ async persistModel(queryPayload) {
19804
+ await this.queryStreamController.saveToMainDB(queryPayload);
19805
+ }
19806
+ persistQueryStream({ response, direction, refresh, }) {
19807
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
19808
+ }
19809
+ startSubscription() {
19810
+ return this.queryStreamController.subscribeRTE([
19811
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions.OnCommunityJoined },
19812
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
19813
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
19814
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
19815
+ {
19816
+ fn: onCommunityUserRoleRemoved,
19817
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
19818
+ },
19819
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
19820
+ ]);
19821
+ }
19822
+ notifyChange({ origin, loading, error }) {
19336
19823
  var _a, _b;
19337
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19338
- const communityMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19339
- if (!initial && communityMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
19824
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19825
+ if (!collection)
19340
19826
  return;
19341
- 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 }));
19342
- runQuery(query, ({ data: result, error, loading, paging }) => {
19343
- const data = {
19344
- loading,
19345
- error,
19346
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
19347
- data: communityMembers,
19348
- };
19349
- if (result) {
19350
- data.data = [
19351
- ...new Set([...communityMembers, ...result.map(getResolver('communityUsers'))]),
19352
- ];
19353
- }
19354
- pushToCache(cacheKey, data);
19355
- pushToCache(cacheByCommunityIdKey, data);
19356
- responder(data);
19357
- }, queryOptions(policy));
19358
- };
19359
- disposers.push(onCommunityLeft(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityUserBanned(realtimeRouter()), onCommunityUserUnbanned(realtimeRouter()), onCommunityUserChanged(realtimeRouter()), onCommunityUserRoleAdded(realtimeRouter()), onCommunityUserRoleRemoved(realtimeRouter()));
19360
- onFetch(true);
19827
+ const data = this.applyFilter((_b = collection.data
19828
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
19829
+ .filter(isNonNullable)
19830
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
19831
+ if (!this.shouldNotify(data) && origin === 'event')
19832
+ return;
19833
+ this.callback({
19834
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
19835
+ data,
19836
+ hasNextPage: !!this.paginationController.getNextToken(),
19837
+ loading,
19838
+ error,
19839
+ });
19840
+ }
19841
+ applyFilter(data) {
19842
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
19843
+ if (this.query.memberships) {
19844
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
19845
+ const memberships = this.query.memberships || [];
19846
+ return memberships.includes(communityMembership);
19847
+ });
19848
+ }
19849
+ if (this.query.search) {
19850
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
19851
+ }
19852
+ return communityMembers;
19853
+ }
19854
+ }
19855
+
19856
+ /* begin_public_function
19857
+ id: community.membership.query
19858
+ */
19859
+ /**
19860
+ * ```js
19861
+ * import { searchMembers } from '@amityco/ts-sdk-react-native'
19862
+ *
19863
+ * let communityMembers = []
19864
+ * const unsub = searchMembers({
19865
+ * communityId: Amity.Community['communityId'],
19866
+ * }, response => merge(communityMembers, response.data))
19867
+ * ```
19868
+ *
19869
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
19870
+ *
19871
+ * @param params for querying community users
19872
+ * @param callback the function to call when new data are available
19873
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
19874
+ *
19875
+ * @category Community Live Collection
19876
+ */
19877
+ const searchMembers = (params, callback, config) => {
19878
+ const { log, cache } = getActiveClient();
19879
+ if (!cache) {
19880
+ console.log(ENABLE_CACHE_MESSAGE);
19881
+ }
19882
+ const timestamp = Date.now();
19883
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
19884
+ const searchCommunityMemberLiveCollection = new SearchCommunityMembersLiveCollectionController(params, resp => {
19885
+ callback(resp);
19886
+ });
19887
+ const disposers = searchCommunityMemberLiveCollection.startSubscription();
19888
+ const cacheKey = searchCommunityMemberLiveCollection.getCacheKey();
19889
+ disposers.push(() => {
19890
+ dropFromCache(cacheKey);
19891
+ });
19361
19892
  return () => {
19362
19893
  log(`getMembers(tmpid: ${timestamp}) > dispose`);
19363
19894
  disposers.forEach(fn => fn());
@@ -19371,6 +19902,7 @@ var index$9 = /*#__PURE__*/Object.freeze({
19371
19902
  removeMembers: removeMembers,
19372
19903
  applyFilter: applyFilter,
19373
19904
  getMembers: getMembers,
19905
+ searchMembers: searchMembers,
19374
19906
  onCommunityUserAdded: onCommunityUserAdded,
19375
19907
  onCommunityUserRemoved: onCommunityUserRemoved,
19376
19908
  onCommunityUserBanned: onCommunityUserBanned,
@@ -19397,6 +19929,7 @@ var index$8 = /*#__PURE__*/Object.freeze({
19397
19929
  onCommunityUpdated: onCommunityUpdated,
19398
19930
  onCommunityDeleted: onCommunityDeleted,
19399
19931
  observeCommunity: observeCommunity,
19932
+ searchCommunities: searchCommunities,
19400
19933
  getCommunities: getCommunities,
19401
19934
  getCommunity: getCommunity,
19402
19935
  getTrendingCommunities: getTrendingCommunities,
@@ -19983,7 +20516,7 @@ const updatePost = async (postId, patch) => {
19983
20516
  const cachedAt = client.cache && Date.now();
19984
20517
  if (client.cache)
19985
20518
  ingestInCache(data, { cachedAt });
19986
- fireEvent('post.updated', data);
20519
+ fireEvent('local.post.updated', data);
19987
20520
  const { posts } = data;
19988
20521
  return {
19989
20522
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -20020,7 +20553,7 @@ const editPost = async (postId, patch) => {
20020
20553
  const cachedAt = client.cache && Date.now();
20021
20554
  if (client.cache)
20022
20555
  ingestInCache(data, { cachedAt });
20023
- fireEvent('post.updated', data);
20556
+ fireEvent('local.post.updated', data);
20024
20557
  const { posts } = data;
20025
20558
  return {
20026
20559
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -20279,403 +20812,119 @@ const unflagPost = async (postId) => {
20279
20812
  const { data: payload } = await client.http.delete(`/api/v3/posts/${encodeURIComponent(postId)}/unflag`);
20280
20813
  if (client.cache) {
20281
20814
  ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
20282
- }
20283
- fireEvent('post.unflagged', payload);
20284
- return !!payload;
20285
- };
20286
- /* end_public_function */
20287
-
20288
- /* begin_public_function
20289
- id: post.check_flag_by_me
20290
- */
20291
- /**
20292
- * ```js
20293
- * import { PostRepository } from '@amityco/ts-sdk-react-native'
20294
- * const isReported = await PostRepository.isPostFlaggedByMe('post', postId)
20295
- * ```
20296
- *
20297
- * @param postId of the post to check if flagged by current user
20298
- * @returns `true` if the post is flagged by me, `false` if doesn't.
20299
- *
20300
- * @category Post API
20301
- * @async
20302
- * */
20303
- const isPostFlaggedByMe = async (postId) => {
20304
- const client = getActiveClient();
20305
- client.log('post/isPostFlaggedByMe', postId);
20306
- const { data: { result }, } = await client.http.get(`/api/v3/posts/${postId}/isflagbyme`);
20307
- return result;
20308
- };
20309
- /* end_public_function */
20310
-
20311
- /**
20312
- * ```js
20313
- * import { PostRepository } from '@amityco/ts-sdk-react-native'
20314
- *
20315
- * let posts = []
20316
- * const unsub = PostRepository.observePosts({
20317
- * targetType: Amity.PostTargetType,
20318
- * targetId: Amity.InternalPost['targetId'],
20319
- * }, post => merge(posts, post))
20320
- * ```
20321
- *
20322
- * Observe all mutations on a list of {@link Amity.Post} for a given target object
20323
- *
20324
- * @param params
20325
- * @param callback the function to call when new data are available
20326
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
20327
- *
20328
- * @category Post Observer
20329
- */
20330
- const observePosts = (params, callback) => {
20331
- const { log } = getActiveClient();
20332
- const timestamp = Date.now();
20333
- log(`observePosts(tmpid: ${timestamp}) > listen`);
20334
- const disposers = [];
20335
- const router = (post, action) => {
20336
- var _a, _b;
20337
- if (params.targetId !== post.targetId || params.targetType !== post.targetType)
20338
- return;
20339
- if (callback instanceof Function)
20340
- return callback(LinkedObject.post(post));
20341
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, LinkedObject.post(post));
20342
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, LinkedObject.post(post));
20343
- };
20344
- disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')), onPostApproved(post => router(post, 'onApproved')), onPostDeclined(post => router(post, 'onDeclined')), onPostFlagged(post => router(post, 'onFlagged')), onPostUnflagged(post => router(post, 'onUnflagged')), onPostReactionAdded(post => router(post, 'onReactionAdded')), onPostReactionRemoved(post => router(post, 'onReactionRemoved')));
20345
- return () => {
20346
- log(`observePosts(tmpid: ${timestamp}) > dispose`);
20347
- disposers.forEach(fn => fn());
20348
- };
20349
- };
20350
-
20351
- /**
20352
- * ```js
20353
- * import { observePost } from '@amityco/ts-sdk-react-native'
20354
- *
20355
- * let post = {}
20356
- * const dispose = observePost(postId, updated => post = updated)
20357
- * ```
20358
- *
20359
- * Observe all mutations on a given {@link Amity.Post}
20360
- *
20361
- * @param postId the ID of the post to observe
20362
- * @param callback the function to call when new data are available
20363
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the post
20364
- *
20365
- * @category Post Observer
20366
- */
20367
- const observePost = (postId, callback, policy = 'cache_then_server') => {
20368
- const { log } = getActiveClient();
20369
- const timestamp = Date.now();
20370
- log(`observePost(tmpid: ${timestamp}) > listen`);
20371
- // wrapper function to make sure
20372
- const router = (result, action) => {
20373
- var _a, _b;
20374
- if (callback instanceof Function)
20375
- return callback(result);
20376
- if (action !== 'onFetch')
20377
- (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
20378
- (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
20379
- };
20380
- const realtimeRouter = (result, action) => {
20381
- var _a;
20382
- if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
20383
- return;
20384
- router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), action);
20385
- };
20386
- const disposers = [];
20387
- disposers.push(onPostUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onPostDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')), onPostApproved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onApproved')), onPostDeclined(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDeclined')), onPostFlagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onFlagged')), onPostUnflagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUnflagged')), onPostReactionAdded(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionAdded')), onPostReactionRemoved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionRemoved')));
20388
- runQuery(createQuery(getPost$1, postId), result => (result.data || result.error) &&
20389
- router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), 'onFetch'), queryOptions(policy));
20390
- return () => {
20391
- log(`observePosts(tmpid: ${timestamp}) > dispose`);
20392
- disposers.forEach(fn => fn());
20393
- };
20394
- };
20395
-
20396
- /* begin_public_function
20397
- id: post.get
20398
- */
20399
- /**
20400
- * ```js
20401
- * import { PostRepository } from '@amityco/ts-sdk-react-native';
20402
- *
20403
- * let post;
20404
- *
20405
- * const unsub = PostRepository.getPost(postId, response => {
20406
- * post = response.data;
20407
- * });
20408
- * ```
20409
- *
20410
- * Observe all mutation on a given {@link Amity.Post}
20411
- *
20412
- * @param postId the ID of the message to observe
20413
- * @param callback the function to call when new data are available
20414
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
20415
- *
20416
- * @category Post Live Object
20417
- */
20418
- const getPost = (postId, callback) => {
20419
- return liveObject(postId, callback, 'postId', getPost$1, [
20420
- onPostApproved,
20421
- onPostDeclined,
20422
- (callback) => {
20423
- return onPostDeleted((post) => {
20424
- var _a;
20425
- let targetPost = post;
20426
- // check if the deleted post is a child of the target post
20427
- if (post.parentPostId === postId && post.isDeleted) {
20428
- const parentPost = (_a = pullFromCache([
20429
- 'post',
20430
- 'get',
20431
- post.parentPostId,
20432
- ])) === null || _a === void 0 ? void 0 : _a.data;
20433
- if (parentPost) {
20434
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
20435
- pushToCache(['post', 'get', parentPost.postId], parentPost);
20436
- // if the deleted post is a child of the target post, then the target post is the parent post
20437
- targetPost = parentPost;
20438
- }
20439
- }
20440
- callback(targetPost);
20441
- });
20442
- },
20443
- onPostFlagged,
20444
- (callback) => {
20445
- return onPostReactionAdded((post) => {
20446
- callback(LinkedObject.post(post));
20447
- });
20448
- },
20449
- (callback) => {
20450
- return onPostReactionRemoved((post) => {
20451
- callback(LinkedObject.post(post));
20452
- });
20453
- },
20454
- onPostUnflagged,
20455
- onPostUpdated,
20456
- ]);
20815
+ }
20816
+ fireEvent('post.unflagged', payload);
20817
+ return !!payload;
20457
20818
  };
20458
20819
  /* end_public_function */
20459
20820
 
20821
+ /* begin_public_function
20822
+ id: post.check_flag_by_me
20823
+ */
20460
20824
  /**
20461
20825
  * ```js
20462
- * import { queryPosts } from '@amityco/ts-sdk-react-native'
20463
- * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
20826
+ * import { PostRepository } from '@amityco/ts-sdk-react-native'
20827
+ * const isReported = await PostRepository.isPostFlaggedByMe('post', postId)
20464
20828
  * ```
20465
20829
  *
20466
- * Queries a paginable list of {@link Amity.Post} objects
20467
- *
20468
- * @param query The query parameters
20469
- * @returns posts
20830
+ * @param postId of the post to check if flagged by current user
20831
+ * @returns `true` if the post is flagged by me, `false` if doesn't.
20470
20832
  *
20471
20833
  * @category Post API
20472
20834
  * @async
20473
- */
20474
- const queryPosts = async (query) => {
20835
+ * */
20836
+ const isPostFlaggedByMe = async (postId) => {
20475
20837
  const client = getActiveClient();
20476
- client.log('post/queryPosts', query);
20477
- const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
20478
- const { dataTypes, matchingOnlyParentPost } = params;
20479
- const options = (() => {
20480
- if (page)
20481
- return { token: page };
20482
- if (limit)
20483
- return { limit };
20484
- return undefined;
20485
- })();
20486
- // API-FIX: parameters should be querystring. (1)
20487
- // API-FIX: backend should answer Amity.Response (2)
20488
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
20489
- const { data } = await client.http.get(`/api/v4/posts`, {
20490
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
20491
- /*
20492
- * when creating post like image, file, video BE will create 2 posts
20493
- * 1. parent post to store text with dataType=text
20494
- * 2. child post to store dataTypes post data
20495
- *
20496
- * By default, BE queries only parent post
20497
- */
20498
- matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
20499
- });
20500
- // API-FIX: backend should answer Amity.Response (2)
20501
- // const { paging, posts } = unwrapPayload(data)
20502
- // unpacking
20503
- const { paging } = data, payload = __rest(data, ["paging"]);
20504
- const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
20505
- const { posts } = payload;
20506
- const cachedAt = client.cache && Date.now();
20507
- if (client.cache) {
20508
- ingestInCache(paperedPayload, { cachedAt });
20509
- const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
20510
- pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
20511
- }
20512
- return { data: posts.map(LinkedObject.post), cachedAt, paging };
20513
- };
20838
+ client.log('post/isPostFlaggedByMe', postId);
20839
+ const { data: { result }, } = await client.http.get(`/api/v3/posts/${postId}/isflagbyme`);
20840
+ return result;
20841
+ };
20842
+ /* end_public_function */
20514
20843
 
20515
- /* begin_public_function
20516
- id: post.query
20517
- */
20518
20844
  /**
20519
20845
  * ```js
20520
20846
  * import { PostRepository } from '@amityco/ts-sdk-react-native'
20521
20847
  *
20522
20848
  * let posts = []
20523
- * const unsub = PostRepository.getPosts({
20849
+ * const unsub = PostRepository.observePosts({
20524
20850
  * targetType: Amity.PostTargetType,
20525
- * targetId: Amity.Post['targetId'],
20526
- * }, response => merge(posts, response.data))
20851
+ * targetId: Amity.InternalPost['targetId'],
20852
+ * }, post => merge(posts, post))
20527
20853
  * ```
20528
20854
  *
20529
20855
  * Observe all mutations on a list of {@link Amity.Post} for a given target object
20530
20856
  *
20531
- * @param params.targetType the type of the target
20532
- * @param params.targetId the ID of the target
20857
+ * @param params
20533
20858
  * @param callback the function to call when new data are available
20534
- * @param config
20535
20859
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
20536
20860
  *
20537
- * @category Posts Live Collection
20861
+ * @category Post Observer
20538
20862
  */
20539
- const getPosts = (params, callback, config) => {
20540
- const { log, cache } = getActiveClient();
20541
- if (!cache) {
20542
- console.log(ENABLE_CACHE_MESSAGE);
20543
- }
20863
+ const observePosts = (params, callback) => {
20864
+ const { log } = getActiveClient();
20544
20865
  const timestamp = Date.now();
20545
- log(`getPosts(tmpid: ${timestamp}) > listen`);
20546
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
20547
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
20548
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
20866
+ log(`observePosts(tmpid: ${timestamp}) > listen`);
20549
20867
  const disposers = [];
20550
- const cacheKey = [
20551
- 'post',
20552
- 'collection',
20553
- { targetId: params.targetId, targetType: params.targetType },
20554
- ];
20555
- const responder = (data) => {
20556
- var _a, _b, _c;
20557
- let posts = (_a = data.data
20558
- .map(postId => pullFromCache(['post', 'get', postId]))
20559
- .filter(Boolean)
20560
- .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
20561
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
20562
- posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
20563
- if (!params.includeDeleted) {
20564
- posts = filterByPropEquality(posts, 'isDeleted', false);
20565
- }
20566
- if (params.tags) {
20567
- posts = posts.filter(p => { var _a; return (_a = p.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); }); });
20568
- }
20569
- if (params.targetType === 'community' && params.feedType) {
20570
- posts = filterByFeedType(posts, params.feedType);
20571
- }
20572
- if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
20573
- posts = filterByPostDataTypes(posts, params.dataTypes);
20574
- }
20575
- callback({
20576
- onNextPage: onFetch,
20577
- data: posts,
20578
- hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
20579
- loading: data.loading,
20580
- error: data.error,
20581
- });
20582
- };
20583
- const realtimeRouter = (action) => (post) => {
20868
+ const router = (post, action) => {
20584
20869
  var _a, _b;
20585
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
20586
- if (!collection)
20587
- return;
20588
- if (post.parentPostId && post.isDeleted) {
20589
- const parentPost = (_b = pullFromCache([
20590
- 'post',
20591
- 'get',
20592
- post.parentPostId,
20593
- ])) === null || _b === void 0 ? void 0 : _b.data;
20594
- if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
20595
- return;
20596
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
20597
- pushToCache(['post', 'get', parentPost.postId], parentPost);
20598
- }
20599
- else {
20600
- if (params.targetId !== post.targetId)
20601
- return;
20602
- if (params.targetType !== post.targetType)
20603
- return;
20604
- }
20605
- /*
20606
- * This is not ideal, but currently this is the only way to update the
20607
- * collection on post declined
20608
- */
20609
- if (action === 'onDeclined') {
20610
- collection.data = collection.data.filter(postId => postId !== post.postId);
20611
- }
20612
- else {
20613
- collection.data = [...new Set([post.postId, ...collection.data])];
20614
- }
20615
- pushToCache(cacheKey, collection);
20616
- responder(collection);
20617
- };
20618
- const onFetch = (initial = false) => {
20619
- var _a, _b, _c;
20620
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
20621
- const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
20622
- if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
20870
+ if (params.targetId !== post.targetId || params.targetType !== post.targetType)
20623
20871
  return;
20624
- const query = createQuery(queryPosts, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
20625
- runQuery(query, ({ data: result, error, loading, paging }) => {
20626
- const data = {
20627
- loading,
20628
- error,
20629
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
20630
- data: posts,
20631
- };
20632
- if (result) {
20633
- data.data = initial
20634
- ? result.map(getResolver('post'))
20635
- : [...new Set([...posts, ...result.map(getResolver('post'))])];
20636
- }
20637
- pushToCache(cacheKey, data);
20638
- responder(data);
20639
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
20872
+ if (callback instanceof Function)
20873
+ return callback(LinkedObject.post(post));
20874
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, LinkedObject.post(post));
20875
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, LinkedObject.post(post));
20640
20876
  };
20641
- disposers.push(onPostCreated(realtimeRouter('onCreate')), onPostApproved(realtimeRouter('onApproved')), onPostDeclined(realtimeRouter('onDeclined')), onPostDeleted(realtimeRouter('onDelete')), onPostUpdated(realtimeRouter('onUpdate')), onPostFlagged(realtimeRouter('onFlagged')), onPostUnflagged(realtimeRouter('onUnflagged')), onPostReactionAdded(realtimeRouter('onReactionAdded')), onPostReactionRemoved(realtimeRouter('onReactionRemoved')));
20642
- onFetch(true);
20643
- disposers.push(() => dropFromCache(cacheKey));
20877
+ disposers.push(onPostCreated(post => router(post, 'onCreate')), onPostUpdated(post => router(post, 'onUpdate')), onPostDeleted(post => router(post, 'onDelete')), onPostApproved(post => router(post, 'onApproved')), onPostDeclined(post => router(post, 'onDeclined')), onPostFlagged(post => router(post, 'onFlagged')), onPostUnflagged(post => router(post, 'onUnflagged')), onPostReactionAdded(post => router(post, 'onReactionAdded')), onPostReactionRemoved(post => router(post, 'onReactionRemoved')));
20644
20878
  return () => {
20645
- log(`getPosts(tmpid: ${timestamp}) > dispose`);
20879
+ log(`observePosts(tmpid: ${timestamp}) > dispose`);
20646
20880
  disposers.forEach(fn => fn());
20647
20881
  };
20648
- };
20649
- /* end_public_function */
20882
+ };
20650
20883
 
20651
- var index$5 = /*#__PURE__*/Object.freeze({
20652
- __proto__: null,
20653
- getPostByIds: getPostByIds,
20654
- createPost: createPost,
20655
- updatePost: updatePost,
20656
- editPost: editPost,
20657
- deletePost: deletePost,
20658
- softDeletePost: softDeletePost,
20659
- hardDeletePost: hardDeletePost,
20660
- approvePost: approvePost,
20661
- declinePost: declinePost,
20662
- flagPost: flagPost,
20663
- unflagPost: unflagPost,
20664
- isPostFlaggedByMe: isPostFlaggedByMe,
20665
- onPostCreated: onPostCreated,
20666
- onPostUpdated: onPostUpdated,
20667
- onPostDeleted: onPostDeleted,
20668
- onPostApproved: onPostApproved,
20669
- onPostDeclined: onPostDeclined,
20670
- onPostFlagged: onPostFlagged,
20671
- onPostUnflagged: onPostUnflagged,
20672
- onPostReactionAdded: onPostReactionAdded,
20673
- onPostReactionRemoved: onPostReactionRemoved,
20674
- observePosts: observePosts,
20675
- observePost: observePost,
20676
- getPost: getPost,
20677
- getPosts: getPosts
20678
- });
20884
+ /**
20885
+ * ```js
20886
+ * import { observePost } from '@amityco/ts-sdk-react-native'
20887
+ *
20888
+ * let post = {}
20889
+ * const dispose = observePost(postId, updated => post = updated)
20890
+ * ```
20891
+ *
20892
+ * Observe all mutations on a given {@link Amity.Post}
20893
+ *
20894
+ * @param postId the ID of the post to observe
20895
+ * @param callback the function to call when new data are available
20896
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the post
20897
+ *
20898
+ * @category Post Observer
20899
+ */
20900
+ const observePost = (postId, callback, policy = 'cache_then_server') => {
20901
+ const { log } = getActiveClient();
20902
+ const timestamp = Date.now();
20903
+ log(`observePost(tmpid: ${timestamp}) > listen`);
20904
+ // wrapper function to make sure
20905
+ const router = (result, action) => {
20906
+ var _a, _b;
20907
+ if (callback instanceof Function)
20908
+ return callback(result);
20909
+ if (action !== 'onFetch')
20910
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
20911
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
20912
+ };
20913
+ const realtimeRouter = (result, action) => {
20914
+ var _a;
20915
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.postId) !== postId)
20916
+ return;
20917
+ router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), action);
20918
+ };
20919
+ const disposers = [];
20920
+ disposers.push(onPostUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onPostDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')), onPostApproved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onApproved')), onPostDeclined(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDeclined')), onPostFlagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onFlagged')), onPostUnflagged(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUnflagged')), onPostReactionAdded(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionAdded')), onPostReactionRemoved(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onReactionRemoved')));
20921
+ runQuery(createQuery(getPost$1, postId), result => (result.data || result.error) &&
20922
+ router(Object.assign(Object.assign({}, result), { data: result.data && LinkedObject.post(result.data) }), 'onFetch'), queryOptions(policy));
20923
+ return () => {
20924
+ log(`observePosts(tmpid: ${timestamp}) > dispose`);
20925
+ disposers.forEach(fn => fn());
20926
+ };
20927
+ };
20679
20928
 
20680
20929
  /* begin_public_function
20681
20930
  id: comment.get_by_ids
@@ -20785,7 +21034,7 @@ const createComment = async (bundle) => {
20785
21034
  ingestInCache(data, { cachedAt });
20786
21035
  if (['post', 'content'].includes(bundle.referenceType)) {
20787
21036
  const post = await getPost$1(bundle.referenceId);
20788
- fireEvent('post.updated', {
21037
+ fireEvent('local.post.updated', {
20789
21038
  posts: [post.data],
20790
21039
  categories: [],
20791
21040
  comments: [],
@@ -20823,7 +21072,7 @@ const createComment = async (bundle) => {
20823
21072
  }
20824
21073
  }
20825
21074
  }
20826
- fireEvent('comment.created', data);
21075
+ fireEvent('local.comment.created', data);
20827
21076
  return {
20828
21077
  data: LinkedObject.comment(comments[0]),
20829
21078
  cachedAt,
@@ -20979,8 +21228,7 @@ const deleteComment = async (commentId, permanent = false) => {
20979
21228
  }
20980
21229
  else {
20981
21230
  const post = await getPost$1(comment.data.referenceId);
20982
- // @TODO: Need to separate Local / MQTT later
20983
- fireEvent('post.updated', {
21231
+ fireEvent('local.post.updated', {
20984
21232
  posts: [post.data],
20985
21233
  categories: [],
20986
21234
  comments: [],
@@ -20992,8 +21240,7 @@ const deleteComment = async (commentId, permanent = false) => {
20992
21240
  users: [],
20993
21241
  });
20994
21242
  }
20995
- // @TODO: Need to separate Local / MQTT later
20996
- fireEvent('comment.deleted', {
21243
+ fireEvent('local.comment.deleted', {
20997
21244
  comments: [deleted],
20998
21245
  commentChildren: [],
20999
21246
  files: [],
@@ -21288,142 +21535,438 @@ const getComment = (commentId, callback) => {
21288
21535
  onCommentUnflagged,
21289
21536
  onCommentUpdated,
21290
21537
  (callback) => {
21291
- return onCommentCreated((comment) => {
21292
- if (comment.parentId !== commentId)
21293
- return;
21294
- const cacheParent = pullFromCache([
21295
- 'comment',
21296
- 'get',
21297
- comment.parentId,
21298
- ]);
21299
- if (!(cacheParent === null || cacheParent === void 0 ? void 0 : cacheParent.data))
21300
- return;
21301
- callback(Object.assign(Object.assign({}, cacheParent.data), { childrenNumber: cacheParent.data.childrenNumber + 1, children: [...new Set([...cacheParent.data.children, comment.commentId])] }));
21538
+ return onCommentCreated((comment) => {
21539
+ if (comment.parentId !== commentId)
21540
+ return;
21541
+ const cacheParent = pullFromCache([
21542
+ 'comment',
21543
+ 'get',
21544
+ comment.parentId,
21545
+ ]);
21546
+ if (!(cacheParent === null || cacheParent === void 0 ? void 0 : cacheParent.data))
21547
+ return;
21548
+ callback(Object.assign(Object.assign({}, cacheParent.data), { childrenNumber: cacheParent.data.childrenNumber + 1, children: [...new Set([...cacheParent.data.children, comment.commentId])] }));
21549
+ });
21550
+ },
21551
+ ]);
21552
+ };
21553
+ /* end_public_function */
21554
+
21555
+ const convertToInternalComment = (commentPayload) => {
21556
+ const { comments } = commentPayload;
21557
+ return Object.assign(Object.assign({}, commentPayload), { comments: comments.map(comment => {
21558
+ if (comment.hasOwnProperty('myReactions'))
21559
+ return comment;
21560
+ // Sometimes `myReactions` field will not come with BE response because that field is empty
21561
+ // We need to put it with an empty array manually to make it show up in client side
21562
+ return Object.assign({ myReactions: [] }, comment);
21563
+ }) });
21564
+ };
21565
+
21566
+ const queryComments = async (query) => {
21567
+ const client = getActiveClient();
21568
+ client.log('comment/queryComments', query);
21569
+ const { limit = 10, includeDeleted } = query, params = __rest(query, ["limit", "includeDeleted"]);
21570
+ const options = {
21571
+ type: params.sortBy || query.limit ? 'pagination' : undefined,
21572
+ limit: query.limit,
21573
+ token: query.page,
21574
+ };
21575
+ // const filterByParentId = query.parentId !== undefined
21576
+ // API-FIX: parameters should be querystring. (1)
21577
+ // API-FIX: backend should answer Amity.Response (2)
21578
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.CommentPayload>>>(
21579
+ const { data } = await client.http.get(`/api/v3/comments`, {
21580
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
21581
+ // filterByParentId, API-FIX: backend does not support this boolean LOL. what the hell seriously.
21582
+ options }),
21583
+ });
21584
+ // API-FIX: backend should answer Amity.Response (2)
21585
+ // const { paging, comments } = unwrapPayload(data)
21586
+ const { paging } = data, payload = __rest(data, ["paging"]);
21587
+ const processedData = convertToInternalComment(payload);
21588
+ const { comments } = processedData;
21589
+ const cachedAt = client.cache && Date.now();
21590
+ if (client.cache) {
21591
+ ingestInCache(processedData, { cachedAt });
21592
+ const cacheKey = ['comment', 'query', Object.assign(Object.assign({}, params), { options: { limit } })];
21593
+ pushToCache(cacheKey, { comments: comments.map(getResolver('comment')), paging });
21594
+ }
21595
+ return { data: comments, cachedAt, paging };
21596
+ };
21597
+
21598
+ /* begin_public_function
21599
+ id: comment.query
21600
+ */
21601
+ /**
21602
+ * ```js
21603
+ * import { getComments } from '@amityco/ts-sdk-react-native'
21604
+ *
21605
+ * let comments = []
21606
+ * const unsub = getComments({
21607
+ * referenceType: Amity.InternalComment['referenceType'];
21608
+ * referenceId: Amity.InternalComment['referenceId'];
21609
+ * }, response => merge(comments, response.data))
21610
+ * ```
21611
+ *
21612
+ * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
21613
+ *
21614
+ * @param referenceType the type of the target
21615
+ * @param referenceId the ID of the target
21616
+ * @param callback the function to call when new data are available
21617
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
21618
+ *
21619
+ * @category Comments Live Collection
21620
+ */
21621
+ const getComments = (params, callback, config) => {
21622
+ const { log, cache } = getActiveClient();
21623
+ if (!cache) {
21624
+ console.log('For using Live Collection feature you need to enable Cache!');
21625
+ }
21626
+ const timestamp = Date.now();
21627
+ log(`getComments(tmpid: ${timestamp}) > listen`);
21628
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
21629
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
21630
+ const disposers = [];
21631
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
21632
+ const cacheKey = [
21633
+ 'comment',
21634
+ 'collection',
21635
+ {
21636
+ referenceId: params.referenceType,
21637
+ referenceType: params.referenceId,
21638
+ parentId: (params === null || params === void 0 ? void 0 : params.parentId) || '',
21639
+ sortBy,
21640
+ },
21641
+ ];
21642
+ const responder = (data) => {
21643
+ var _a, _b;
21644
+ let comments = (_a = data.data
21645
+ .map(commentId => pullFromCache(['comment', 'get', commentId]))
21646
+ .filter(({ data }) => data.parentId === (params === null || params === void 0 ? void 0 : params.parentId))
21647
+ .filter(Boolean)
21648
+ .map(({ data }) => LinkedObject.comment(data))) !== null && _a !== void 0 ? _a : [];
21649
+ if (!params.includeDeleted) {
21650
+ comments = filterByPropEquality(comments, 'isDeleted', false);
21651
+ }
21652
+ comments = comments.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
21653
+ callback({
21654
+ onNextPage: onFetch,
21655
+ data: comments,
21656
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
21657
+ loading: data.loading,
21658
+ error: data.error,
21659
+ });
21660
+ };
21661
+ const realtimeRouter = (action) => (comment) => {
21662
+ var _a;
21663
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21664
+ if (params.referenceId !== comment.referenceId ||
21665
+ params.referenceType !== comment.referenceType ||
21666
+ !collection) {
21667
+ return;
21668
+ }
21669
+ if (action === 'onCreate') {
21670
+ collection.data = [...new Set([comment.commentId, ...collection.data])];
21671
+ }
21672
+ else if (action === 'onDelete') {
21673
+ collection.data = collection.data.filter(p => p !== comment.commentId);
21674
+ }
21675
+ pushToCache(cacheKey, collection);
21676
+ responder(collection);
21677
+ };
21678
+ const onFetch = (initial = false) => {
21679
+ var _a, _b, _c;
21680
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21681
+ const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
21682
+ if (!initial && comments.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
21683
+ return;
21684
+ const query = createQuery(queryComments, Object.assign(Object.assign({}, queryParams), { limit: queryLimit, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
21685
+ runQuery(query, ({ data: result, error, loading, paging }) => {
21686
+ const page = paging === null || paging === void 0 ? void 0 : paging.next;
21687
+ const data = {
21688
+ loading,
21689
+ error,
21690
+ params: { page },
21691
+ data: comments,
21692
+ };
21693
+ if (result) {
21694
+ data.data = initial
21695
+ ? result.map(getResolver('comment')) // Replace a collection list with new data from BE
21696
+ : [...new Set([...comments, ...result.map(getResolver('comment'))])];
21697
+ }
21698
+ pushToCache(cacheKey, data);
21699
+ responder(data);
21700
+ }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
21701
+ };
21702
+ disposers.push(onCommentCreated(realtimeRouter('onCreate')), onCommentUpdated(realtimeRouter('onUpdate')), onCommentDeleted(realtimeRouter('onDelete')), onCommentFlagged(realtimeRouter('onFlagged')), onCommentUnflagged(realtimeRouter('onUnflagged')), onCommentReactionAdded(realtimeRouter('onReactionAdded')), onCommentReactionRemoved(realtimeRouter('onReactionRemoved')));
21703
+ onFetch(true);
21704
+ disposers.push(() => dropFromCache(cacheKey));
21705
+ return () => {
21706
+ log(`getComments(tmpid: ${timestamp}) > dispose`);
21707
+ disposers.forEach(fn => fn());
21708
+ };
21709
+ };
21710
+ /* end_public_function */
21711
+
21712
+ var index$5 = /*#__PURE__*/Object.freeze({
21713
+ __proto__: null,
21714
+ getCommentByIds: getCommentByIds,
21715
+ createComment: createComment,
21716
+ updateComment: updateComment,
21717
+ deleteComment: deleteComment,
21718
+ softDeleteComment: softDeleteComment,
21719
+ hardDeleteComment: hardDeleteComment,
21720
+ flagComment: flagComment,
21721
+ unflagComment: unflagComment,
21722
+ isCommentFlaggedByMe: isCommentFlaggedByMe,
21723
+ onCommentCreated: onCommentCreated,
21724
+ onCommentUpdated: onCommentUpdated,
21725
+ onCommentDeleted: onCommentDeleted,
21726
+ onCommentFlagged: onCommentFlagged,
21727
+ onCommentUnflagged: onCommentUnflagged,
21728
+ onCommentReactionAdded: onCommentReactionAdded,
21729
+ onCommentReactionRemoved: onCommentReactionRemoved,
21730
+ observeComments: observeComments,
21731
+ observeComment: observeComment,
21732
+ getComment: getComment,
21733
+ getComments: getComments
21734
+ });
21735
+
21736
+ /* begin_public_function
21737
+ id: post.get
21738
+ */
21739
+ /**
21740
+ * ```js
21741
+ * import { PostRepository } from '@amityco/ts-sdk-react-native';
21742
+ *
21743
+ * let post;
21744
+ *
21745
+ * const unsub = PostRepository.getPost(postId, response => {
21746
+ * post = response.data;
21747
+ * });
21748
+ * ```
21749
+ *
21750
+ * Observe all mutation on a given {@link Amity.Post}
21751
+ *
21752
+ * @param postId the ID of the message to observe
21753
+ * @param callback the function to call when new data are available
21754
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
21755
+ *
21756
+ * @category Post Live Object
21757
+ */
21758
+ const getPost = (postId, callback) => {
21759
+ return liveObject(postId, callback, 'postId', getPost$1, [
21760
+ onPostApproved,
21761
+ onPostDeclined,
21762
+ (callback) => {
21763
+ return onPostDeleted((post) => {
21764
+ var _a;
21765
+ let targetPost = post;
21766
+ // check if the deleted post is a child of the target post
21767
+ if (post.parentPostId === postId && post.isDeleted) {
21768
+ const parentPost = (_a = pullFromCache([
21769
+ 'post',
21770
+ 'get',
21771
+ post.parentPostId,
21772
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21773
+ if (parentPost) {
21774
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
21775
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
21776
+ // if the deleted post is a child of the target post, then the target post is the parent post
21777
+ targetPost = parentPost;
21778
+ }
21779
+ }
21780
+ callback(targetPost);
21781
+ });
21782
+ },
21783
+ onPostFlagged,
21784
+ (callback) => {
21785
+ return onPostReactionAdded((post) => {
21786
+ callback(LinkedObject.post(post));
21787
+ });
21788
+ },
21789
+ (callback) => {
21790
+ return onPostReactionRemoved((post) => {
21791
+ callback(LinkedObject.post(post));
21302
21792
  });
21303
21793
  },
21794
+ onPostUnflagged,
21795
+ onPostUpdated,
21796
+ convertEventPayload((callback) => {
21797
+ return onCommentCreated(async (comment) => {
21798
+ if (comment.referenceId === postId) {
21799
+ await getPost$1(postId);
21800
+ callback(comment);
21801
+ }
21802
+ });
21803
+ }, 'referenceId', 'post'),
21804
+ convertEventPayload((callback) => {
21805
+ return onCommentDeleted(async (comment) => {
21806
+ if (comment.referenceId === postId) {
21807
+ await getPost$1(postId);
21808
+ callback(comment);
21809
+ }
21810
+ });
21811
+ }, 'referenceId', 'post'),
21304
21812
  ]);
21305
21813
  };
21306
21814
  /* end_public_function */
21307
21815
 
21308
- const convertToInternalComment = (commentPayload) => {
21309
- const { comments } = commentPayload;
21310
- return Object.assign(Object.assign({}, commentPayload), { comments: comments.map(comment => {
21311
- if (comment.hasOwnProperty('myReactions'))
21312
- return comment;
21313
- // Sometimes `myReactions` field will not come with BE response because that field is empty
21314
- // We need to put it with an empty array manually to make it show up in client side
21315
- return Object.assign({ myReactions: [] }, comment);
21316
- }) });
21317
- };
21318
-
21319
- const queryComments = async (query) => {
21816
+ /**
21817
+ * ```js
21818
+ * import { queryPosts } from '@amityco/ts-sdk-react-native'
21819
+ * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
21820
+ * ```
21821
+ *
21822
+ * Queries a paginable list of {@link Amity.Post} objects
21823
+ *
21824
+ * @param query The query parameters
21825
+ * @returns posts
21826
+ *
21827
+ * @category Post API
21828
+ * @async
21829
+ */
21830
+ const queryPosts = async (query) => {
21320
21831
  const client = getActiveClient();
21321
- client.log('comment/queryComments', query);
21322
- const { limit = 10, includeDeleted } = query, params = __rest(query, ["limit", "includeDeleted"]);
21323
- const options = {
21324
- type: params.sortBy || query.limit ? 'pagination' : undefined,
21325
- limit: query.limit,
21326
- token: query.page,
21327
- };
21328
- // const filterByParentId = query.parentId !== undefined
21832
+ client.log('post/queryPosts', query);
21833
+ const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
21834
+ const { dataTypes, matchingOnlyParentPost } = params;
21835
+ const options = (() => {
21836
+ if (page)
21837
+ return { token: page };
21838
+ if (limit)
21839
+ return { limit };
21840
+ return undefined;
21841
+ })();
21329
21842
  // API-FIX: parameters should be querystring. (1)
21330
21843
  // API-FIX: backend should answer Amity.Response (2)
21331
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.CommentPayload>>>(
21332
- const { data } = await client.http.get(`/api/v3/comments`, {
21844
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
21845
+ const { data } = await client.http.get(`/api/v4/posts`, {
21333
21846
  params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
21334
- // filterByParentId, API-FIX: backend does not support this boolean LOL. what the hell seriously.
21335
- options }),
21847
+ /*
21848
+ * when creating post like image, file, video BE will create 2 posts
21849
+ * 1. parent post to store text with dataType=text
21850
+ * 2. child post to store dataTypes post data
21851
+ *
21852
+ * By default, BE queries only parent post
21853
+ */
21854
+ matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
21336
21855
  });
21337
21856
  // API-FIX: backend should answer Amity.Response (2)
21338
- // const { paging, comments } = unwrapPayload(data)
21857
+ // const { paging, posts } = unwrapPayload(data)
21858
+ // unpacking
21339
21859
  const { paging } = data, payload = __rest(data, ["paging"]);
21340
- const processedData = convertToInternalComment(payload);
21341
- const { comments } = processedData;
21860
+ const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
21861
+ const { posts } = payload;
21342
21862
  const cachedAt = client.cache && Date.now();
21343
21863
  if (client.cache) {
21344
- ingestInCache(processedData, { cachedAt });
21345
- const cacheKey = ['comment', 'query', Object.assign(Object.assign({}, params), { options: { limit } })];
21346
- pushToCache(cacheKey, { comments: comments.map(getResolver('comment')), paging });
21864
+ ingestInCache(paperedPayload, { cachedAt });
21865
+ const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
21866
+ pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
21347
21867
  }
21348
- return { data: comments, cachedAt, paging };
21868
+ return { data: posts.map(LinkedObject.post), cachedAt, paging };
21349
21869
  };
21350
21870
 
21351
21871
  /* begin_public_function
21352
- id: comment.query
21872
+ id: post.query
21353
21873
  */
21354
21874
  /**
21355
21875
  * ```js
21356
- * import { getComments } from '@amityco/ts-sdk-react-native'
21876
+ * import { PostRepository } from '@amityco/ts-sdk-react-native'
21357
21877
  *
21358
- * let comments = []
21359
- * const unsub = getComments({
21360
- * referenceType: Amity.InternalComment['referenceType'];
21361
- * referenceId: Amity.InternalComment['referenceId'];
21362
- * }, response => merge(comments, response.data))
21878
+ * let posts = []
21879
+ * const unsub = PostRepository.getPosts({
21880
+ * targetType: Amity.PostTargetType,
21881
+ * targetId: Amity.Post['targetId'],
21882
+ * }, response => merge(posts, response.data))
21363
21883
  * ```
21364
21884
  *
21365
- * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
21885
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
21366
21886
  *
21367
- * @param referenceType the type of the target
21368
- * @param referenceId the ID of the target
21887
+ * @param params.targetType the type of the target
21888
+ * @param params.targetId the ID of the target
21369
21889
  * @param callback the function to call when new data are available
21890
+ * @param config
21370
21891
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
21371
21892
  *
21372
- * @category Comments Live Collection
21893
+ * @category Posts Live Collection
21373
21894
  */
21374
- const getComments = (params, callback, config) => {
21895
+ const getPosts = (params, callback, config) => {
21375
21896
  const { log, cache } = getActiveClient();
21376
21897
  if (!cache) {
21377
- console.log('For using Live Collection feature you need to enable Cache!');
21898
+ console.log(ENABLE_CACHE_MESSAGE);
21378
21899
  }
21379
21900
  const timestamp = Date.now();
21380
- log(`getComments(tmpid: ${timestamp}) > listen`);
21901
+ log(`getPosts(tmpid: ${timestamp}) > listen`);
21381
21902
  const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
21903
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
21382
21904
  const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
21383
21905
  const disposers = [];
21384
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
21385
21906
  const cacheKey = [
21386
- 'comment',
21907
+ 'post',
21387
21908
  'collection',
21388
- {
21389
- referenceId: params.referenceType,
21390
- referenceType: params.referenceId,
21391
- parentId: (params === null || params === void 0 ? void 0 : params.parentId) || '',
21392
- sortBy,
21393
- },
21909
+ { targetId: params.targetId, targetType: params.targetType },
21394
21910
  ];
21395
21911
  const responder = (data) => {
21396
- var _a, _b;
21397
- let comments = (_a = data.data
21398
- .map(commentId => pullFromCache(['comment', 'get', commentId]))
21399
- .filter(({ data }) => data.parentId === (params === null || params === void 0 ? void 0 : params.parentId))
21912
+ var _a, _b, _c;
21913
+ let posts = (_a = data.data
21914
+ .map(postId => pullFromCache(['post', 'get', postId]))
21400
21915
  .filter(Boolean)
21401
- .map(({ data }) => LinkedObject.comment(data))) !== null && _a !== void 0 ? _a : [];
21916
+ .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
21917
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
21918
+ posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
21402
21919
  if (!params.includeDeleted) {
21403
- comments = filterByPropEquality(comments, 'isDeleted', false);
21920
+ posts = filterByPropEquality(posts, 'isDeleted', false);
21921
+ }
21922
+ if (params.tags) {
21923
+ posts = posts.filter(p => { var _a; return (_a = p.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); }); });
21924
+ }
21925
+ if (params.targetType === 'community' && params.feedType) {
21926
+ posts = filterByFeedType(posts, params.feedType);
21927
+ }
21928
+ if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
21929
+ posts = filterByPostDataTypes(posts, params.dataTypes);
21404
21930
  }
21405
- comments = comments.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
21406
21931
  callback({
21407
21932
  onNextPage: onFetch,
21408
- data: comments,
21409
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
21933
+ data: posts,
21934
+ hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
21410
21935
  loading: data.loading,
21411
21936
  error: data.error,
21412
21937
  });
21413
21938
  };
21414
- const realtimeRouter = (action) => (comment) => {
21415
- var _a;
21939
+ const realtimeRouter = (action) => (post) => {
21940
+ var _a, _b;
21416
21941
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21417
- if (params.referenceId !== comment.referenceId ||
21418
- params.referenceType !== comment.referenceType ||
21419
- !collection) {
21942
+ if (!collection)
21420
21943
  return;
21944
+ if (post.parentPostId && post.isDeleted) {
21945
+ const parentPost = (_b = pullFromCache([
21946
+ 'post',
21947
+ 'get',
21948
+ post.parentPostId,
21949
+ ])) === null || _b === void 0 ? void 0 : _b.data;
21950
+ if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
21951
+ return;
21952
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
21953
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
21421
21954
  }
21422
- if (action === 'onCreate') {
21423
- collection.data = [...new Set([comment.commentId, ...collection.data])];
21955
+ else {
21956
+ if (params.targetId !== post.targetId)
21957
+ return;
21958
+ if (params.targetType !== post.targetType)
21959
+ return;
21424
21960
  }
21425
- else if (action === 'onDelete') {
21426
- collection.data = collection.data.filter(p => p !== comment.commentId);
21961
+ /*
21962
+ * This is not ideal, but currently this is the only way to update the
21963
+ * collection on post declined
21964
+ */
21965
+ if (action === 'onDeclined') {
21966
+ collection.data = collection.data.filter(postId => postId !== post.postId);
21967
+ }
21968
+ else {
21969
+ collection.data = [...new Set([post.postId, ...collection.data])];
21427
21970
  }
21428
21971
  pushToCache(cacheKey, collection);
21429
21972
  responder(collection);
@@ -21431,32 +21974,49 @@ const getComments = (params, callback, config) => {
21431
21974
  const onFetch = (initial = false) => {
21432
21975
  var _a, _b, _c;
21433
21976
  const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21434
- const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
21435
- if (!initial && comments.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
21977
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
21978
+ if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
21436
21979
  return;
21437
- const query = createQuery(queryComments, Object.assign(Object.assign({}, queryParams), { limit: queryLimit, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
21980
+ const query = createQuery(queryPosts, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
21438
21981
  runQuery(query, ({ data: result, error, loading, paging }) => {
21439
- const page = paging === null || paging === void 0 ? void 0 : paging.next;
21440
21982
  const data = {
21441
21983
  loading,
21442
21984
  error,
21443
- params: { page },
21444
- data: comments,
21985
+ params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
21986
+ data: posts,
21445
21987
  };
21446
21988
  if (result) {
21447
21989
  data.data = initial
21448
- ? result.map(getResolver('comment')) // Replace a collection list with new data from BE
21449
- : [...new Set([...comments, ...result.map(getResolver('comment'))])];
21990
+ ? result.map(getResolver('post'))
21991
+ : [...new Set([...posts, ...result.map(getResolver('post'))])];
21450
21992
  }
21451
21993
  pushToCache(cacheKey, data);
21452
21994
  responder(data);
21453
21995
  }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
21454
21996
  };
21455
- disposers.push(onCommentCreated(realtimeRouter('onCreate')), onCommentUpdated(realtimeRouter('onUpdate')), onCommentDeleted(realtimeRouter('onDelete')), onCommentFlagged(realtimeRouter('onFlagged')), onCommentUnflagged(realtimeRouter('onUnflagged')), onCommentReactionAdded(realtimeRouter('onReactionAdded')), onCommentReactionRemoved(realtimeRouter('onReactionRemoved')));
21997
+ disposers.push(onPostCreated(realtimeRouter('onCreate')), onPostApproved(realtimeRouter('onApproved')), onPostDeclined(realtimeRouter('onDeclined')), onPostDeleted(realtimeRouter('onDelete')), onPostUpdated(realtimeRouter('onUpdate')), onPostFlagged(realtimeRouter('onFlagged')), onPostUnflagged(realtimeRouter('onUnflagged')), onPostReactionAdded(realtimeRouter('onReactionAdded')), onPostReactionRemoved(realtimeRouter('onReactionRemoved')), convertEventPayload((callback) => {
21998
+ return onCommentCreated(async (comment) => {
21999
+ var _a;
22000
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22001
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
22002
+ return;
22003
+ await getPost$1(comment.referenceId);
22004
+ callback(comment);
22005
+ });
22006
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')), convertEventPayload((callback) => {
22007
+ return onCommentDeleted(async (comment) => {
22008
+ var _a;
22009
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22010
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
22011
+ return;
22012
+ await getPost$1(comment.referenceId);
22013
+ callback(comment);
22014
+ });
22015
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')));
21456
22016
  onFetch(true);
21457
22017
  disposers.push(() => dropFromCache(cacheKey));
21458
22018
  return () => {
21459
- log(`getComments(tmpid: ${timestamp}) > dispose`);
22019
+ log(`getPosts(tmpid: ${timestamp}) > dispose`);
21460
22020
  disposers.forEach(fn => fn());
21461
22021
  };
21462
22022
  };
@@ -21464,26 +22024,31 @@ const getComments = (params, callback, config) => {
21464
22024
 
21465
22025
  var index$4 = /*#__PURE__*/Object.freeze({
21466
22026
  __proto__: null,
21467
- getCommentByIds: getCommentByIds,
21468
- createComment: createComment,
21469
- updateComment: updateComment,
21470
- deleteComment: deleteComment,
21471
- softDeleteComment: softDeleteComment,
21472
- hardDeleteComment: hardDeleteComment,
21473
- flagComment: flagComment,
21474
- unflagComment: unflagComment,
21475
- isCommentFlaggedByMe: isCommentFlaggedByMe,
21476
- onCommentCreated: onCommentCreated,
21477
- onCommentUpdated: onCommentUpdated,
21478
- onCommentDeleted: onCommentDeleted,
21479
- onCommentFlagged: onCommentFlagged,
21480
- onCommentUnflagged: onCommentUnflagged,
21481
- onCommentReactionAdded: onCommentReactionAdded,
21482
- onCommentReactionRemoved: onCommentReactionRemoved,
21483
- observeComments: observeComments,
21484
- observeComment: observeComment,
21485
- getComment: getComment,
21486
- getComments: getComments
22027
+ getPostByIds: getPostByIds,
22028
+ createPost: createPost,
22029
+ updatePost: updatePost,
22030
+ editPost: editPost,
22031
+ deletePost: deletePost,
22032
+ softDeletePost: softDeletePost,
22033
+ hardDeletePost: hardDeletePost,
22034
+ approvePost: approvePost,
22035
+ declinePost: declinePost,
22036
+ flagPost: flagPost,
22037
+ unflagPost: unflagPost,
22038
+ isPostFlaggedByMe: isPostFlaggedByMe,
22039
+ onPostCreated: onPostCreated,
22040
+ onPostUpdated: onPostUpdated,
22041
+ onPostDeleted: onPostDeleted,
22042
+ onPostApproved: onPostApproved,
22043
+ onPostDeclined: onPostDeclined,
22044
+ onPostFlagged: onPostFlagged,
22045
+ onPostUnflagged: onPostUnflagged,
22046
+ onPostReactionAdded: onPostReactionAdded,
22047
+ onPostReactionRemoved: onPostReactionRemoved,
22048
+ observePosts: observePosts,
22049
+ observePost: observePost,
22050
+ getPost: getPost,
22051
+ getPosts: getPosts
21487
22052
  });
21488
22053
 
21489
22054
  /* begin_public_function
@@ -21495,10 +22060,10 @@ var index$4 = /*#__PURE__*/Object.freeze({
21495
22060
  * const created = await createStream({ title: 'my stream', 'thumbnailFileId': fileId })
21496
22061
  * ```
21497
22062
  *
21498
- * Creates an {@link Amity.Stream}
22063
+ * Creates an {@link Amity.InternalStream}
21499
22064
  *
21500
- * @param bundle The data necessary to create a new {@link Amity.Stream}
21501
- * @returns The newly created {@link Amity.Stream}
22065
+ * @param bundle The data necessary to create a new {@link Amity.InternalStream}
22066
+ * @returns The newly created {@link Amity.InternalStream}
21502
22067
  *
21503
22068
  * @category Stream API
21504
22069
  * @async
@@ -21512,7 +22077,7 @@ const createStream = async (bundle) => {
21512
22077
  ingestInCache(data, { cachedAt });
21513
22078
  const { videoStreamings } = data;
21514
22079
  return {
21515
- data: videoStreamings[0],
22080
+ data: LinkedObject.stream(videoStreamings[0]),
21516
22081
  cachedAt,
21517
22082
  };
21518
22083
  };
@@ -21545,7 +22110,7 @@ const updateStream = async (streamId, patch) => {
21545
22110
  ingestInCache(data, { cachedAt });
21546
22111
  const { videoStreamings } = data;
21547
22112
  return {
21548
- data: videoStreamings.find(stream => stream.streamId === streamId),
22113
+ data: LinkedObject.stream(videoStreamings.find(stream => stream.streamId === streamId)),
21549
22114
  cachedAt,
21550
22115
  };
21551
22116
  };
@@ -21619,10 +22184,10 @@ getStream.locally = (streamId) => {
21619
22184
  * const success = await deleteStream(streamId)
21620
22185
  * ```
21621
22186
  *
21622
- * Deletes a {@link Amity.Stream}
22187
+ * Deletes a {@link Amity.InternalStream}
21623
22188
  *
21624
- * @param streamId The {@link Amity.Stream} ID to delete
21625
- * @return A success boolean if the {@link Amity.Stream} was deleted
22189
+ * @param streamId The {@link Amity.InternalStream} ID to delete
22190
+ * @return A success boolean if the {@link Amity.InternalStream} was deleted
21626
22191
  *
21627
22192
  * @category Stream API
21628
22193
  * @async
@@ -21647,11 +22212,11 @@ const deleteStream = async (streamId) => {
21647
22212
  * const stream = await disposeStream(streamId)
21648
22213
  * ```
21649
22214
  *
21650
- * Dispose a {@link Amity.Stream}.
22215
+ * Dispose a {@link Amity.InternalStream}.
21651
22216
  * Streaming status will be updated to "ended" and streaming url will be invalidated
21652
22217
  *
21653
- * @param streamId The {@link Amity.Stream} ID to dispose
21654
- * @returns the associated {@link Amity.Stream} object
22218
+ * @param streamId The {@link Amity.InternalStream} ID to dispose
22219
+ * @returns the associated {@link Amity.InternalStream} object
21655
22220
  *
21656
22221
  * @category Stream API
21657
22222
  * @async
@@ -21682,15 +22247,15 @@ const disposeStream = async (streamId) => {
21682
22247
  * const streams = await getStreams()
21683
22248
  * ```
21684
22249
  *
21685
- * Queries a paginable list of {@link Amity.Stream} objects
22250
+ * Queries a paginable list of {@link Amity.InternalStream} objects
21686
22251
  *
21687
22252
  * @param query The query parameters
21688
- * @returns A page of {@link Amity.Stream} objects
22253
+ * @returns A page of {@link Amity.InternalStream} objects
21689
22254
  *
21690
22255
  * @category Stream API
21691
22256
  * @async
21692
22257
  */
21693
- const queryStreams$1 = async (query) => {
22258
+ const queryStreams = async (query) => {
21694
22259
  const client = getActiveClient();
21695
22260
  client.log('stream/queryStreams', query);
21696
22261
  const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
@@ -21720,7 +22285,7 @@ const queryStreams$1 = async (query) => {
21720
22285
  * })
21721
22286
  * ```
21722
22287
  *
21723
- * Fired when a {@link Amity.Stream} has started airing
22288
+ * Fired when a {@link Amity.InternalStream} has started airing
21724
22289
  *
21725
22290
  * @param callback The function to call when the event was fired
21726
22291
  * @returns an {@link Amity.Unsubscriber} function to stop listening
@@ -21744,7 +22309,7 @@ const onStreamStarted = (callback) => {
21744
22309
  * })
21745
22310
  * ```
21746
22311
  *
21747
- * Fired when a {@link Amity.Stream} has stopped airing
22312
+ * Fired when a {@link Amity.InternalStream} has stopped airing
21748
22313
  *
21749
22314
  * @param callback The function to call when the event was fired
21750
22315
  * @returns an {@link Amity.Unsubscriber} function to stop listening
@@ -21768,7 +22333,7 @@ const onStreamStopped = (callback) => {
21768
22333
  * })
21769
22334
  * ```
21770
22335
  *
21771
- * Fired when the recordings of a {@link Amity.Stream} are available
22336
+ * Fired when the recordings of a {@link Amity.InternalStream} are available
21772
22337
  *
21773
22338
  * @param callback The function to call when the event was fired
21774
22339
  * @returns an {@link Amity.Unsubscriber} function to stop listening
@@ -21784,6 +22349,54 @@ const onStreamRecorded = (callback) => {
21784
22349
  return createEventSubscriber(client, 'stream/onStreamRecorded', 'v3.video-streaming.didRecord', filter);
21785
22350
  };
21786
22351
 
22352
+ /**
22353
+ * ```js
22354
+ * import { onStreamFlagged } from '@amityco/ts-sdk-react-native'
22355
+ * const dispose = onStreamFlagged(stream => {
22356
+ * // ...
22357
+ * })
22358
+ * ```
22359
+ *
22360
+ * Fired when a {@link Amity.InternalStream} has started airing
22361
+ *
22362
+ * @param callback The function to call when the event was fired
22363
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22364
+ *
22365
+ * @category Stream Events
22366
+ */
22367
+ const onStreamFlagged = (callback) => {
22368
+ const client = getActiveClient();
22369
+ const filter = (payload) => {
22370
+ ingestInCache(payload);
22371
+ callback(payload.videoStreamings[0]);
22372
+ };
22373
+ return createEventSubscriber(client, 'stream/onStreamFlagged', 'v3.video-streaming.didFlag', filter);
22374
+ };
22375
+
22376
+ /**
22377
+ * ```js
22378
+ * import { onStreamTerminated } from '@amityco/ts-sdk-react-native'
22379
+ * const dispose = onStreamTerminated(stream => {
22380
+ * // ...
22381
+ * })
22382
+ * ```
22383
+ *
22384
+ * Fired when a {@link Amity.InternalStream} has started airing
22385
+ *
22386
+ * @param callback The function to call when the event was fired
22387
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
22388
+ *
22389
+ * @category Stream Events
22390
+ */
22391
+ const onStreamTerminated = (callback) => {
22392
+ const client = getActiveClient();
22393
+ const filter = (payload) => {
22394
+ ingestInCache(payload);
22395
+ callback(payload.videoStreamings[0]);
22396
+ };
22397
+ return createEventSubscriber(client, 'stream/onStreamTerminated', 'v3.video-streaming.didTerminate', filter);
22398
+ };
22399
+
21787
22400
  /* eslint-disable no-use-before-define */
21788
22401
  /* begin_public_function
21789
22402
  id: stream.get
@@ -21798,15 +22411,22 @@ const onStreamRecorded = (callback) => {
21798
22411
  * Fetches a {@link Amity.Stream} object
21799
22412
  *
21800
22413
  * @param streamId the ID of the {@link Amity.Stream} to get
22414
+ * @param callback
21801
22415
  * @returns the associated {@link Amity.Stream} object
21802
22416
  *
21803
22417
  * @category Stream Live Object
21804
22418
  */
21805
22419
  const getStreamById = (streamId, callback) => {
21806
- return liveObject(streamId, callback, 'streamId', getStream, [
22420
+ const reactor = (snapshot) => {
22421
+ const { data } = snapshot;
22422
+ callback(Object.assign(Object.assign({}, snapshot), { data: data ? LinkedObject.stream(snapshot.data) : data }));
22423
+ };
22424
+ return liveObject(streamId, reactor, 'streamId', getStream, [
21807
22425
  onStreamRecorded,
21808
22426
  onStreamStarted,
21809
22427
  onStreamStopped,
22428
+ onStreamFlagged,
22429
+ onStreamTerminated,
21810
22430
  ]);
21811
22431
  };
21812
22432
  /* end_public_function */
@@ -21832,145 +22452,150 @@ getStreamById.locally = (streamId) => {
21832
22452
  if (!cached)
21833
22453
  return;
21834
22454
  return {
21835
- data: cached.data,
22455
+ data: LinkedObject.stream(cached.data),
21836
22456
  cachedAt: cached.cachedAt,
21837
22457
  };
21838
22458
  };
21839
22459
 
21840
- /* begin_public_function
21841
- id: stream.query
21842
- */
21843
- /**
21844
- * ```js
21845
- * import { getStreams } from '@amityco/ts-sdk-react-native'
21846
- * const streams = await getStreams()
21847
- * ```
21848
- *
21849
- * Queries a paginable list of {@link Amity.Stream} objects
21850
- *
21851
- * @param query The query parameters
21852
- * @returns A page of {@link Amity.Stream} objects
21853
- *
21854
- * @category Stream API
21855
- * @async
21856
- */
21857
- const queryStreams = async (query) => {
21858
- const client = getActiveClient();
21859
- client.log('stream/queryStreams', query);
21860
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit } = _a, params = __rest(_a, ["page", "limit"]);
21861
- const options = (() => {
21862
- if (page)
21863
- return { token: page };
21864
- if (limit)
21865
- return { limit };
21866
- return undefined;
21867
- })();
21868
- const { data } = await client.http.get(`/api/v3/video-streaming`, {
21869
- params: Object.assign(Object.assign({}, params), { options }),
21870
- });
21871
- // API-FIX: backend to response Amity.Response: const { paging, videoStreamings } = unwrapPayload(data)
21872
- // API-FIX: seems returned data has a results identifier on top of data, like no other apis, and this is beautiful
21873
- const { paging, results: payload } = data;
21874
- const { videoStreamings } = payload;
21875
- const cachedAt = client.cache && Date.now();
21876
- if (client.cache)
21877
- ingestInCache(payload, { cachedAt });
21878
- return { data: videoStreamings, cachedAt, paging };
21879
- };
21880
- /* end_public_function */
22460
+ class GetStreamsPageController extends PaginationController {
22461
+ async getRequest(queryParams, token) {
22462
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
22463
+ const options = token ? { token } : { limit };
22464
+ const { data: queryResponse } = await this.http.get(`/api/v3/video-streaming`, {
22465
+ params: Object.assign(Object.assign({}, params), { options }),
22466
+ });
22467
+ return Object.assign(Object.assign({}, queryResponse.results), { paging: queryResponse.paging });
22468
+ }
22469
+ }
21881
22470
 
21882
- /* begin_public_function
21883
- id: stream.query
21884
- */
21885
- /**
21886
- * ```js
21887
- * import { StreamRepository } from '@amityco/ts-sdk-react-native'
21888
- * const streams = await StreamRepository.getStreams()
21889
- * ```
21890
- *
21891
- * Observe all mutations on a list of {@link Amity.Stream}s
21892
- *
21893
- * @param params for querying streams
21894
- * @param callback the function to call when new data are available
21895
- * @param config
21896
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the streams
21897
- *
21898
- * @category Stream Live Collection
21899
- */
21900
- const getStreams = (params, callback, config) => {
21901
- const { log, cache } = getActiveClient();
21902
- if (!cache) {
21903
- console.log(ENABLE_CACHE_MESSAGE);
22471
+ class GetStreamsQueryStreamController extends QueryStreamController {
22472
+ constructor(query, cacheKey, notifyChange, paginationController) {
22473
+ super(query, cacheKey);
22474
+ this.notifyChange = notifyChange;
22475
+ this.paginationController = paginationController;
21904
22476
  }
21905
- const timestamp = Date.now();
21906
- log(`getStreams(tmpid: ${timestamp}) > listen`);
21907
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
21908
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
21909
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
21910
- const disposers = [];
21911
- const cacheKey = ['streams', 'collection', params];
21912
- const applyFilter = (data) => {
21913
- let streams = filterByPropEquality(data, 'isDeleted', params.isDeleted);
21914
- streams = streams.sort(params.sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
21915
- return streams;
21916
- };
21917
- const responder = (data, isEventModel = false) => {
22477
+ // eslint-disable-next-line class-methods-use-this
22478
+ saveToMainDB(response) {
22479
+ const client = getActiveClient();
22480
+ const cachedAt = client.cache && Date.now();
22481
+ if (client.cache) {
22482
+ ingestInCache(response, { cachedAt });
22483
+ }
22484
+ }
22485
+ appendToQueryStream(response, direction, refresh = false) {
21918
22486
  var _a, _b;
21919
- const streams = (_a = data.data
21920
- .map(streamId => {
21921
- return pullFromCache(['stream', 'get', streamId]);
21922
- })
21923
- .filter(Boolean)
21924
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
21925
- callback({
21926
- onNextPage: onFetch,
21927
- /*
21928
- * Only apply filter to RTE Model
21929
- */
21930
- data: isEventModel ? applyFilter(streams) : streams,
21931
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
21932
- loading: data.loading,
21933
- error: data.error,
21934
- });
21935
- };
21936
- const realtimeRouter = (_) => (stream) => {
22487
+ if (refresh) {
22488
+ pushToCache(this.cacheKey, {
22489
+ data: response.videoStreamings.map(getResolver('stream')),
22490
+ query: this.query,
22491
+ });
22492
+ }
22493
+ else {
22494
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22495
+ const messages = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
22496
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: direction === 'next'
22497
+ ? [...new Set([...messages, ...response.videoStreamings.map(getResolver('stream'))])]
22498
+ : [...new Set([...response.videoStreamings.map(getResolver('stream')), ...messages])] }));
22499
+ }
22500
+ }
22501
+ reactor(action) {
22502
+ return (payload) => {
22503
+ var _a;
22504
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22505
+ if (!collection)
22506
+ return;
22507
+ collection.data = [...new Set([payload.streamId, ...collection.data])];
22508
+ pushToCache(this.cacheKey, collection);
22509
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
22510
+ };
22511
+ }
22512
+ subscribeRTE(createSubscriber) {
22513
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
22514
+ }
22515
+ }
22516
+
22517
+ class GetStreamsLiveCollectionController extends LiveCollectionController {
22518
+ constructor(query, callback) {
22519
+ const queryStreamId = hash__default["default"](query);
22520
+ const cacheKey = ['streams', 'collection', queryStreamId];
22521
+ const paginationController = new GetStreamsPageController(query);
22522
+ super(paginationController, queryStreamId, cacheKey, callback);
22523
+ this.applyFilter = (data) => {
22524
+ let streams = filterByPropEquality(data, 'isDeleted', this.query.isDeleted);
22525
+ streams = streams.sort(this.query.sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
22526
+ return streams;
22527
+ };
22528
+ this.query = query;
22529
+ this.queryStreamController = new GetStreamsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
22530
+ this.paginationController = paginationController;
22531
+ this.callback = callback.bind(this);
22532
+ this.loadPage({ initial: true });
22533
+ }
22534
+ notifyChange({ origin, loading, error }) {
21937
22535
  var _a;
21938
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22536
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21939
22537
  if (!collection)
21940
22538
  return;
21941
- collection.data = [...new Set([stream.streamId, ...collection.data])];
21942
- pushToCache(cacheKey, collection);
21943
- responder(collection, true);
21944
- };
21945
- const onFetch = (initial = false) => {
21946
- var _a, _b;
21947
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21948
- const streams = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
21949
- if (!initial && streams.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
22539
+ let data = collection.data
22540
+ .map(streamId => pullFromCache(['stream', 'get', streamId]))
22541
+ .filter(Boolean)
22542
+ .map(stream => LinkedObject.stream(stream.data));
22543
+ if (!this.shouldNotify(data) && origin === 'event')
21950
22544
  return;
21951
- const query = createQuery(queryStreams, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
21952
- runQuery(query, ({ data: result, error, loading, paging }) => {
21953
- const data = {
21954
- loading,
21955
- error,
21956
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
21957
- data: streams,
21958
- };
21959
- if (result) {
21960
- data.data = [...new Set([...streams, ...result.map(getResolver('stream'))])];
21961
- }
21962
- pushToCache(cacheKey, data);
21963
- responder(data);
21964
- }, queryOptions(policy));
21965
- };
21966
- disposers.push(onStreamRecorded(realtimeRouter()), onStreamStarted(realtimeRouter()), onStreamStopped(realtimeRouter()));
21967
- onFetch(true);
22545
+ data = this.applyFilter(data);
22546
+ this.callback({
22547
+ onNextPage: () => this.loadPage({ initial: false, direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
22548
+ data,
22549
+ hasNextPage: !!this.paginationController.getNextToken(),
22550
+ loading,
22551
+ error,
22552
+ });
22553
+ }
22554
+ startSubscription() {
22555
+ return this.queryStreamController.subscribeRTE([
22556
+ { fn: onStreamRecorded, action: 'onStreamRecorded' },
22557
+ { fn: onStreamStarted, action: 'onStreamStarted' },
22558
+ { fn: onStreamStopped, action: 'onStreamStopped' },
22559
+ { fn: onStreamFlagged, action: 'onStreamFlagged' },
22560
+ { fn: onStreamTerminated, action: 'onStreamTerminated' },
22561
+ ]);
22562
+ }
22563
+ setup() {
22564
+ var _a;
22565
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
22566
+ if (!collection) {
22567
+ pushToCache(this.cacheKey, {
22568
+ data: [],
22569
+ params: {},
22570
+ });
22571
+ }
22572
+ }
22573
+ persistModel(response) {
22574
+ this.queryStreamController.saveToMainDB(response);
22575
+ }
22576
+ persistQueryStream({ response, direction, refresh, }) {
22577
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
22578
+ }
22579
+ }
22580
+
22581
+ const getStreams = (params, callback, config) => {
22582
+ const { log, cache, userId } = getActiveClient();
22583
+ if (!cache) {
22584
+ console.log(ENABLE_CACHE_MESSAGE);
22585
+ }
22586
+ const timestamp = Date.now();
22587
+ log(`getStreams(tmpid: ${timestamp}) > listen`);
22588
+ const liveCollection = new GetStreamsLiveCollectionController(params, callback);
22589
+ const disposers = liveCollection.startSubscription();
22590
+ const cacheKey = liveCollection.getCacheKey();
22591
+ disposers.push(() => {
22592
+ dropFromCache(cacheKey);
22593
+ });
21968
22594
  return () => {
21969
22595
  log(`getStreams(tmpid: ${timestamp}) > dispose`);
21970
22596
  disposers.forEach(fn => fn());
21971
22597
  };
21972
- };
21973
- /* end_public_function */
22598
+ };
21974
22599
 
21975
22600
  var index$3 = /*#__PURE__*/Object.freeze({
21976
22601
  __proto__: null,
@@ -21978,11 +22603,13 @@ var index$3 = /*#__PURE__*/Object.freeze({
21978
22603
  updateStream: updateStream,
21979
22604
  deleteStream: deleteStream,
21980
22605
  disposeStream: disposeStream,
21981
- queryStreams: queryStreams$1,
22606
+ queryStreams: queryStreams,
21982
22607
  getStream: getStream,
21983
22608
  onStreamStarted: onStreamStarted,
21984
22609
  onStreamStopped: onStreamStopped,
21985
22610
  onStreamRecorded: onStreamRecorded,
22611
+ onStreamFlagged: onStreamFlagged,
22612
+ onStreamTerminated: onStreamTerminated,
21986
22613
  getStreamById: getStreamById,
21987
22614
  getStreams: getStreams
21988
22615
  });
@@ -22315,7 +22942,7 @@ var index$2 = /*#__PURE__*/Object.freeze({
22315
22942
  getPoll: getPoll
22316
22943
  });
22317
22944
 
22318
- const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----";
22945
+ const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAARz+hmBgi8pJ\nQb8LeY41gtHhk+ACMwRfhsn7GqpqRQNG2qU0755mzZuVDUqjQMGSo8THJB7O+OJs\nflbZRkFXlFoFOVNw1UpNOgwEQZ6wB9oRwzepTJAfF1sVhm/o/ixvXh1zDFNDy6yZ\npXyiiJHUVxqyjllZhxnwdvjoVtDs6hW6awG09bB9nh/TTejlUKXoAgzqVwu/1QMu\nUVViET495elEe19aUarEy+oL2iKeXCEvqda/pWNBdbieFyJvvZ08HN8dPuT88wq2\njZLEAth1vrwQ2IAa4ktaLcBQdLJgIkrbDvAiVZ8lQAjS/bq5vXQikTGvoPlC5bbn\nvuOM/3eLAgMBAAECggEAVZ+peHAghq2QVj71nX5lxsNCKaCyYwixSJBpfouTt7Rz\nE6PpzMOXFi1W1o+I22jDakuSM2SOQKqI/u0QefB0r0O/KVk5NrZHXk0mkrdYtxOp\nUgaGyf8UvmjB+8VqHrNKyZdk9qtmbnNj01kTTcAtmE4H39zPR7eR/8Rul94vaZbs\nwCnKJS3mLT3JxyGug6lxanveKkjG+CKC1nJQYWaxCJxaFSzbwXQPvDhB+TvrIbee\npd5v4EAyEJohpr+T9oDGGJkb/KARBZCtwLyB976PKJwwBA8MRVL1i5QwawuMiMq5\nUtnOnbGKtCeFzaLbNU0Qi8bqyims84EQxC6DOu1fkQKBgQDdvsoBsEhsOXV7hlIJ\naEd0eSJZVkdqimxH8uGoMM2FeNaOrcB6yBXqTSP0R3OIyf8eaY6yjRvP30ZNXcll\n/gD3O1Mu6YmWQdt1W2WA6pKOsUuPXasf0pdOF7IiFZKlSabz5YHXFqwVuqm8loaj\nsXel3YWqPVdHiankE7tz+3ssnQKBgQDdqi4TNdD1MdEpihx19jr0QjUiXW3939FK\nqp30HESPEGDGQzXdmJgif9HhZb+cJSuWaHEbjgBrYahvgCF+y6LbEpOD+D/dmT+s\nDEAQaR84sah6dokwPjV8fjBSrcVFjCS+doxv0d3p/9OUEeyUhFrY03nxtIEYkLIE\n/Zvn37b4RwKBgQCLENVFe9XfsaVhQ5r9dV2iyTlmh7qgMZG5CbTFs12hQGhm8McO\n+Z7s41YSJCFr/yq1WwP4LJDtrBw99vyQr1zRsG35tNLp3gGRNzGQSQyC2uQFVHw2\np+7mNewsfhUK/gbrXNsyFnDz6635rPlhfbII3sWuP2wWXFqkxE9CbMwR7QKBgQC6\nawDMzxmo2/iYArrkyevSuEuPVxvFwpF1RgAI6C0QVCnPE38dmdN4UB7mfHekje4W\nVEercMURidPp0cxZolCYBQtilUjAyL0vqC3In1/Ogjq6oy3FEMxSop1pKxMY5j+Q\nnoqFD+6deLUrddeNH7J3X4LSr4dSbX4JjG+tlgt+yQKBgQCuwTL4hA6KqeInQ0Ta\n9VQX5Qr8hFlqJz1gpymi/k63tW/Ob8yedbg3WWNWyShwRMFYyY9S81ITFWM95uL6\nvF3x9rmRjwElJw9PMwVu6dmf/CO0Z1wzXSp2VVD12gbrUD/0/d7MUoJ9LgC8X8f/\nn0txLHYGHbx+nf95+JUg6lV3hg==\n-----END PRIVATE KEY-----";
22319
22946
  /*
22320
22947
  * The crypto algorithm used for importing key and signing string
22321
22948
  */
@@ -23460,7 +24087,7 @@ class StoryLiveCollectionController extends LiveCollectionController {
23460
24087
  this.queryStreamController = new StoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
23461
24088
  this.paginationController = paginationController;
23462
24089
  this.callback = callback.bind(this);
23463
- this.loadPage(true);
24090
+ this.loadPage({ initial: true });
23464
24091
  }
23465
24092
  setup() {
23466
24093
  var _a;
@@ -23642,7 +24269,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
23642
24269
  this.queryStreamController = new GlobalStoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
23643
24270
  this.paginationController = paginationController;
23644
24271
  this.callback = callback.bind(this);
23645
- this.loadPage(true);
24272
+ this.loadPage({ initial: true });
23646
24273
  }
23647
24274
  setup() {
23648
24275
  var _a;
@@ -23678,7 +24305,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
23678
24305
  return rest;
23679
24306
  });
23680
24307
  this.callback({
23681
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
24308
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
23682
24309
  data,
23683
24310
  hasNextPage: !!this.paginationController.getNextToken(),
23684
24311
  loading,
@@ -23788,7 +24415,7 @@ exports.API_REGIONS = API_REGIONS;
23788
24415
  exports.CategoryRepository = index$7;
23789
24416
  exports.ChannelRepository = index$b;
23790
24417
  exports.Client = index$k;
23791
- exports.CommentRepository = index$4;
24418
+ exports.CommentRepository = index$5;
23792
24419
  exports.CommunityPostSettingMaps = CommunityPostSettingMaps;
23793
24420
  exports.CommunityPostSettings = CommunityPostSettings;
23794
24421
  exports.CommunityRepository = index$8;
@@ -23802,7 +24429,7 @@ exports.MessageContentType = MessageContentType;
23802
24429
  exports.MessageRepository = index$f;
23803
24430
  exports.PollRepository = index$2;
23804
24431
  exports.PostContentType = PostContentType;
23805
- exports.PostRepository = index$5;
24432
+ exports.PostRepository = index$4;
23806
24433
  exports.ReactionRepository = index$g;
23807
24434
  exports.StoryRepository = index;
23808
24435
  exports.StreamRepository = index$3;