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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/.env +26 -26
  2. package/dist/@types/core/events.d.ts +5 -0
  3. package/dist/@types/core/events.d.ts.map +1 -1
  4. package/dist/@types/domains/community.d.ts +16 -1
  5. package/dist/@types/domains/community.d.ts.map +1 -1
  6. package/dist/client/api/secureLogout.d.ts +1 -1
  7. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  8. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  9. package/dist/commentRepository/events/utils.d.ts.map +1 -1
  10. package/dist/commentRepository/internalApi/createComment.d.ts.map +1 -1
  11. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  12. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  13. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  14. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  15. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  16. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts +14 -0
  17. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts.map +1 -0
  18. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts +9 -0
  19. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts.map +1 -0
  20. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +15 -0
  21. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -0
  22. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts +10 -0
  23. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts.map +1 -0
  24. package/dist/communityRepository/communityMembership/observers/getMembers.d.ts.map +1 -1
  25. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts +20 -0
  26. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts.map +1 -0
  27. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts +14 -0
  28. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -0
  29. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts +9 -0
  30. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts.map +1 -0
  31. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +15 -0
  32. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -0
  33. package/dist/communityRepository/observers/getCommunities/enums.d.ts +6 -0
  34. package/dist/communityRepository/observers/getCommunities/enums.d.ts.map +1 -0
  35. package/dist/communityRepository/observers/getCommunities.d.ts.map +1 -1
  36. package/dist/communityRepository/observers/index.d.ts +1 -0
  37. package/dist/communityRepository/observers/index.d.ts.map +1 -1
  38. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts +14 -0
  39. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts.map +1 -0
  40. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts +9 -0
  41. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -0
  42. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +15 -0
  43. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -0
  44. package/dist/communityRepository/observers/searchCommunities/enums.d.ts +6 -0
  45. package/dist/communityRepository/observers/searchCommunities/enums.d.ts.map +1 -0
  46. package/dist/communityRepository/observers/searchCommunities.d.ts +20 -0
  47. package/dist/communityRepository/observers/searchCommunities.d.ts.map +1 -0
  48. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  49. package/dist/communityRepository/utils/saveCommunityUsers.d.ts +2 -0
  50. package/dist/communityRepository/utils/saveCommunityUsers.d.ts.map +1 -0
  51. package/dist/core/events.d.ts +3 -3
  52. package/dist/core/events.d.ts.map +1 -1
  53. package/dist/core/liveCollection/LiveCollectionController.d.ts +4 -1
  54. package/dist/core/liveCollection/LiveCollectionController.d.ts.map +1 -1
  55. package/dist/index.cjs.js +1149 -797
  56. package/dist/index.esm.js +1148 -796
  57. package/dist/index.umd.js +4 -4
  58. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts +12 -0
  59. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts.map +1 -0
  60. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts +12 -0
  61. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts.map +1 -0
  62. package/dist/marker/events/onUserFeedMarkerUpdated.d.ts.map +1 -1
  63. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts +1 -1
  64. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts.map +1 -1
  65. package/dist/postRepository/observers/getPost.d.ts.map +1 -1
  66. package/dist/postRepository/observers/getPosts.d.ts.map +1 -1
  67. package/dist/streamRepository/api/getStreams.d.ts +2 -2
  68. package/dist/streamRepository/events/onStreamFlagged.d.ts +17 -0
  69. package/dist/streamRepository/events/onStreamFlagged.d.ts.map +1 -0
  70. package/dist/streamRepository/events/onStreamTerminated.d.ts +17 -0
  71. package/dist/streamRepository/events/onStreamTerminated.d.ts.map +1 -0
  72. package/dist/streamRepository/observers/getStreams.d.ts +1 -1
  73. package/dist/utils/liveObject.d.ts +3 -0
  74. package/dist/utils/liveObject.d.ts.map +1 -1
  75. package/package.json +1 -1
  76. package/src/@types/core/events.ts +8 -0
  77. package/src/@types/domains/community.ts +26 -1
  78. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +2 -2
  79. package/src/channelRepository/observers/getChannel.ts +2 -2
  80. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +7 -7
  81. package/src/client/api/secureLogout.ts +1 -1
  82. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +6 -3
  83. package/src/commentRepository/api/createComment.ts +2 -2
  84. package/src/commentRepository/api/deleteComment.ts +2 -4
  85. package/src/commentRepository/events/utils.ts +8 -5
  86. package/src/commentRepository/internalApi/createComment.ts +3 -2
  87. package/src/commentRepository/internalApi/deleteComment.ts +2 -2
  88. package/src/communityRepository/api/createCommunity.ts +5 -2
  89. package/src/communityRepository/api/getCommunities.ts +5 -1
  90. package/src/communityRepository/api/getCommunity.ts +5 -1
  91. package/src/communityRepository/api/queryCommunities.ts +2 -2
  92. package/src/communityRepository/api/updateCommunity.ts +5 -1
  93. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +152 -0
  94. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.ts +26 -0
  95. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +107 -0
  96. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +9 -0
  97. package/src/communityRepository/communityMembership/observers/getMembers.ts +15 -128
  98. package/src/communityRepository/communityMembership/observers/searchMembers.ts +60 -0
  99. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +147 -0
  100. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +31 -0
  101. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +88 -0
  102. package/src/communityRepository/observers/getCommunities/enums.ts +5 -0
  103. package/src/communityRepository/observers/getCommunities.ts +7 -150
  104. package/src/communityRepository/observers/index.ts +1 -0
  105. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +129 -0
  106. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +31 -0
  107. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +81 -0
  108. package/src/communityRepository/observers/searchCommunities/enums.ts +5 -0
  109. package/src/communityRepository/observers/searchCommunities.ts +56 -0
  110. package/src/communityRepository/utils/payload.ts +35 -1
  111. package/src/communityRepository/utils/saveCommunityUsers.ts +16 -0
  112. package/src/core/liveCollection/LiveCollectionController.ts +6 -3
  113. package/src/marker/events/onChannelUnreadUpdatedLocal.ts +29 -0
  114. package/src/marker/events/onSubChannelMarkerFetched.ts +1 -1
  115. package/src/marker/events/onSubChannelUnreadUpdatedLocal.ts +29 -0
  116. package/src/marker/events/onUserFeedMarkerUpdated.ts +3 -4
  117. package/src/marker/utils/reCalculateChannelUnreadInfo.ts +7 -3
  118. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +3 -3
  119. package/src/postRepository/api/editPost.ts +1 -1
  120. package/src/postRepository/api/updatePost.ts +1 -1
  121. package/src/postRepository/observers/getPost.ts +26 -0
  122. package/src/postRepository/observers/getPosts.ts +31 -0
  123. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +2 -2
  124. package/src/storyRepository/observers/getStoriesByTargetIds/StoryLiveCollectionController.ts +1 -1
  125. package/src/streamRepository/api/getStreams.ts +2 -2
  126. package/src/streamRepository/events/onStreamFlagged.ts +37 -0
  127. package/src/streamRepository/events/onStreamTerminated.ts +37 -0
  128. package/src/streamRepository/observers/getStreams.ts +1 -1
  129. package/src/subChannelRepository/observers/getSubChannel.ts +2 -2
  130. package/src/subChannelRepository/observers/getSubChannels/SubChannelLiveCollectionController.ts +4 -4
  131. package/src/utils/liveObject.ts +3 -0
package/dist/index.cjs.js CHANGED
@@ -5428,7 +5428,7 @@ const markAsReadBySegment = async ({ subChannelId, readToSegment, }) => {
5428
5428
  }
5429
5429
  };
5430
5430
 
5431
- const reCalculateChannelUnreadInfo = async (channelId) => {
5431
+ const reCalculateChannelUnreadInfo = (channelId) => {
5432
5432
  var _a;
5433
5433
  const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
5434
5434
  const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
@@ -5445,10 +5445,12 @@ const reCalculateChannelUnreadInfo = async (channelId) => {
5445
5445
  .reduce((acc, cur) => acc + cur, 0);
5446
5446
  isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
5447
5447
  }
5448
- pushToCache(cacheKeyChannelUnread, Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
5448
+ const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
5449
5449
  channelId,
5450
5450
  createdAt: new Date().toISOString(),
5451
- })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned }));
5451
+ })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
5452
+ pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
5453
+ return channelUnreadInfo;
5452
5454
  };
5453
5455
 
5454
5456
  class MessageReadReceiptSyncEngine {
@@ -5593,9 +5595,11 @@ class MessageReadReceiptSyncEngine {
5593
5595
  if (subChannelUnreadInfo && segment > subChannelUnreadInfo.readToSegment) {
5594
5596
  subChannelUnreadInfo.readToSegment = segment;
5595
5597
  subChannelUnreadInfo.unreadCount = Math.max(subChannelUnreadInfo.lastSegment - segment, 0);
5596
- reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
5598
+ const channelUnreadInfo = reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
5599
+ fireEvent('local.channelUnread.updated', channelUnreadInfo);
5600
+ pushToCache(cacheKey, subChannelUnreadInfo);
5601
+ fireEvent('local.subChannelUnread.updated', subChannelUnreadInfo);
5597
5602
  }
5598
- pushToCache(cacheKey, subChannelUnreadInfo);
5599
5603
  // Step 2: Enqueue the read receipt
5600
5604
  this.enqueueReadReceipt(subChannelId, segment);
5601
5605
  }
@@ -8590,9 +8594,9 @@ const enableUnreadCount = () => {
8590
8594
  const onUserFeedMarkerUpdated = (callback) => {
8591
8595
  const client = getActiveClient();
8592
8596
  const filter = (payload) => {
8593
- // update sub channel unread info and channel unread info in cache
8594
- persistUnreadCountInfo(payload);
8595
- callback(payload.feedMarkers[0]);
8597
+ payload.feedMarkers.forEach(feedMarker => {
8598
+ callback(feedMarker);
8599
+ });
8596
8600
  };
8597
8601
  return createEventSubscriber(client, 'feedMarker/onUserFeedMarkerUpdated', 'marker.userFeed-updated', filter);
8598
8602
  };
@@ -9102,7 +9106,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
9102
9106
  */
9103
9107
  /**
9104
9108
  * ```js
9105
- * import { Client } from '@amityco/ts-sdk'
9109
+ * import { Client } from '@amityco/ts-sdk-react-native'
9106
9110
  * const success = await Client.secureLogout()
9107
9111
  * ```
9108
9112
  *
@@ -9188,7 +9192,7 @@ const onChannelMarkerFetched = (callback) => {
9188
9192
  const onSubChannelMarkerFetched = (callback) => {
9189
9193
  const client = getActiveClient();
9190
9194
  const filter = (payload) => {
9191
- callback(payload.userFeedMarkers[0]);
9195
+ payload.userFeedMarkers.forEach(callback);
9192
9196
  };
9193
9197
  return createEventSubscriber(client, 'subChannelMarker/onSubChannelMarkerFetched', 'local.subChannelMarker.fetched', filter);
9194
9198
  };
@@ -9458,6 +9462,9 @@ function isEqual(x, y) {
9458
9462
  }));
9459
9463
  }
9460
9464
 
9465
+ /**
9466
+ * @deprecated This function is deprecated
9467
+ */
9461
9468
  const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
9462
9469
  const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
9463
9470
  const { cache } = getActiveClient();
@@ -13014,7 +13021,10 @@ const createCommentEventSubscriber = (event, callback) => {
13014
13021
  comments[0].parentId,
13015
13022
  ]);
13016
13023
  if (parentComment === null || parentComment === void 0 ? void 0 : parentComment.data) {
13017
- pushToCache(['comment', 'get', comments[0].parentId], Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber + 1, children: [...new Set([...parentComment.data.children, comments[0].commentId])] }));
13024
+ // Skip to update parent childComment if current comment already exists
13025
+ if (!parentComment.data.children.includes(comments[0].commentId)) {
13026
+ pushToCache(['comment', 'get', comments[0].parentId], Object.assign(Object.assign({}, parentComment.data), { childrenNumber: parentComment.data.childrenNumber + 1, children: [...new Set([...parentComment.data.children, comments[0].commentId])] }));
13027
+ }
13018
13028
  }
13019
13029
  }
13020
13030
  const queries = (_a = queryCache(['comment', 'query'])) === null || _a === void 0 ? void 0 : _a.filter(({ key }) => { var _a; return ((_a = key[2]) === null || _a === void 0 ? void 0 : _a.referenceId) === comment.data.referenceId; });
@@ -15443,7 +15453,7 @@ class LiveCollectionController {
15443
15453
  this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
15444
15454
  }
15445
15455
  }
15446
- loadPage(initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
15456
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
15447
15457
  this.setup();
15448
15458
  this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
15449
15459
  if (initial) {
@@ -15513,7 +15523,7 @@ class MessageLiveCollectionController extends LiveCollectionController {
15513
15523
  this.query = query;
15514
15524
  this.queryStreamController = new MessageQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMessagePayload, this.paginationController);
15515
15525
  this.callback = callback.bind(this);
15516
- this.loadPage(true);
15526
+ this.loadPage({ initial: true });
15517
15527
  }
15518
15528
  setup() {
15519
15529
  var _a;
@@ -15561,8 +15571,8 @@ class MessageLiveCollectionController extends LiveCollectionController {
15561
15571
  if (!this.shouldNotify(data) && origin === 'event')
15562
15572
  return;
15563
15573
  this.callback({
15564
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
15565
- onPrevPage: () => this.loadPage(false, "prev" /* Amity.LiveCollectionPageDirection.PREV */),
15574
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
15575
+ onPrevPage: () => this.loadPage({ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */ }),
15566
15576
  data,
15567
15577
  hasNextPage: !!this.paginationController.getNextToken(),
15568
15578
  hasPrevPage: !!this.paginationController.getPrevToken(),
@@ -15844,6 +15854,24 @@ var index$f = /*#__PURE__*/Object.freeze({
15844
15854
  convertQueryParams: convertQueryParams$1
15845
15855
  });
15846
15856
 
15857
+ /**
15858
+ * Internal used only
15859
+ *
15860
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
15861
+ *
15862
+ * @param callback The function to call when the event was fired
15863
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
15864
+ *
15865
+ * @category MessageMarker Events
15866
+ */
15867
+ const onSubChannelUnreadUpdatedLocal = (callback) => {
15868
+ const client = getActiveClient();
15869
+ const filter = (payload) => {
15870
+ callback(payload);
15871
+ };
15872
+ return createEventSubscriber(client, 'subChannelMarker/onSubChannelUnreadUpdatedLocal', 'local.subChannelUnread.updated', filter);
15873
+ };
15874
+
15847
15875
  /* begin_public_function
15848
15876
  id: subchannel.get
15849
15877
  */
@@ -15996,7 +16024,7 @@ const getSubChannel = (subChannelId, callback) => {
15996
16024
  };
15997
16025
  return onMessageDeleted(updateMessagePreview);
15998
16026
  }, 'subChannelId', 'subChannel'),
15999
- convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
16027
+ convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
16000
16028
  ], {
16001
16029
  forceDispatch: true,
16002
16030
  });
@@ -16086,7 +16114,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16086
16114
  this.query = query;
16087
16115
  this.queryStreamController = new SubChannelQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareSubChannelPayload);
16088
16116
  this.callback = callback.bind(this);
16089
- this.loadPage(true);
16117
+ this.loadPage({ initial: true });
16090
16118
  }
16091
16119
  setup() {
16092
16120
  var _a;
@@ -16263,7 +16291,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16263
16291
  action: 'onUpdate',
16264
16292
  },
16265
16293
  {
16266
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
16294
+ fn: convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
16267
16295
  action: 'onUpdate',
16268
16296
  },
16269
16297
  ]);
@@ -16281,7 +16309,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16281
16309
  if (!this.shouldNotify(data) && origin === 'event')
16282
16310
  return;
16283
16311
  this.callback({
16284
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
16312
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
16285
16313
  data,
16286
16314
  hasNextPage: !!this.paginationController.getNextToken(),
16287
16315
  loading,
@@ -16421,6 +16449,24 @@ var index$e = /*#__PURE__*/Object.freeze({
16421
16449
  stopMessageReceiptSync: stopMessageReceiptSync
16422
16450
  });
16423
16451
 
16452
+ /**
16453
+ * Internal used only
16454
+ *
16455
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
16456
+ *
16457
+ * @param callback The function to call when the event was fired
16458
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
16459
+ *
16460
+ * @category MessageMarker Events
16461
+ */
16462
+ const onChannelUnreadUpdatedLocal = (callback) => {
16463
+ const client = getActiveClient();
16464
+ const filter = (payload) => {
16465
+ callback(payload);
16466
+ };
16467
+ return createEventSubscriber(client, 'channelMarker/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
16468
+ };
16469
+
16424
16470
  /* begin_public_function
16425
16471
  id: channel.get
16426
16472
  */
@@ -16596,7 +16642,7 @@ const getChannel = (channelId, callback) => {
16596
16642
  return onSubChannelUpdated(updateMessagePreview);
16597
16643
  }, 'channelId', 'channel'),
16598
16644
  convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
16599
- convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
16645
+ convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
16600
16646
  ], {
16601
16647
  forceDispatch: true,
16602
16648
  });
@@ -16756,7 +16802,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
16756
16802
  }, paginationController);
16757
16803
  this.paginationController = paginationController;
16758
16804
  this.callback = callback.bind(this);
16759
- this.loadPage(true);
16805
+ this.loadPage({ initial: true });
16760
16806
  }
16761
16807
  setup() {
16762
16808
  var _a;
@@ -16795,7 +16841,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
16795
16841
  return;
16796
16842
  this.callback({
16797
16843
  onNextPage: this.paginationController instanceof ChannelPaginationController
16798
- ? () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */)
16844
+ ? () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ })
16799
16845
  : undefined,
16800
16846
  data,
16801
16847
  hasNextPage: this.paginationController instanceof ChannelPaginationController
@@ -17075,10 +17121,6 @@ class ChannelLiveCollectionController extends LiveCollectionController {
17075
17121
  }, 'channelId', 'channel'),
17076
17122
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17077
17123
  },
17078
- {
17079
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
17080
- action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17081
- },
17082
17124
  {
17083
17125
  fn: convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
17084
17126
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -17104,6 +17146,10 @@ class ChannelLiveCollectionController extends LiveCollectionController {
17104
17146
  },
17105
17147
  action: "onResolve" /* Amity.ChannelActionType.OnResolve */,
17106
17148
  },
17149
+ {
17150
+ fn: convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
17151
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17152
+ },
17107
17153
  ];
17108
17154
  if (this.paginationController instanceof PaginationController) {
17109
17155
  return [
@@ -17318,7 +17364,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
17318
17364
  this.query = query;
17319
17365
  this.queryStreamController = new ChannelMemberQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareChannelPayload);
17320
17366
  this.callback = callback.bind(this);
17321
- this.loadPage(true);
17367
+ this.loadPage({ initial: true });
17322
17368
  }
17323
17369
  setup() {
17324
17370
  var _a;
@@ -17360,7 +17406,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
17360
17406
  if (!this.shouldNotify(data) && origin === 'event')
17361
17407
  return;
17362
17408
  this.callback({
17363
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
17409
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
17364
17410
  data,
17365
17411
  hasNextPage: !!this.paginationController.getNextToken(),
17366
17412
  loading,
@@ -17750,12 +17796,30 @@ var index$b = /*#__PURE__*/Object.freeze({
17750
17796
  prepareChannelPayload: prepareChannelPayload
17751
17797
  });
17752
17798
 
17799
+ const saveCommunityUsers = (communities, communityUsers) => {
17800
+ if (communities.length === 0 || communityUsers.length === 0)
17801
+ return;
17802
+ communities.forEach(({ communityId }) => {
17803
+ const collection = communityUsers.filter(({ communityId: userCommunityId }) => communityId === userCommunityId);
17804
+ pushToCache(['communityUsers', 'collection', communityId], collection);
17805
+ });
17806
+ };
17807
+
17753
17808
  const getMatchPostSetting = (value) => {
17754
17809
  var _a;
17755
17810
  return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
17756
17811
  CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
17757
17812
  value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
17758
17813
  };
17814
+ const convertCommunityUsersToUniqueObject = (communityUsers) => {
17815
+ if (!communityUsers)
17816
+ return communityUsers;
17817
+ const result = {};
17818
+ communityUsers.forEach(user => {
17819
+ result[`${user.userId}#${user.communityId}`] = user;
17820
+ });
17821
+ return result;
17822
+ };
17759
17823
  const prepareCommunityPayload = (rawPayload) => {
17760
17824
  // Unpack community payload by mapping payload field to postSetting value.
17761
17825
  const communities = rawPayload.communities.map((_a) => {
@@ -17765,7 +17829,18 @@ const prepareCommunityPayload = (rawPayload) => {
17765
17829
  onlyAdminCanPost,
17766
17830
  }) }, restCommunityPayload));
17767
17831
  });
17768
- const communityUsers = withUsers(rawPayload.communityUsers);
17832
+ const mergeCommunityUsers = communities.reduce((acc, { communityId }) => {
17833
+ var _a;
17834
+ const users = (_a = pullFromCache([
17835
+ 'communityUsers',
17836
+ 'collection',
17837
+ communityId,
17838
+ ])) === null || _a === void 0 ? void 0 : _a.data;
17839
+ if (!users)
17840
+ return acc;
17841
+ return Object.assign(Object.assign({}, convertCommunityUsersToUniqueObject(users)), acc);
17842
+ }, convertCommunityUsersToUniqueObject(rawPayload.communityUsers));
17843
+ const communityUsers = withUsers(Object.values(mergeCommunityUsers));
17769
17844
  const communityWithMembershipStatus = updateMembershipStatus(communities, communityUsers);
17770
17845
  return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers });
17771
17846
  };
@@ -17799,8 +17874,10 @@ const getCommunities$1 = async (communityIds) => {
17799
17874
  });
17800
17875
  const data = prepareCommunityPayload(payload);
17801
17876
  const cachedAt = client.cache && Date.now();
17802
- if (client.cache)
17877
+ if (client.cache) {
17803
17878
  ingestInCache(data, { cachedAt });
17879
+ saveCommunityUsers(data.communities, data.communityUsers);
17880
+ }
17804
17881
  return {
17805
17882
  data: data.communities,
17806
17883
  cachedAt,
@@ -17862,8 +17939,10 @@ const createCommunity = async (bundle) => {
17862
17939
  fireEvent('community.created', payload);
17863
17940
  const data = prepareCommunityPayload(payload);
17864
17941
  const cachedAt = client.cache && Date.now();
17865
- if (client.cache)
17942
+ if (client.cache) {
17866
17943
  ingestInCache(data, { cachedAt });
17944
+ saveCommunityUsers(data.communities, data.communityUsers);
17945
+ }
17867
17946
  const { communities } = data;
17868
17947
  return {
17869
17948
  data: communities[0],
@@ -17897,8 +17976,10 @@ const updateCommunity = async (communityId, patch) => {
17897
17976
  fireEvent('community.updated', payload);
17898
17977
  const data = prepareCommunityPayload(payload);
17899
17978
  const cachedAt = client.cache && Date.now();
17900
- if (client.cache)
17979
+ if (client.cache) {
17901
17980
  ingestInCache(data, { cachedAt });
17981
+ saveCommunityUsers(data.communities, data.communityUsers);
17982
+ }
17902
17983
  const { communities } = data;
17903
17984
  return {
17904
17985
  data: communities.find(community => community.communityId === communityId),
@@ -17928,8 +18009,10 @@ const getCommunity$1 = async (communityId) => {
17928
18009
  const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
17929
18010
  const data = prepareCommunityPayload(payload);
17930
18011
  const cachedAt = client.cache && Date.now();
17931
- if (client.cache)
18012
+ if (client.cache) {
17932
18013
  ingestInCache(data, { cachedAt });
18014
+ saveCommunityUsers(data.communities, data.communityUsers);
18015
+ }
17933
18016
  const { communities } = data;
17934
18017
  return {
17935
18018
  data: communities.find(community => community.communityId === communityId),
@@ -18469,50 +18552,140 @@ const observeCommunity = (communityId, callback) => {
18469
18552
  };
18470
18553
 
18471
18554
  /**
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
18555
+ * TODO: handle cache receive cache option, and cache policy
18556
+ * TODO: check if querybyIds is supported
18485
18557
  */
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 });
18558
+ class CommunitiesPaginationController$1 extends PaginationController {
18559
+ async getRequest(queryParams, token) {
18560
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18561
+ const options = token ? { token } : { limit };
18562
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
18563
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
18564
+ });
18565
+ return queryResponse;
18513
18566
  }
18514
- return { data: communities, cachedAt, paging };
18515
- };
18567
+ }
18568
+
18569
+ class CommunitiesQueryStreamController$1 extends QueryStreamController {
18570
+ constructor(query, cacheKey, notifyChange, preparePayload) {
18571
+ super(query, cacheKey);
18572
+ this.notifyChange = notifyChange;
18573
+ this.preparePayload = preparePayload;
18574
+ }
18575
+ async saveToMainDB(response) {
18576
+ const processedPayload = await this.preparePayload(response);
18577
+ const client = getActiveClient();
18578
+ const cachedAt = client.cache && Date.now();
18579
+ if (client.cache) {
18580
+ ingestInCache(processedPayload, { cachedAt });
18581
+ }
18582
+ }
18583
+ appendToQueryStream(response, direction, refresh = false) {
18584
+ var _a, _b;
18585
+ if (refresh) {
18586
+ pushToCache(this.cacheKey, {
18587
+ data: response.communities.map(getResolver('community')),
18588
+ });
18589
+ }
18590
+ else {
18591
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18592
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18593
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
18594
+ }
18595
+ }
18596
+ reactor(action) {
18597
+ return (community) => {
18598
+ var _a;
18599
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18600
+ if (!collection)
18601
+ return;
18602
+ pushToCache(this.cacheKey, collection);
18603
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
18604
+ };
18605
+ }
18606
+ subscribeRTE(createSubscriber) {
18607
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
18608
+ }
18609
+ }
18610
+
18611
+ var EnumCommunityActions$1;
18612
+ (function (EnumCommunityActions) {
18613
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
18614
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
18615
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
18616
+ })(EnumCommunityActions$1 || (EnumCommunityActions$1 = {}));
18617
+
18618
+ /* eslint-disable no-use-before-define */
18619
+ class SearchCommunityLiveCollectionController extends LiveCollectionController {
18620
+ constructor(query, callback) {
18621
+ const queryStreamId = hash__default["default"](query);
18622
+ const cacheKey = ['community', 'collection', queryStreamId];
18623
+ const paginationController = new CommunitiesPaginationController$1(query);
18624
+ super(paginationController, queryStreamId, cacheKey, callback);
18625
+ this.query = query;
18626
+ this.queryStreamController = new CommunitiesQueryStreamController$1(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
18627
+ this.callback = callback.bind(this);
18628
+ this.loadPage({ initial: true });
18629
+ }
18630
+ setup() {
18631
+ var _a;
18632
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18633
+ if (!collection) {
18634
+ pushToCache(this.cacheKey, {
18635
+ data: [],
18636
+ params: {},
18637
+ });
18638
+ }
18639
+ }
18640
+ async persistModel(queryPayload) {
18641
+ await this.queryStreamController.saveToMainDB(queryPayload);
18642
+ }
18643
+ persistQueryStream({ response, direction, refresh, }) {
18644
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
18645
+ }
18646
+ startSubscription() {
18647
+ return this.queryStreamController.subscribeRTE([
18648
+ { fn: onCommunityDeleted, action: EnumCommunityActions$1.OnCommunityDeleted },
18649
+ { fn: onCommunityUpdated, action: EnumCommunityActions$1.OnCommunityUpdated },
18650
+ ]);
18651
+ }
18652
+ notifyChange({ origin, loading, error }) {
18653
+ var _a, _b;
18654
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18655
+ if (!collection)
18656
+ return;
18657
+ const data = this.applyFilter((_b = collection.data
18658
+ .map(id => pullFromCache(['community', 'get', id]))
18659
+ .filter(Boolean)
18660
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
18661
+ if (!this.shouldNotify(data) && origin === 'event')
18662
+ return;
18663
+ this.callback({
18664
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
18665
+ data,
18666
+ hasNextPage: !!this.paginationController.getNextToken(),
18667
+ loading,
18668
+ error,
18669
+ });
18670
+ }
18671
+ applyFilter(data) {
18672
+ const { userId } = getActiveClient();
18673
+ let communities = data;
18674
+ if (this.query.includeDeleted) {
18675
+ communities = filterByPropEquality(communities, 'isDeleted', false);
18676
+ }
18677
+ if (this.query.categoryId) {
18678
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
18679
+ }
18680
+ if (this.query.tags) {
18681
+ 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); }); });
18682
+ }
18683
+ if (this.query.membership && userId) {
18684
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
18685
+ }
18686
+ return communities;
18687
+ }
18688
+ }
18516
18689
 
18517
18690
  /* begin_public_function
18518
18691
  id: community.query
@@ -18522,7 +18695,7 @@ const queryCommunities = async (query) => {
18522
18695
  * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
18523
18696
  *
18524
18697
  * let communities = []
18525
- * const unsub = CommunityRepository.getCommunities({
18698
+ * const unsub = CommunityRepository.searchCommunities({
18526
18699
  * displayName: Amity.Community['displayName'],
18527
18700
  * }, response => merge(communities, response.data))
18528
18701
  * ```
@@ -18535,99 +18708,215 @@ const queryCommunities = async (query) => {
18535
18708
  *
18536
18709
  * @category Community Live Collection
18537
18710
  */
18538
- const getCommunities = (params, callback, config) => {
18539
- const { log, cache, userId } = getActiveClient();
18711
+ const searchCommunities = (params, callback, config) => {
18712
+ const { log, cache } = getActiveClient();
18540
18713
  if (!cache) {
18541
18714
  console.log(ENABLE_CACHE_MESSAGE);
18542
18715
  }
18543
18716
  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); }); });
18565
- }
18566
- if (params.membership && userId) {
18567
- communities = filterByCommunityMembership(communities, params.membership, userId);
18717
+ log(`searchCommunities(tmpid: ${timestamp}) > listen`);
18718
+ const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
18719
+ const disposers = searchCommunitiesLiveCollection.startSubscription();
18720
+ const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
18721
+ disposers.push(() => dropFromCache(cacheKey));
18722
+ return () => {
18723
+ log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
18724
+ disposers.forEach(fn => fn());
18725
+ };
18726
+ };
18727
+ /* end_public_function */
18728
+
18729
+ /**
18730
+ * TODO: handle cache receive cache option, and cache policy
18731
+ * TODO: check if querybyIds is supported
18732
+ */
18733
+ class CommunitiesPaginationController extends PaginationController {
18734
+ async getRequest(queryParams, token) {
18735
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18736
+ const options = token ? { token } : { limit };
18737
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
18738
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
18739
+ });
18740
+ return queryResponse;
18741
+ }
18742
+ }
18743
+
18744
+ var EnumCommunityActions;
18745
+ (function (EnumCommunityActions) {
18746
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
18747
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
18748
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
18749
+ })(EnumCommunityActions || (EnumCommunityActions = {}));
18750
+
18751
+ class CommunitiesQueryStreamController extends QueryStreamController {
18752
+ constructor(query, cacheKey, notifyChange, preparePayload) {
18753
+ super(query, cacheKey);
18754
+ this.notifyChange = notifyChange;
18755
+ this.preparePayload = preparePayload;
18756
+ }
18757
+ async saveToMainDB(response) {
18758
+ const processedPayload = await this.preparePayload(response);
18759
+ const client = getActiveClient();
18760
+ const cachedAt = client.cache && Date.now();
18761
+ if (client.cache) {
18762
+ ingestInCache(processedPayload, { cachedAt });
18763
+ saveCommunityUsers(response.communities, response.communityUsers);
18568
18764
  }
18569
- const sortBy = params.sortBy || 'lastCreated';
18570
- if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
18571
- communities = communities.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
18765
+ }
18766
+ appendToQueryStream(response, direction, refresh = false) {
18767
+ var _a, _b;
18768
+ if (refresh) {
18769
+ pushToCache(this.cacheKey, {
18770
+ data: response.communities.map(getResolver('community')),
18771
+ });
18572
18772
  }
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);
18773
+ else {
18774
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18775
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18776
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
18585
18777
  }
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) => {
18778
+ }
18779
+ reactor(action) {
18780
+ return (community) => {
18781
+ var _a;
18782
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18783
+ if (!collection)
18784
+ return;
18785
+ if (this.query.displayName && action === EnumCommunityActions.OnCommunityCreated) {
18786
+ return;
18787
+ }
18788
+ /*
18789
+ * Simply update a collection and let responder decide what to do with data
18790
+ */
18791
+ collection.data = [...new Set([community.communityId, ...collection.data])];
18792
+ pushToCache(this.cacheKey, collection);
18793
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
18794
+ };
18795
+ }
18796
+ subscribeRTE(createSubscriber) {
18797
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
18798
+ }
18799
+ }
18800
+
18801
+ /* eslint-disable no-use-before-define */
18802
+ class CommunityLiveCollectionController extends LiveCollectionController {
18803
+ constructor(query, callback) {
18804
+ const queryStreamId = hash__default["default"](query);
18805
+ const cacheKey = ['community', 'collection', queryStreamId];
18806
+ const paginationController = new CommunitiesPaginationController(query);
18807
+ super(paginationController, queryStreamId, cacheKey, callback);
18808
+ this.query = query;
18809
+ this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
18810
+ this.callback = callback.bind(this);
18811
+ this.loadPage({ initial: true });
18812
+ }
18813
+ setup() {
18595
18814
  var _a;
18596
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18815
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18816
+ if (!collection) {
18817
+ pushToCache(this.cacheKey, {
18818
+ data: [],
18819
+ params: {},
18820
+ });
18821
+ }
18822
+ }
18823
+ async persistModel(queryPayload) {
18824
+ await this.queryStreamController.saveToMainDB(queryPayload);
18825
+ }
18826
+ persistQueryStream({ response, direction, refresh, }) {
18827
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
18828
+ }
18829
+ startSubscription() {
18830
+ return this.queryStreamController.subscribeRTE([
18831
+ { fn: onCommunityCreated, action: EnumCommunityActions.OnCommunityCreated },
18832
+ { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
18833
+ { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
18834
+ ]);
18835
+ }
18836
+ notifyChange({ origin, loading, error }) {
18837
+ var _a, _b;
18838
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18597
18839
  if (!collection)
18598
18840
  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))
18841
+ const data = this.applyFilter((_b = collection.data
18842
+ .map(id => pullFromCache(['community', 'get', id]))
18843
+ .filter(Boolean)
18844
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
18845
+ if (!this.shouldNotify(data) && origin === 'event')
18611
18846
  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);
18847
+ this.callback({
18848
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
18849
+ data,
18850
+ hasNextPage: !!this.paginationController.getNextToken(),
18851
+ loading,
18852
+ error,
18853
+ });
18854
+ }
18855
+ applyFilter(data) {
18856
+ const { userId } = getActiveClient();
18857
+ let communities = data;
18858
+ if (this.query.includeDeleted) {
18859
+ communities = filterByPropEquality(communities, 'isDeleted', false);
18860
+ }
18861
+ if (this.query.categoryId) {
18862
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
18863
+ }
18864
+ if (this.query.tags) {
18865
+ 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); }); });
18866
+ }
18867
+ if (this.query.membership && userId) {
18868
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
18869
+ }
18870
+ if (!this.query.displayName) {
18871
+ const sortFn = (() => {
18872
+ switch (this.query.sortBy) {
18873
+ case 'firstCreated':
18874
+ return sortByFirstCreated;
18875
+ case 'lastCreated':
18876
+ return sortByLastCreated;
18877
+ case 'displayName':
18878
+ return sortByDisplayName;
18879
+ default:
18880
+ return sortByLastCreated;
18881
+ }
18882
+ })();
18883
+ communities = communities.sort(sortFn);
18884
+ }
18885
+ return communities;
18886
+ }
18887
+ }
18888
+
18889
+ /* begin_public_function
18890
+ id: community.query
18891
+ */
18892
+ /**
18893
+ * ```js
18894
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
18895
+ *
18896
+ * let communities = []
18897
+ * const unsub = CommunityRepository.getCommunities({
18898
+ * displayName: Amity.Community['displayName'],
18899
+ * }, response => merge(communities, response.data))
18900
+ * ```
18901
+ *
18902
+ * Observe all mutations on a list of {@link Amity.Community}s
18903
+ *
18904
+ * @param params for querying communities
18905
+ * @param callback the function to call when new data are available
18906
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
18907
+ *
18908
+ * @category Community Live Collection
18909
+ */
18910
+ const getCommunities = (params, callback, config) => {
18911
+ const { log, cache } = getActiveClient();
18912
+ if (!cache) {
18913
+ console.log(ENABLE_CACHE_MESSAGE);
18914
+ }
18915
+ const timestamp = Date.now();
18916
+ log(`getCommunities(tmpid: ${timestamp}) > listen`);
18917
+ const communitiesLiveCollection = new CommunityLiveCollectionController(params, callback);
18918
+ const disposers = communitiesLiveCollection.startSubscription();
18919
+ const cacheKey = communitiesLiveCollection.getCacheKey();
18631
18920
  disposers.push(() => dropFromCache(cacheKey));
18632
18921
  return () => {
18633
18922
  log(`getCommunities(tmpid: ${timestamp}) > dispose`);
@@ -19156,208 +19445,238 @@ const removeMembers = async (communityId, userIds) => {
19156
19445
  /* end_public_function */
19157
19446
 
19158
19447
  /**
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,
19196
- });
19197
- }
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
- };
19240
-
19241
- /*
19242
- * Exported for testing
19243
- * @hidden
19448
+ * TODO: handle cache receive cache option, and cache policy
19449
+ * TODO: check if querybyIds is supported
19244
19450
  */
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);
19451
+ class CommunityMembersPaginationController extends PaginationController {
19452
+ async getRequest(queryParams, token) {
19453
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
19454
+ const options = token ? { token } : { limit };
19455
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
19456
+ params: Object.assign(Object.assign({}, params), { options }),
19251
19457
  });
19458
+ return queryResponse;
19252
19459
  }
19253
- if (params.search) {
19254
- communityMembers = filterBySearchTerm(communityMembers, params.search);
19460
+ }
19461
+
19462
+ class CommunityMembersQueryStreamController extends QueryStreamController {
19463
+ constructor(query, cacheKey, notifyChange, preparePayload) {
19464
+ super(query, cacheKey);
19465
+ this.notifyChange = notifyChange;
19466
+ this.preparePayload = preparePayload;
19255
19467
  }
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);
19468
+ async saveToMainDB(response) {
19469
+ const processedPayload = await this.preparePayload(response);
19470
+ const client = getActiveClient();
19471
+ const cachedAt = client.cache && Date.now();
19472
+ if (client.cache) {
19473
+ ingestInCache(processedPayload, { cachedAt });
19474
+ }
19285
19475
  }
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) => {
19476
+ appendToQueryStream(response, direction, refresh = false) {
19299
19477
  var _a, _b;
19300
- const communityMembers = (_a = data.data
19301
- .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,
19310
- });
19311
- };
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;
19478
+ if (refresh) {
19479
+ pushToCache(this.cacheKey, {
19480
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19481
+ });
19482
+ }
19483
+ else {
19484
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19485
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
19486
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
19487
+ ...new Set([
19488
+ ...communityUsers,
19489
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
19490
+ ]),
19491
+ ] }));
19317
19492
  }
19318
- const communityMemberCacheIds = communityMembers
19319
- .map(communityMember => {
19320
- if (params.communityId !== communityMember.communityId) {
19493
+ }
19494
+ reactor(action) {
19495
+ return (community, communityMembers) => {
19496
+ var _a;
19497
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19498
+ if (!collection)
19321
19499
  return;
19322
- }
19323
- const communityMemberCacheId = getResolver('communityUsers')({
19324
- communityId: params.communityId,
19325
- userId: communityMember.userId,
19500
+ communityMembers.forEach(communityMember => {
19501
+ const communityMemberCacheId = getResolver('communityUsers')({
19502
+ communityId: this.query.communityId,
19503
+ userId: communityMember.userId,
19504
+ });
19505
+ if (communityMember.communityMembership === 'none') {
19506
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
19507
+ }
19508
+ else if (!collection.data.includes(communityMemberCacheId)) {
19509
+ collection.data = [communityMemberCacheId, ...collection.data];
19510
+ }
19326
19511
  });
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) => {
19512
+ pushToCache(this.cacheKey, collection);
19513
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
19514
+ };
19515
+ }
19516
+ subscribeRTE(createSubscriber) {
19517
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
19518
+ }
19519
+ }
19520
+
19521
+ var EnumCommunityMemberActions;
19522
+ (function (EnumCommunityMemberActions) {
19523
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
19524
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
19525
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
19526
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
19527
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
19528
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
19529
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
19530
+ })(EnumCommunityMemberActions || (EnumCommunityMemberActions = {}));
19531
+
19532
+ /* eslint-disable no-use-before-define */
19533
+ class CommunityMembersLiveCollectionController extends LiveCollectionController {
19534
+ constructor(query, callback) {
19535
+ const queryStreamId = hash__default["default"](query);
19536
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
19537
+ const paginationController = new CommunityMembersPaginationController(query);
19538
+ super(paginationController, queryStreamId, cacheKey, callback);
19539
+ this.query = query;
19540
+ this.queryStreamController = new CommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
19541
+ this.callback = callback.bind(this);
19542
+ this.loadPage({ initial: true });
19543
+ }
19544
+ setup() {
19545
+ var _a;
19546
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19547
+ if (!collection) {
19548
+ pushToCache(this.cacheKey, {
19549
+ data: [],
19550
+ params: {},
19551
+ });
19552
+ }
19553
+ }
19554
+ async persistModel(queryPayload) {
19555
+ await this.queryStreamController.saveToMainDB(queryPayload);
19556
+ }
19557
+ persistQueryStream({ response, direction, refresh, }) {
19558
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
19559
+ }
19560
+ startSubscription() {
19561
+ return this.queryStreamController.subscribeRTE([
19562
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions.OnCommunityJoined },
19563
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
19564
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
19565
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
19566
+ { fn: onCommunityUserRoleAdded, action: EnumCommunityMemberActions.OnCommunityUserRoleAdded },
19567
+ {
19568
+ fn: onCommunityUserRoleRemoved,
19569
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
19570
+ },
19571
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
19572
+ ]);
19573
+ }
19574
+ notifyChange({ origin, loading, error }) {
19336
19575
  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))
19576
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
19577
+ if (!collection)
19340
19578
  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);
19579
+ const data = this.applyFilter((_b = collection.data
19580
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
19581
+ .filter(isNonNullable)
19582
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
19583
+ if (!this.shouldNotify(data) && origin === 'event')
19584
+ return;
19585
+ this.callback({
19586
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
19587
+ data,
19588
+ hasNextPage: !!this.paginationController.getNextToken(),
19589
+ loading,
19590
+ error,
19591
+ });
19592
+ }
19593
+ applyFilter(data) {
19594
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
19595
+ if (this.query.memberships) {
19596
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
19597
+ const memberships = this.query.memberships || [];
19598
+ return memberships.includes(communityMembership);
19599
+ });
19600
+ }
19601
+ if (this.query.search) {
19602
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
19603
+ }
19604
+ const sortBy = this.query.sortBy ? this.query.sortBy : 'lastCreated';
19605
+ switch (sortBy) {
19606
+ case 'lastCreated':
19607
+ communityMembers = communityMembers.sort(sortByLastCreated);
19608
+ break;
19609
+ case 'firstCreated':
19610
+ communityMembers = communityMembers.sort(sortByFirstCreated);
19611
+ break;
19612
+ case 'displayName':
19613
+ communityMembers = communityMembers.sort((memberA, memberB) => {
19614
+ if (!memberA.user || !memberB.user)
19615
+ return 0;
19616
+ return sortByDisplayName(memberA.user, memberB.user);
19617
+ });
19618
+ break;
19619
+ }
19620
+ return communityMembers;
19621
+ }
19622
+ }
19623
+
19624
+ /*
19625
+ * Exported for testing
19626
+ * @hidden
19627
+ */
19628
+ const applyFilter = (data, params) => {
19629
+ let communityMembers = filterByPropIntersection(data, 'roles', params.roles);
19630
+ if (params.memberships) {
19631
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
19632
+ const membership = params.memberships;
19633
+ return membership.includes(communityMembership);
19634
+ });
19635
+ }
19636
+ if (params.search) {
19637
+ communityMembers = filterBySearchTerm(communityMembers, params.search);
19638
+ }
19639
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
19640
+ communityMembers = communityMembers.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
19641
+ return communityMembers;
19642
+ };
19643
+ /* begin_public_function
19644
+ id: community.membership.query
19645
+ */
19646
+ /**
19647
+ * ```js
19648
+ * import { getMembers } from '@amityco/ts-sdk-react-native'
19649
+ *
19650
+ * let communityMembers = []
19651
+ * const unsub = getMembers({
19652
+ * communityId: Amity.Community['communityId'],
19653
+ * }, response => merge(communityMembers, response.data))
19654
+ * ```
19655
+ *
19656
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
19657
+ *
19658
+ * @param params for querying community users
19659
+ * @param callback the function to call when new data are available
19660
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
19661
+ *
19662
+ * @category Community Live Collection
19663
+ */
19664
+ const getMembers = (params, callback, config) => {
19665
+ const { log, cache } = getActiveClient();
19666
+ if (!cache) {
19667
+ console.log(ENABLE_CACHE_MESSAGE);
19668
+ }
19669
+ const timestamp = Date.now();
19670
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
19671
+ const communityMemberLiveCollection = new CommunityMembersLiveCollectionController(params, resp => {
19672
+ console.log('resp', resp);
19673
+ callback(resp);
19674
+ });
19675
+ const disposers = communityMemberLiveCollection.startSubscription();
19676
+ const cacheKey = communityMemberLiveCollection.getCacheKey();
19677
+ disposers.push(() => {
19678
+ dropFromCache(cacheKey);
19679
+ });
19361
19680
  return () => {
19362
19681
  log(`getMembers(tmpid: ${timestamp}) > dispose`);
19363
19682
  disposers.forEach(fn => fn());
@@ -19397,6 +19716,7 @@ var index$8 = /*#__PURE__*/Object.freeze({
19397
19716
  onCommunityUpdated: onCommunityUpdated,
19398
19717
  onCommunityDeleted: onCommunityDeleted,
19399
19718
  observeCommunity: observeCommunity,
19719
+ searchCommunities: searchCommunities,
19400
19720
  getCommunities: getCommunities,
19401
19721
  getCommunity: getCommunity,
19402
19722
  getTrendingCommunities: getTrendingCommunities,
@@ -19983,7 +20303,7 @@ const updatePost = async (postId, patch) => {
19983
20303
  const cachedAt = client.cache && Date.now();
19984
20304
  if (client.cache)
19985
20305
  ingestInCache(data, { cachedAt });
19986
- fireEvent('post.updated', data);
20306
+ fireEvent('local.post.updated', data);
19987
20307
  const { posts } = data;
19988
20308
  return {
19989
20309
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -20020,7 +20340,7 @@ const editPost = async (postId, patch) => {
20020
20340
  const cachedAt = client.cache && Date.now();
20021
20341
  if (client.cache)
20022
20342
  ingestInCache(data, { cachedAt });
20023
- fireEvent('post.updated', data);
20343
+ fireEvent('local.post.updated', data);
20024
20344
  const { posts } = data;
20025
20345
  return {
20026
20346
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -20394,347 +20714,63 @@ const observePost = (postId, callback, policy = 'cache_then_server') => {
20394
20714
  };
20395
20715
 
20396
20716
  /* begin_public_function
20397
- id: post.get
20717
+ id: comment.get_by_ids
20398
20718
  */
20399
20719
  /**
20400
20720
  * ```js
20401
- * import { PostRepository } from '@amityco/ts-sdk-react-native';
20721
+ * import { CommentRepository } from '@amityco/ts-sdk-react-native'
20722
+ * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
20723
+ * ```
20402
20724
  *
20403
- * let post;
20725
+ * Fetches a collection of {@link Amity.Comment} objects
20404
20726
  *
20405
- * const unsub = PostRepository.getPost(postId, response => {
20406
- * post = response.data;
20407
- * });
20727
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
20728
+ * @returns the associated collection of {@link Amity.Comment} objects
20729
+ *
20730
+ * @category Comment API
20731
+ * @async
20732
+ */
20733
+ const getCommentByIds = async (commentIds) => {
20734
+ const client = getActiveClient();
20735
+ client.log('comment/getCommentByIds', commentIds);
20736
+ const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
20737
+ let data;
20738
+ try {
20739
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
20740
+ const response = await client.http.get(`/api/v3/comments/list`, {
20741
+ params: { commentIds: encodedCommentIds },
20742
+ });
20743
+ data = response.data;
20744
+ }
20745
+ catch (error) {
20746
+ commentIds.forEach(commentId => {
20747
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
20748
+ pushToTombstone('comment', commentId);
20749
+ }
20750
+ });
20751
+ throw error;
20752
+ }
20753
+ const cachedAt = client.cache && Date.now();
20754
+ if (client.cache)
20755
+ ingestInCache(data, { cachedAt });
20756
+ return {
20757
+ data: data.comments.map(comment => LinkedObject.comment(comment)),
20758
+ cachedAt,
20759
+ };
20760
+ };
20761
+ /* end_public_function */
20762
+ /**
20763
+ * ```js
20764
+ * import { getCommentByIds } from '@amityco/ts-sdk-react-native'
20765
+ * const comments = getCommentByIds.locally(['foo', 'bar'])
20408
20766
  * ```
20409
20767
  *
20410
- * Observe all mutation on a given {@link Amity.Post}
20768
+ * Fetches a collection of {@link Amity.Comment} objects from cache
20411
20769
  *
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
20770
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
20771
+ * @returns the associated collection of {@link Amity.Comment} objects
20415
20772
  *
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
- ]);
20457
- };
20458
- /* end_public_function */
20459
-
20460
- /**
20461
- * ```js
20462
- * import { queryPosts } from '@amityco/ts-sdk-react-native'
20463
- * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
20464
- * ```
20465
- *
20466
- * Queries a paginable list of {@link Amity.Post} objects
20467
- *
20468
- * @param query The query parameters
20469
- * @returns posts
20470
- *
20471
- * @category Post API
20472
- * @async
20473
- */
20474
- const queryPosts = async (query) => {
20475
- 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
- };
20514
-
20515
- /* begin_public_function
20516
- id: post.query
20517
- */
20518
- /**
20519
- * ```js
20520
- * import { PostRepository } from '@amityco/ts-sdk-react-native'
20521
- *
20522
- * let posts = []
20523
- * const unsub = PostRepository.getPosts({
20524
- * targetType: Amity.PostTargetType,
20525
- * targetId: Amity.Post['targetId'],
20526
- * }, response => merge(posts, response.data))
20527
- * ```
20528
- *
20529
- * Observe all mutations on a list of {@link Amity.Post} for a given target object
20530
- *
20531
- * @param params.targetType the type of the target
20532
- * @param params.targetId the ID of the target
20533
- * @param callback the function to call when new data are available
20534
- * @param config
20535
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
20536
- *
20537
- * @category Posts Live Collection
20538
- */
20539
- const getPosts = (params, callback, config) => {
20540
- const { log, cache } = getActiveClient();
20541
- if (!cache) {
20542
- console.log(ENABLE_CACHE_MESSAGE);
20543
- }
20544
- 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 : {};
20549
- 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) => {
20584
- 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))
20623
- 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));
20640
- };
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));
20644
- return () => {
20645
- log(`getPosts(tmpid: ${timestamp}) > dispose`);
20646
- disposers.forEach(fn => fn());
20647
- };
20648
- };
20649
- /* end_public_function */
20650
-
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
- });
20679
-
20680
- /* begin_public_function
20681
- id: comment.get_by_ids
20682
- */
20683
- /**
20684
- * ```js
20685
- * import { CommentRepository } from '@amityco/ts-sdk-react-native'
20686
- * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
20687
- * ```
20688
- *
20689
- * Fetches a collection of {@link Amity.Comment} objects
20690
- *
20691
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
20692
- * @returns the associated collection of {@link Amity.Comment} objects
20693
- *
20694
- * @category Comment API
20695
- * @async
20696
- */
20697
- const getCommentByIds = async (commentIds) => {
20698
- const client = getActiveClient();
20699
- client.log('comment/getCommentByIds', commentIds);
20700
- const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
20701
- let data;
20702
- try {
20703
- // API-FIX: endpoint should not be /list, parameters should be querystring.
20704
- const response = await client.http.get(`/api/v3/comments/list`, {
20705
- params: { commentIds: encodedCommentIds },
20706
- });
20707
- data = response.data;
20708
- }
20709
- catch (error) {
20710
- commentIds.forEach(commentId => {
20711
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
20712
- pushToTombstone('comment', commentId);
20713
- }
20714
- });
20715
- throw error;
20716
- }
20717
- const cachedAt = client.cache && Date.now();
20718
- if (client.cache)
20719
- ingestInCache(data, { cachedAt });
20720
- return {
20721
- data: data.comments.map(comment => LinkedObject.comment(comment)),
20722
- cachedAt,
20723
- };
20724
- };
20725
- /* end_public_function */
20726
- /**
20727
- * ```js
20728
- * import { getCommentByIds } from '@amityco/ts-sdk-react-native'
20729
- * const comments = getCommentByIds.locally(['foo', 'bar'])
20730
- * ```
20731
- *
20732
- * Fetches a collection of {@link Amity.Comment} objects from cache
20733
- *
20734
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
20735
- * @returns the associated collection of {@link Amity.Comment} objects
20736
- *
20737
- * @category Comment API
20773
+ * @category Comment API
20738
20774
  */
20739
20775
  getCommentByIds.locally = (commentIds) => {
20740
20776
  var _a;
@@ -20785,7 +20821,7 @@ const createComment = async (bundle) => {
20785
20821
  ingestInCache(data, { cachedAt });
20786
20822
  if (['post', 'content'].includes(bundle.referenceType)) {
20787
20823
  const post = await getPost$1(bundle.referenceId);
20788
- fireEvent('post.updated', {
20824
+ fireEvent('local.post.updated', {
20789
20825
  posts: [post.data],
20790
20826
  categories: [],
20791
20827
  comments: [],
@@ -20823,7 +20859,7 @@ const createComment = async (bundle) => {
20823
20859
  }
20824
20860
  }
20825
20861
  }
20826
- fireEvent('comment.created', data);
20862
+ fireEvent('local.comment.created', data);
20827
20863
  return {
20828
20864
  data: LinkedObject.comment(comments[0]),
20829
20865
  cachedAt,
@@ -20979,8 +21015,7 @@ const deleteComment = async (commentId, permanent = false) => {
20979
21015
  }
20980
21016
  else {
20981
21017
  const post = await getPost$1(comment.data.referenceId);
20982
- // @TODO: Need to separate Local / MQTT later
20983
- fireEvent('post.updated', {
21018
+ fireEvent('local.post.updated', {
20984
21019
  posts: [post.data],
20985
21020
  categories: [],
20986
21021
  comments: [],
@@ -20992,8 +21027,7 @@ const deleteComment = async (commentId, permanent = false) => {
20992
21027
  users: [],
20993
21028
  });
20994
21029
  }
20995
- // @TODO: Need to separate Local / MQTT later
20996
- fireEvent('comment.deleted', {
21030
+ fireEvent('local.comment.deleted', {
20997
21031
  comments: [deleted],
20998
21032
  commentChildren: [],
20999
21033
  files: [],
@@ -21305,125 +21339,421 @@ const getComment = (commentId, callback) => {
21305
21339
  };
21306
21340
  /* end_public_function */
21307
21341
 
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) => {
21342
+ const convertToInternalComment = (commentPayload) => {
21343
+ const { comments } = commentPayload;
21344
+ return Object.assign(Object.assign({}, commentPayload), { comments: comments.map(comment => {
21345
+ if (comment.hasOwnProperty('myReactions'))
21346
+ return comment;
21347
+ // Sometimes `myReactions` field will not come with BE response because that field is empty
21348
+ // We need to put it with an empty array manually to make it show up in client side
21349
+ return Object.assign({ myReactions: [] }, comment);
21350
+ }) });
21351
+ };
21352
+
21353
+ const queryComments = async (query) => {
21354
+ const client = getActiveClient();
21355
+ client.log('comment/queryComments', query);
21356
+ const { limit = 10, includeDeleted } = query, params = __rest(query, ["limit", "includeDeleted"]);
21357
+ const options = {
21358
+ type: params.sortBy || query.limit ? 'pagination' : undefined,
21359
+ limit: query.limit,
21360
+ token: query.page,
21361
+ };
21362
+ // const filterByParentId = query.parentId !== undefined
21363
+ // API-FIX: parameters should be querystring. (1)
21364
+ // API-FIX: backend should answer Amity.Response (2)
21365
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.CommentPayload>>>(
21366
+ const { data } = await client.http.get(`/api/v3/comments`, {
21367
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
21368
+ // filterByParentId, API-FIX: backend does not support this boolean LOL. what the hell seriously.
21369
+ options }),
21370
+ });
21371
+ // API-FIX: backend should answer Amity.Response (2)
21372
+ // const { paging, comments } = unwrapPayload(data)
21373
+ const { paging } = data, payload = __rest(data, ["paging"]);
21374
+ const processedData = convertToInternalComment(payload);
21375
+ const { comments } = processedData;
21376
+ const cachedAt = client.cache && Date.now();
21377
+ if (client.cache) {
21378
+ ingestInCache(processedData, { cachedAt });
21379
+ const cacheKey = ['comment', 'query', Object.assign(Object.assign({}, params), { options: { limit } })];
21380
+ pushToCache(cacheKey, { comments: comments.map(getResolver('comment')), paging });
21381
+ }
21382
+ return { data: comments, cachedAt, paging };
21383
+ };
21384
+
21385
+ /* begin_public_function
21386
+ id: comment.query
21387
+ */
21388
+ /**
21389
+ * ```js
21390
+ * import { getComments } from '@amityco/ts-sdk-react-native'
21391
+ *
21392
+ * let comments = []
21393
+ * const unsub = getComments({
21394
+ * referenceType: Amity.InternalComment['referenceType'];
21395
+ * referenceId: Amity.InternalComment['referenceId'];
21396
+ * }, response => merge(comments, response.data))
21397
+ * ```
21398
+ *
21399
+ * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
21400
+ *
21401
+ * @param referenceType the type of the target
21402
+ * @param referenceId the ID of the target
21403
+ * @param callback the function to call when new data are available
21404
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
21405
+ *
21406
+ * @category Comments Live Collection
21407
+ */
21408
+ const getComments = (params, callback, config) => {
21409
+ const { log, cache } = getActiveClient();
21410
+ if (!cache) {
21411
+ console.log('For using Live Collection feature you need to enable Cache!');
21412
+ }
21413
+ const timestamp = Date.now();
21414
+ log(`getComments(tmpid: ${timestamp}) > listen`);
21415
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
21416
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
21417
+ const disposers = [];
21418
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
21419
+ const cacheKey = [
21420
+ 'comment',
21421
+ 'collection',
21422
+ {
21423
+ referenceId: params.referenceType,
21424
+ referenceType: params.referenceId,
21425
+ parentId: (params === null || params === void 0 ? void 0 : params.parentId) || '',
21426
+ sortBy,
21427
+ },
21428
+ ];
21429
+ const responder = (data) => {
21430
+ var _a, _b;
21431
+ let comments = (_a = data.data
21432
+ .map(commentId => pullFromCache(['comment', 'get', commentId]))
21433
+ .filter(({ data }) => data.parentId === (params === null || params === void 0 ? void 0 : params.parentId))
21434
+ .filter(Boolean)
21435
+ .map(({ data }) => LinkedObject.comment(data))) !== null && _a !== void 0 ? _a : [];
21436
+ if (!params.includeDeleted) {
21437
+ comments = filterByPropEquality(comments, 'isDeleted', false);
21438
+ }
21439
+ comments = comments.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
21440
+ callback({
21441
+ onNextPage: onFetch,
21442
+ data: comments,
21443
+ hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
21444
+ loading: data.loading,
21445
+ error: data.error,
21446
+ });
21447
+ };
21448
+ const realtimeRouter = (action) => (comment) => {
21449
+ var _a;
21450
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21451
+ if (params.referenceId !== comment.referenceId ||
21452
+ params.referenceType !== comment.referenceType ||
21453
+ !collection) {
21454
+ return;
21455
+ }
21456
+ if (action === 'onCreate') {
21457
+ collection.data = [...new Set([comment.commentId, ...collection.data])];
21458
+ }
21459
+ else if (action === 'onDelete') {
21460
+ collection.data = collection.data.filter(p => p !== comment.commentId);
21461
+ }
21462
+ pushToCache(cacheKey, collection);
21463
+ responder(collection);
21464
+ };
21465
+ const onFetch = (initial = false) => {
21466
+ var _a, _b, _c;
21467
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21468
+ const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
21469
+ if (!initial && comments.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
21470
+ return;
21471
+ const query = createQuery(queryComments, Object.assign(Object.assign({}, queryParams), { limit: queryLimit, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
21472
+ runQuery(query, ({ data: result, error, loading, paging }) => {
21473
+ const page = paging === null || paging === void 0 ? void 0 : paging.next;
21474
+ const data = {
21475
+ loading,
21476
+ error,
21477
+ params: { page },
21478
+ data: comments,
21479
+ };
21480
+ if (result) {
21481
+ data.data = initial
21482
+ ? result.map(getResolver('comment')) // Replace a collection list with new data from BE
21483
+ : [...new Set([...comments, ...result.map(getResolver('comment'))])];
21484
+ }
21485
+ pushToCache(cacheKey, data);
21486
+ responder(data);
21487
+ }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
21488
+ };
21489
+ disposers.push(onCommentCreated(realtimeRouter('onCreate')), onCommentUpdated(realtimeRouter('onUpdate')), onCommentDeleted(realtimeRouter('onDelete')), onCommentFlagged(realtimeRouter('onFlagged')), onCommentUnflagged(realtimeRouter('onUnflagged')), onCommentReactionAdded(realtimeRouter('onReactionAdded')), onCommentReactionRemoved(realtimeRouter('onReactionRemoved')));
21490
+ onFetch(true);
21491
+ disposers.push(() => dropFromCache(cacheKey));
21492
+ return () => {
21493
+ log(`getComments(tmpid: ${timestamp}) > dispose`);
21494
+ disposers.forEach(fn => fn());
21495
+ };
21496
+ };
21497
+ /* end_public_function */
21498
+
21499
+ var index$5 = /*#__PURE__*/Object.freeze({
21500
+ __proto__: null,
21501
+ getCommentByIds: getCommentByIds,
21502
+ createComment: createComment,
21503
+ updateComment: updateComment,
21504
+ deleteComment: deleteComment,
21505
+ softDeleteComment: softDeleteComment,
21506
+ hardDeleteComment: hardDeleteComment,
21507
+ flagComment: flagComment,
21508
+ unflagComment: unflagComment,
21509
+ isCommentFlaggedByMe: isCommentFlaggedByMe,
21510
+ onCommentCreated: onCommentCreated,
21511
+ onCommentUpdated: onCommentUpdated,
21512
+ onCommentDeleted: onCommentDeleted,
21513
+ onCommentFlagged: onCommentFlagged,
21514
+ onCommentUnflagged: onCommentUnflagged,
21515
+ onCommentReactionAdded: onCommentReactionAdded,
21516
+ onCommentReactionRemoved: onCommentReactionRemoved,
21517
+ observeComments: observeComments,
21518
+ observeComment: observeComment,
21519
+ getComment: getComment,
21520
+ getComments: getComments
21521
+ });
21522
+
21523
+ /* begin_public_function
21524
+ id: post.get
21525
+ */
21526
+ /**
21527
+ * ```js
21528
+ * import { PostRepository } from '@amityco/ts-sdk-react-native';
21529
+ *
21530
+ * let post;
21531
+ *
21532
+ * const unsub = PostRepository.getPost(postId, response => {
21533
+ * post = response.data;
21534
+ * });
21535
+ * ```
21536
+ *
21537
+ * Observe all mutation on a given {@link Amity.Post}
21538
+ *
21539
+ * @param postId the ID of the message to observe
21540
+ * @param callback the function to call when new data are available
21541
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
21542
+ *
21543
+ * @category Post Live Object
21544
+ */
21545
+ const getPost = (postId, callback) => {
21546
+ return liveObject(postId, callback, 'postId', getPost$1, [
21547
+ onPostApproved,
21548
+ onPostDeclined,
21549
+ (callback) => {
21550
+ return onPostDeleted((post) => {
21551
+ var _a;
21552
+ let targetPost = post;
21553
+ // check if the deleted post is a child of the target post
21554
+ if (post.parentPostId === postId && post.isDeleted) {
21555
+ const parentPost = (_a = pullFromCache([
21556
+ 'post',
21557
+ 'get',
21558
+ post.parentPostId,
21559
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21560
+ if (parentPost) {
21561
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
21562
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
21563
+ // if the deleted post is a child of the target post, then the target post is the parent post
21564
+ targetPost = parentPost;
21565
+ }
21566
+ }
21567
+ callback(targetPost);
21568
+ });
21569
+ },
21570
+ onPostFlagged,
21571
+ (callback) => {
21572
+ return onPostReactionAdded((post) => {
21573
+ callback(LinkedObject.post(post));
21574
+ });
21575
+ },
21576
+ (callback) => {
21577
+ return onPostReactionRemoved((post) => {
21578
+ callback(LinkedObject.post(post));
21579
+ });
21580
+ },
21581
+ onPostUnflagged,
21582
+ onPostUpdated,
21583
+ convertEventPayload((callback) => {
21584
+ return onCommentCreated(async (comment) => {
21585
+ if (comment.referenceId === postId) {
21586
+ await getPost$1(postId);
21587
+ callback(comment);
21588
+ }
21589
+ });
21590
+ }, 'referenceId', 'post'),
21591
+ convertEventPayload((callback) => {
21592
+ return onCommentDeleted(async (comment) => {
21593
+ if (comment.referenceId === postId) {
21594
+ await getPost$1(postId);
21595
+ callback(comment);
21596
+ }
21597
+ });
21598
+ }, 'referenceId', 'post'),
21599
+ ]);
21600
+ };
21601
+ /* end_public_function */
21602
+
21603
+ /**
21604
+ * ```js
21605
+ * import { queryPosts } from '@amityco/ts-sdk-react-native'
21606
+ * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
21607
+ * ```
21608
+ *
21609
+ * Queries a paginable list of {@link Amity.Post} objects
21610
+ *
21611
+ * @param query The query parameters
21612
+ * @returns posts
21613
+ *
21614
+ * @category Post API
21615
+ * @async
21616
+ */
21617
+ const queryPosts = async (query) => {
21320
21618
  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
21619
+ client.log('post/queryPosts', query);
21620
+ const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
21621
+ const { dataTypes, matchingOnlyParentPost } = params;
21622
+ const options = (() => {
21623
+ if (page)
21624
+ return { token: page };
21625
+ if (limit)
21626
+ return { limit };
21627
+ return undefined;
21628
+ })();
21329
21629
  // API-FIX: parameters should be querystring. (1)
21330
21630
  // 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`, {
21631
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
21632
+ const { data } = await client.http.get(`/api/v4/posts`, {
21333
21633
  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 }),
21634
+ /*
21635
+ * when creating post like image, file, video BE will create 2 posts
21636
+ * 1. parent post to store text with dataType=text
21637
+ * 2. child post to store dataTypes post data
21638
+ *
21639
+ * By default, BE queries only parent post
21640
+ */
21641
+ matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
21336
21642
  });
21337
21643
  // API-FIX: backend should answer Amity.Response (2)
21338
- // const { paging, comments } = unwrapPayload(data)
21644
+ // const { paging, posts } = unwrapPayload(data)
21645
+ // unpacking
21339
21646
  const { paging } = data, payload = __rest(data, ["paging"]);
21340
- const processedData = convertToInternalComment(payload);
21341
- const { comments } = processedData;
21647
+ const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
21648
+ const { posts } = payload;
21342
21649
  const cachedAt = client.cache && Date.now();
21343
21650
  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 });
21651
+ ingestInCache(paperedPayload, { cachedAt });
21652
+ const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
21653
+ pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
21347
21654
  }
21348
- return { data: comments, cachedAt, paging };
21655
+ return { data: posts.map(LinkedObject.post), cachedAt, paging };
21349
21656
  };
21350
21657
 
21351
21658
  /* begin_public_function
21352
- id: comment.query
21659
+ id: post.query
21353
21660
  */
21354
21661
  /**
21355
21662
  * ```js
21356
- * import { getComments } from '@amityco/ts-sdk-react-native'
21663
+ * import { PostRepository } from '@amityco/ts-sdk-react-native'
21357
21664
  *
21358
- * let comments = []
21359
- * const unsub = getComments({
21360
- * referenceType: Amity.InternalComment['referenceType'];
21361
- * referenceId: Amity.InternalComment['referenceId'];
21362
- * }, response => merge(comments, response.data))
21665
+ * let posts = []
21666
+ * const unsub = PostRepository.getPosts({
21667
+ * targetType: Amity.PostTargetType,
21668
+ * targetId: Amity.Post['targetId'],
21669
+ * }, response => merge(posts, response.data))
21363
21670
  * ```
21364
21671
  *
21365
- * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
21672
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
21366
21673
  *
21367
- * @param referenceType the type of the target
21368
- * @param referenceId the ID of the target
21674
+ * @param params.targetType the type of the target
21675
+ * @param params.targetId the ID of the target
21369
21676
  * @param callback the function to call when new data are available
21677
+ * @param config
21370
21678
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
21371
21679
  *
21372
- * @category Comments Live Collection
21680
+ * @category Posts Live Collection
21373
21681
  */
21374
- const getComments = (params, callback, config) => {
21682
+ const getPosts = (params, callback, config) => {
21375
21683
  const { log, cache } = getActiveClient();
21376
21684
  if (!cache) {
21377
- console.log('For using Live Collection feature you need to enable Cache!');
21685
+ console.log(ENABLE_CACHE_MESSAGE);
21378
21686
  }
21379
21687
  const timestamp = Date.now();
21380
- log(`getComments(tmpid: ${timestamp}) > listen`);
21688
+ log(`getPosts(tmpid: ${timestamp}) > listen`);
21381
21689
  const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
21690
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
21382
21691
  const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
21383
21692
  const disposers = [];
21384
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
21385
21693
  const cacheKey = [
21386
- 'comment',
21694
+ 'post',
21387
21695
  'collection',
21388
- {
21389
- referenceId: params.referenceType,
21390
- referenceType: params.referenceId,
21391
- parentId: (params === null || params === void 0 ? void 0 : params.parentId) || '',
21392
- sortBy,
21393
- },
21696
+ { targetId: params.targetId, targetType: params.targetType },
21394
21697
  ];
21395
21698
  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))
21699
+ var _a, _b, _c;
21700
+ let posts = (_a = data.data
21701
+ .map(postId => pullFromCache(['post', 'get', postId]))
21400
21702
  .filter(Boolean)
21401
- .map(({ data }) => LinkedObject.comment(data))) !== null && _a !== void 0 ? _a : [];
21703
+ .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
21704
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
21705
+ posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
21402
21706
  if (!params.includeDeleted) {
21403
- comments = filterByPropEquality(comments, 'isDeleted', false);
21707
+ posts = filterByPropEquality(posts, 'isDeleted', false);
21708
+ }
21709
+ if (params.tags) {
21710
+ 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); }); });
21711
+ }
21712
+ if (params.targetType === 'community' && params.feedType) {
21713
+ posts = filterByFeedType(posts, params.feedType);
21714
+ }
21715
+ if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
21716
+ posts = filterByPostDataTypes(posts, params.dataTypes);
21404
21717
  }
21405
- comments = comments.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
21406
21718
  callback({
21407
21719
  onNextPage: onFetch,
21408
- data: comments,
21409
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
21720
+ data: posts,
21721
+ hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
21410
21722
  loading: data.loading,
21411
21723
  error: data.error,
21412
21724
  });
21413
21725
  };
21414
- const realtimeRouter = (action) => (comment) => {
21415
- var _a;
21726
+ const realtimeRouter = (action) => (post) => {
21727
+ var _a, _b;
21416
21728
  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) {
21729
+ if (!collection)
21420
21730
  return;
21731
+ if (post.parentPostId && post.isDeleted) {
21732
+ const parentPost = (_b = pullFromCache([
21733
+ 'post',
21734
+ 'get',
21735
+ post.parentPostId,
21736
+ ])) === null || _b === void 0 ? void 0 : _b.data;
21737
+ if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
21738
+ return;
21739
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
21740
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
21421
21741
  }
21422
- if (action === 'onCreate') {
21423
- collection.data = [...new Set([comment.commentId, ...collection.data])];
21742
+ else {
21743
+ if (params.targetId !== post.targetId)
21744
+ return;
21745
+ if (params.targetType !== post.targetType)
21746
+ return;
21424
21747
  }
21425
- else if (action === 'onDelete') {
21426
- collection.data = collection.data.filter(p => p !== comment.commentId);
21748
+ /*
21749
+ * This is not ideal, but currently this is the only way to update the
21750
+ * collection on post declined
21751
+ */
21752
+ if (action === 'onDeclined') {
21753
+ collection.data = collection.data.filter(postId => postId !== post.postId);
21754
+ }
21755
+ else {
21756
+ collection.data = [...new Set([post.postId, ...collection.data])];
21427
21757
  }
21428
21758
  pushToCache(cacheKey, collection);
21429
21759
  responder(collection);
@@ -21431,32 +21761,49 @@ const getComments = (params, callback, config) => {
21431
21761
  const onFetch = (initial = false) => {
21432
21762
  var _a, _b, _c;
21433
21763
  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))
21764
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
21765
+ if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
21436
21766
  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 }));
21767
+ 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
21768
  runQuery(query, ({ data: result, error, loading, paging }) => {
21439
- const page = paging === null || paging === void 0 ? void 0 : paging.next;
21440
21769
  const data = {
21441
21770
  loading,
21442
21771
  error,
21443
- params: { page },
21444
- data: comments,
21772
+ params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
21773
+ data: posts,
21445
21774
  };
21446
21775
  if (result) {
21447
21776
  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'))])];
21777
+ ? result.map(getResolver('post'))
21778
+ : [...new Set([...posts, ...result.map(getResolver('post'))])];
21450
21779
  }
21451
21780
  pushToCache(cacheKey, data);
21452
21781
  responder(data);
21453
21782
  }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
21454
21783
  };
21455
- disposers.push(onCommentCreated(realtimeRouter('onCreate')), onCommentUpdated(realtimeRouter('onUpdate')), onCommentDeleted(realtimeRouter('onDelete')), onCommentFlagged(realtimeRouter('onFlagged')), onCommentUnflagged(realtimeRouter('onUnflagged')), onCommentReactionAdded(realtimeRouter('onReactionAdded')), onCommentReactionRemoved(realtimeRouter('onReactionRemoved')));
21784
+ 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) => {
21785
+ return onCommentCreated(async (comment) => {
21786
+ var _a;
21787
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21788
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
21789
+ return;
21790
+ await getPost$1(comment.referenceId);
21791
+ callback(comment);
21792
+ });
21793
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')), convertEventPayload((callback) => {
21794
+ return onCommentDeleted(async (comment) => {
21795
+ var _a;
21796
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21797
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
21798
+ return;
21799
+ await getPost$1(comment.referenceId);
21800
+ callback(comment);
21801
+ });
21802
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')));
21456
21803
  onFetch(true);
21457
21804
  disposers.push(() => dropFromCache(cacheKey));
21458
21805
  return () => {
21459
- log(`getComments(tmpid: ${timestamp}) > dispose`);
21806
+ log(`getPosts(tmpid: ${timestamp}) > dispose`);
21460
21807
  disposers.forEach(fn => fn());
21461
21808
  };
21462
21809
  };
@@ -21464,26 +21811,31 @@ const getComments = (params, callback, config) => {
21464
21811
 
21465
21812
  var index$4 = /*#__PURE__*/Object.freeze({
21466
21813
  __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
21814
+ getPostByIds: getPostByIds,
21815
+ createPost: createPost,
21816
+ updatePost: updatePost,
21817
+ editPost: editPost,
21818
+ deletePost: deletePost,
21819
+ softDeletePost: softDeletePost,
21820
+ hardDeletePost: hardDeletePost,
21821
+ approvePost: approvePost,
21822
+ declinePost: declinePost,
21823
+ flagPost: flagPost,
21824
+ unflagPost: unflagPost,
21825
+ isPostFlaggedByMe: isPostFlaggedByMe,
21826
+ onPostCreated: onPostCreated,
21827
+ onPostUpdated: onPostUpdated,
21828
+ onPostDeleted: onPostDeleted,
21829
+ onPostApproved: onPostApproved,
21830
+ onPostDeclined: onPostDeclined,
21831
+ onPostFlagged: onPostFlagged,
21832
+ onPostUnflagged: onPostUnflagged,
21833
+ onPostReactionAdded: onPostReactionAdded,
21834
+ onPostReactionRemoved: onPostReactionRemoved,
21835
+ observePosts: observePosts,
21836
+ observePost: observePost,
21837
+ getPost: getPost,
21838
+ getPosts: getPosts
21487
21839
  });
21488
21840
 
21489
21841
  /* begin_public_function
@@ -21884,7 +22236,7 @@ const queryStreams = async (query) => {
21884
22236
  */
21885
22237
  /**
21886
22238
  * ```js
21887
- * import { StreamRepository } from '@amityco/ts-sdk-react-native'
22239
+ * import { StreamRepository } from '@amityco/ts-sdk'
21888
22240
  * const streams = await StreamRepository.getStreams()
21889
22241
  * ```
21890
22242
  *
@@ -22315,7 +22667,7 @@ var index$2 = /*#__PURE__*/Object.freeze({
22315
22667
  getPoll: getPoll
22316
22668
  });
22317
22669
 
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-----";
22670
+ 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
22671
  /*
22320
22672
  * The crypto algorithm used for importing key and signing string
22321
22673
  */
@@ -23460,7 +23812,7 @@ class StoryLiveCollectionController extends LiveCollectionController {
23460
23812
  this.queryStreamController = new StoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
23461
23813
  this.paginationController = paginationController;
23462
23814
  this.callback = callback.bind(this);
23463
- this.loadPage(true);
23815
+ this.loadPage({ initial: true });
23464
23816
  }
23465
23817
  setup() {
23466
23818
  var _a;
@@ -23642,7 +23994,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
23642
23994
  this.queryStreamController = new GlobalStoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
23643
23995
  this.paginationController = paginationController;
23644
23996
  this.callback = callback.bind(this);
23645
- this.loadPage(true);
23997
+ this.loadPage({ initial: true });
23646
23998
  }
23647
23999
  setup() {
23648
24000
  var _a;
@@ -23678,7 +24030,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
23678
24030
  return rest;
23679
24031
  });
23680
24032
  this.callback({
23681
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
24033
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
23682
24034
  data,
23683
24035
  hasNextPage: !!this.paginationController.getNextToken(),
23684
24036
  loading,
@@ -23788,7 +24140,7 @@ exports.API_REGIONS = API_REGIONS;
23788
24140
  exports.CategoryRepository = index$7;
23789
24141
  exports.ChannelRepository = index$b;
23790
24142
  exports.Client = index$k;
23791
- exports.CommentRepository = index$4;
24143
+ exports.CommentRepository = index$5;
23792
24144
  exports.CommunityPostSettingMaps = CommunityPostSettingMaps;
23793
24145
  exports.CommunityPostSettings = CommunityPostSettings;
23794
24146
  exports.CommunityRepository = index$8;
@@ -23802,7 +24154,7 @@ exports.MessageContentType = MessageContentType;
23802
24154
  exports.MessageRepository = index$f;
23803
24155
  exports.PollRepository = index$2;
23804
24156
  exports.PostContentType = PostContentType;
23805
- exports.PostRepository = index$5;
24157
+ exports.PostRepository = index$4;
23806
24158
  exports.ReactionRepository = index$g;
23807
24159
  exports.StoryRepository = index;
23808
24160
  exports.StreamRepository = index$3;