@amityco/ts-sdk-react-native 6.23.0 → 6.24.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 (80) hide show
  1. package/dist/@types/core/events.d.ts +5 -0
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/domains/community.d.ts +15 -0
  4. package/dist/@types/domains/community.d.ts.map +1 -1
  5. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  6. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  7. package/dist/commentRepository/internalApi/createComment.d.ts.map +1 -1
  8. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts +14 -0
  9. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -0
  10. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts +9 -0
  11. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts.map +1 -0
  12. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +15 -0
  13. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -0
  14. package/dist/communityRepository/observers/getCommunities/enums.d.ts +6 -0
  15. package/dist/communityRepository/observers/getCommunities/enums.d.ts.map +1 -0
  16. package/dist/communityRepository/observers/index.d.ts +1 -0
  17. package/dist/communityRepository/observers/index.d.ts.map +1 -1
  18. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts +14 -0
  19. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts.map +1 -0
  20. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts +9 -0
  21. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -0
  22. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +15 -0
  23. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -0
  24. package/dist/communityRepository/observers/searchCommunities/enums.d.ts +6 -0
  25. package/dist/communityRepository/observers/searchCommunities/enums.d.ts.map +1 -0
  26. package/dist/communityRepository/observers/searchCommunities.d.ts +20 -0
  27. package/dist/communityRepository/observers/searchCommunities.d.ts.map +1 -0
  28. package/dist/core/events.d.ts +3 -3
  29. package/dist/core/events.d.ts.map +1 -1
  30. package/dist/core/liveCollection/LiveCollectionController.d.ts +4 -1
  31. package/dist/core/liveCollection/LiveCollectionController.d.ts.map +1 -1
  32. package/dist/index.cjs.js +582 -334
  33. package/dist/index.esm.js +573 -325
  34. package/dist/index.umd.js +4 -4
  35. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts +12 -0
  36. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts.map +1 -0
  37. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts +12 -0
  38. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts.map +1 -0
  39. package/dist/marker/events/onUserFeedMarkerUpdated.d.ts.map +1 -1
  40. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts +1 -1
  41. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts.map +1 -1
  42. package/dist/postRepository/observers/getPost.d.ts.map +1 -1
  43. package/dist/postRepository/observers/getPosts.d.ts.map +1 -1
  44. package/package.json +1 -1
  45. package/src/@types/core/events.ts +8 -0
  46. package/src/@types/domains/community.ts +25 -0
  47. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +2 -2
  48. package/src/channelRepository/observers/getChannel.ts +2 -2
  49. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +7 -7
  50. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +6 -3
  51. package/src/commentRepository/api/createComment.ts +2 -2
  52. package/src/commentRepository/api/deleteComment.ts +2 -4
  53. package/src/commentRepository/events/utils.ts +1 -1
  54. package/src/commentRepository/internalApi/createComment.ts +3 -2
  55. package/src/commentRepository/internalApi/deleteComment.ts +2 -2
  56. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +147 -0
  57. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +31 -0
  58. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +86 -0
  59. package/src/communityRepository/observers/getCommunities/enums.ts +5 -0
  60. package/src/communityRepository/observers/index.ts +1 -0
  61. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +129 -0
  62. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +31 -0
  63. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +81 -0
  64. package/src/communityRepository/observers/searchCommunities/enums.ts +5 -0
  65. package/src/communityRepository/observers/searchCommunities.ts +56 -0
  66. package/src/core/liveCollection/LiveCollectionController.ts +6 -3
  67. package/src/marker/events/onChannelUnreadUpdatedLocal.ts +29 -0
  68. package/src/marker/events/onSubChannelMarkerFetched.ts +1 -1
  69. package/src/marker/events/onSubChannelUnreadUpdatedLocal.ts +29 -0
  70. package/src/marker/events/onUserFeedMarkerUpdated.ts +3 -4
  71. package/src/marker/utils/reCalculateChannelUnreadInfo.ts +7 -3
  72. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +3 -3
  73. package/src/postRepository/api/editPost.ts +1 -1
  74. package/src/postRepository/api/updatePost.ts +1 -1
  75. package/src/postRepository/observers/getPost.ts +26 -0
  76. package/src/postRepository/observers/getPosts.ts +31 -0
  77. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +2 -2
  78. package/src/storyRepository/observers/getStoriesByTargetIds/StoryLiveCollectionController.ts +1 -1
  79. package/src/subChannelRepository/observers/getSubChannel.ts +2 -2
  80. package/src/subChannelRepository/observers/getSubChannels/SubChannelLiveCollectionController.ts +4 -4
package/dist/index.cjs.js CHANGED
@@ -117,8 +117,8 @@ const PostContentType = Object.freeze({
117
117
 
118
118
  function getVersion() {
119
119
  try {
120
- // the string ''v6.23.0-cjs'' should be replaced by actual value by @rollup/plugin-replace
121
- return 'v6.23.0-cjs';
120
+ // the string ''v6.24.0-cjs'' should be replaced by actual value by @rollup/plugin-replace
121
+ return 'v6.24.0-cjs';
122
122
  }
123
123
  catch (error) {
124
124
  return '__dev__';
@@ -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
  };
@@ -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
  };
@@ -15443,7 +15447,7 @@ class LiveCollectionController {
15443
15447
  this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
15444
15448
  }
15445
15449
  }
15446
- loadPage(initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
15450
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
15447
15451
  this.setup();
15448
15452
  this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
15449
15453
  if (initial) {
@@ -15513,7 +15517,7 @@ class MessageLiveCollectionController extends LiveCollectionController {
15513
15517
  this.query = query;
15514
15518
  this.queryStreamController = new MessageQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMessagePayload, this.paginationController);
15515
15519
  this.callback = callback.bind(this);
15516
- this.loadPage(true);
15520
+ this.loadPage({ initial: true });
15517
15521
  }
15518
15522
  setup() {
15519
15523
  var _a;
@@ -15561,8 +15565,8 @@ class MessageLiveCollectionController extends LiveCollectionController {
15561
15565
  if (!this.shouldNotify(data) && origin === 'event')
15562
15566
  return;
15563
15567
  this.callback({
15564
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
15565
- onPrevPage: () => this.loadPage(false, "prev" /* Amity.LiveCollectionPageDirection.PREV */),
15568
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
15569
+ onPrevPage: () => this.loadPage({ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */ }),
15566
15570
  data,
15567
15571
  hasNextPage: !!this.paginationController.getNextToken(),
15568
15572
  hasPrevPage: !!this.paginationController.getPrevToken(),
@@ -15844,6 +15848,24 @@ var index$f = /*#__PURE__*/Object.freeze({
15844
15848
  convertQueryParams: convertQueryParams$1
15845
15849
  });
15846
15850
 
15851
+ /**
15852
+ * Internal used only
15853
+ *
15854
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
15855
+ *
15856
+ * @param callback The function to call when the event was fired
15857
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
15858
+ *
15859
+ * @category MessageMarker Events
15860
+ */
15861
+ const onSubChannelUnreadUpdatedLocal = (callback) => {
15862
+ const client = getActiveClient();
15863
+ const filter = (payload) => {
15864
+ callback(payload);
15865
+ };
15866
+ return createEventSubscriber(client, 'subChannelMarker/onSubChannelUnreadUpdatedLocal', 'local.subChannelUnread.updated', filter);
15867
+ };
15868
+
15847
15869
  /* begin_public_function
15848
15870
  id: subchannel.get
15849
15871
  */
@@ -15996,7 +16018,7 @@ const getSubChannel = (subChannelId, callback) => {
15996
16018
  };
15997
16019
  return onMessageDeleted(updateMessagePreview);
15998
16020
  }, 'subChannelId', 'subChannel'),
15999
- convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
16021
+ convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
16000
16022
  ], {
16001
16023
  forceDispatch: true,
16002
16024
  });
@@ -16086,7 +16108,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16086
16108
  this.query = query;
16087
16109
  this.queryStreamController = new SubChannelQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareSubChannelPayload);
16088
16110
  this.callback = callback.bind(this);
16089
- this.loadPage(true);
16111
+ this.loadPage({ initial: true });
16090
16112
  }
16091
16113
  setup() {
16092
16114
  var _a;
@@ -16263,7 +16285,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16263
16285
  action: 'onUpdate',
16264
16286
  },
16265
16287
  {
16266
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
16288
+ fn: convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
16267
16289
  action: 'onUpdate',
16268
16290
  },
16269
16291
  ]);
@@ -16281,7 +16303,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
16281
16303
  if (!this.shouldNotify(data) && origin === 'event')
16282
16304
  return;
16283
16305
  this.callback({
16284
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
16306
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
16285
16307
  data,
16286
16308
  hasNextPage: !!this.paginationController.getNextToken(),
16287
16309
  loading,
@@ -16421,6 +16443,24 @@ var index$e = /*#__PURE__*/Object.freeze({
16421
16443
  stopMessageReceiptSync: stopMessageReceiptSync
16422
16444
  });
16423
16445
 
16446
+ /**
16447
+ * Internal used only
16448
+ *
16449
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
16450
+ *
16451
+ * @param callback The function to call when the event was fired
16452
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
16453
+ *
16454
+ * @category MessageMarker Events
16455
+ */
16456
+ const onChannelUnreadUpdatedLocal = (callback) => {
16457
+ const client = getActiveClient();
16458
+ const filter = (payload) => {
16459
+ callback(payload);
16460
+ };
16461
+ return createEventSubscriber(client, 'channelMarker/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
16462
+ };
16463
+
16424
16464
  /* begin_public_function
16425
16465
  id: channel.get
16426
16466
  */
@@ -16596,7 +16636,7 @@ const getChannel = (channelId, callback) => {
16596
16636
  return onSubChannelUpdated(updateMessagePreview);
16597
16637
  }, 'channelId', 'channel'),
16598
16638
  convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
16599
- convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
16639
+ convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
16600
16640
  ], {
16601
16641
  forceDispatch: true,
16602
16642
  });
@@ -16756,7 +16796,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
16756
16796
  }, paginationController);
16757
16797
  this.paginationController = paginationController;
16758
16798
  this.callback = callback.bind(this);
16759
- this.loadPage(true);
16799
+ this.loadPage({ initial: true });
16760
16800
  }
16761
16801
  setup() {
16762
16802
  var _a;
@@ -16795,7 +16835,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
16795
16835
  return;
16796
16836
  this.callback({
16797
16837
  onNextPage: this.paginationController instanceof ChannelPaginationController
16798
- ? () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */)
16838
+ ? () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ })
16799
16839
  : undefined,
16800
16840
  data,
16801
16841
  hasNextPage: this.paginationController instanceof ChannelPaginationController
@@ -17075,10 +17115,6 @@ class ChannelLiveCollectionController extends LiveCollectionController {
17075
17115
  }, 'channelId', 'channel'),
17076
17116
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17077
17117
  },
17078
- {
17079
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
17080
- action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17081
- },
17082
17118
  {
17083
17119
  fn: convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
17084
17120
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -17104,6 +17140,10 @@ class ChannelLiveCollectionController extends LiveCollectionController {
17104
17140
  },
17105
17141
  action: "onResolve" /* Amity.ChannelActionType.OnResolve */,
17106
17142
  },
17143
+ {
17144
+ fn: convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
17145
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
17146
+ },
17107
17147
  ];
17108
17148
  if (this.paginationController instanceof PaginationController) {
17109
17149
  return [
@@ -17318,7 +17358,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
17318
17358
  this.query = query;
17319
17359
  this.queryStreamController = new ChannelMemberQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareChannelPayload);
17320
17360
  this.callback = callback.bind(this);
17321
- this.loadPage(true);
17361
+ this.loadPage({ initial: true });
17322
17362
  }
17323
17363
  setup() {
17324
17364
  var _a;
@@ -17360,7 +17400,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
17360
17400
  if (!this.shouldNotify(data) && origin === 'event')
17361
17401
  return;
17362
17402
  this.callback({
17363
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
17403
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
17364
17404
  data,
17365
17405
  hasNextPage: !!this.paginationController.getNextToken(),
17366
17406
  loading,
@@ -18468,6 +18508,181 @@ const observeCommunity = (communityId, callback) => {
18468
18508
  };
18469
18509
  };
18470
18510
 
18511
+ /**
18512
+ * TODO: handle cache receive cache option, and cache policy
18513
+ * TODO: check if querybyIds is supported
18514
+ */
18515
+ class CommunitiesPaginationController extends PaginationController {
18516
+ async getRequest(queryParams, token) {
18517
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
18518
+ const options = token ? { token } : { limit };
18519
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
18520
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
18521
+ });
18522
+ return queryResponse;
18523
+ }
18524
+ }
18525
+
18526
+ class CommunitiesQueryStreamController extends QueryStreamController {
18527
+ constructor(query, cacheKey, notifyChange, preparePayload) {
18528
+ super(query, cacheKey);
18529
+ this.notifyChange = notifyChange;
18530
+ this.preparePayload = preparePayload;
18531
+ }
18532
+ async saveToMainDB(response) {
18533
+ const processedPayload = await this.preparePayload(response);
18534
+ const client = getActiveClient();
18535
+ const cachedAt = client.cache && Date.now();
18536
+ if (client.cache) {
18537
+ ingestInCache(processedPayload, { cachedAt });
18538
+ }
18539
+ }
18540
+ appendToQueryStream(response, direction, refresh = false) {
18541
+ var _a, _b;
18542
+ if (refresh) {
18543
+ pushToCache(this.cacheKey, {
18544
+ data: response.communities.map(getResolver('community')),
18545
+ });
18546
+ }
18547
+ else {
18548
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18549
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
18550
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
18551
+ }
18552
+ }
18553
+ reactor(action) {
18554
+ return (community) => {
18555
+ var _a;
18556
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18557
+ if (!collection)
18558
+ return;
18559
+ pushToCache(this.cacheKey, collection);
18560
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
18561
+ };
18562
+ }
18563
+ subscribeRTE(createSubscriber) {
18564
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
18565
+ }
18566
+ }
18567
+
18568
+ var EnumCommunityActions;
18569
+ (function (EnumCommunityActions) {
18570
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
18571
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
18572
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
18573
+ })(EnumCommunityActions || (EnumCommunityActions = {}));
18574
+
18575
+ /* eslint-disable no-use-before-define */
18576
+ class SearchCommunityLiveCollectionController extends LiveCollectionController {
18577
+ constructor(query, callback) {
18578
+ const queryStreamId = hash__default["default"](query);
18579
+ const cacheKey = ['community', 'collection', queryStreamId];
18580
+ const paginationController = new CommunitiesPaginationController(query);
18581
+ super(paginationController, queryStreamId, cacheKey, callback);
18582
+ this.query = query;
18583
+ this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
18584
+ this.callback = callback.bind(this);
18585
+ this.loadPage({ initial: true });
18586
+ }
18587
+ setup() {
18588
+ var _a;
18589
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18590
+ if (!collection) {
18591
+ pushToCache(this.cacheKey, {
18592
+ data: [],
18593
+ params: {},
18594
+ });
18595
+ }
18596
+ }
18597
+ async persistModel(queryPayload) {
18598
+ await this.queryStreamController.saveToMainDB(queryPayload);
18599
+ }
18600
+ persistQueryStream({ response, direction, refresh, }) {
18601
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
18602
+ }
18603
+ startSubscription() {
18604
+ return this.queryStreamController.subscribeRTE([
18605
+ { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
18606
+ { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
18607
+ ]);
18608
+ }
18609
+ notifyChange({ origin, loading, error }) {
18610
+ var _a, _b;
18611
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
18612
+ if (!collection)
18613
+ return;
18614
+ const data = this.applyFilter((_b = collection.data
18615
+ .map(id => pullFromCache(['community', 'get', id]))
18616
+ .filter(Boolean)
18617
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
18618
+ if (!this.shouldNotify(data) && origin === 'event')
18619
+ return;
18620
+ this.callback({
18621
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
18622
+ data,
18623
+ hasNextPage: !!this.paginationController.getNextToken(),
18624
+ loading,
18625
+ error,
18626
+ });
18627
+ }
18628
+ applyFilter(data) {
18629
+ const { userId } = getActiveClient();
18630
+ let communities = data;
18631
+ if (this.query.includeDeleted) {
18632
+ communities = filterByPropEquality(communities, 'isDeleted', false);
18633
+ }
18634
+ if (this.query.categoryId) {
18635
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
18636
+ }
18637
+ if (this.query.tags) {
18638
+ communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = this.query.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
18639
+ }
18640
+ if (this.query.membership && userId) {
18641
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
18642
+ }
18643
+ return communities;
18644
+ }
18645
+ }
18646
+
18647
+ /* begin_public_function
18648
+ id: community.query
18649
+ */
18650
+ /**
18651
+ * ```js
18652
+ * import { CommunityRepository } from '@amityco/ts-sdk'
18653
+ *
18654
+ * let communities = []
18655
+ * const unsub = CommunityRepository.searchCommunities({
18656
+ * displayName: Amity.Community['displayName'],
18657
+ * }, response => merge(communities, response.data))
18658
+ * ```
18659
+ *
18660
+ * Observe all mutations on a list of {@link Amity.Community}s
18661
+ *
18662
+ * @param params for querying communities
18663
+ * @param callback the function to call when new data are available
18664
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
18665
+ *
18666
+ * @category Community Live Collection
18667
+ */
18668
+ const searchCommunities = (params, callback, config) => {
18669
+ const { log, cache } = getActiveClient();
18670
+ if (!cache) {
18671
+ console.log(ENABLE_CACHE_MESSAGE);
18672
+ }
18673
+ const timestamp = Date.now();
18674
+ log(`searchCommunities(tmpid: ${timestamp}) > listen`);
18675
+ const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
18676
+ const disposers = searchCommunitiesLiveCollection.startSubscription();
18677
+ const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
18678
+ disposers.push(() => dropFromCache(cacheKey));
18679
+ return () => {
18680
+ log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
18681
+ disposers.forEach(fn => fn());
18682
+ };
18683
+ };
18684
+ /* end_public_function */
18685
+
18471
18686
  /**
18472
18687
  * ```js
18473
18688
  * import { queryCommunities } from '@amityco/ts-sdk-react-native'
@@ -19397,6 +19612,7 @@ var index$8 = /*#__PURE__*/Object.freeze({
19397
19612
  onCommunityUpdated: onCommunityUpdated,
19398
19613
  onCommunityDeleted: onCommunityDeleted,
19399
19614
  observeCommunity: observeCommunity,
19615
+ searchCommunities: searchCommunities,
19400
19616
  getCommunities: getCommunities,
19401
19617
  getCommunity: getCommunity,
19402
19618
  getTrendingCommunities: getTrendingCommunities,
@@ -19983,7 +20199,7 @@ const updatePost = async (postId, patch) => {
19983
20199
  const cachedAt = client.cache && Date.now();
19984
20200
  if (client.cache)
19985
20201
  ingestInCache(data, { cachedAt });
19986
- fireEvent('post.updated', data);
20202
+ fireEvent('local.post.updated', data);
19987
20203
  const { posts } = data;
19988
20204
  return {
19989
20205
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -20020,7 +20236,7 @@ const editPost = async (postId, patch) => {
20020
20236
  const cachedAt = client.cache && Date.now();
20021
20237
  if (client.cache)
20022
20238
  ingestInCache(data, { cachedAt });
20023
- fireEvent('post.updated', data);
20239
+ fireEvent('local.post.updated', data);
20024
20240
  const { posts } = data;
20025
20241
  return {
20026
20242
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -20394,307 +20610,23 @@ const observePost = (postId, callback, policy = 'cache_then_server') => {
20394
20610
  };
20395
20611
 
20396
20612
  /* begin_public_function
20397
- id: post.get
20613
+ id: comment.get_by_ids
20398
20614
  */
20399
20615
  /**
20400
20616
  * ```js
20401
- * import { PostRepository } from '@amityco/ts-sdk-react-native';
20402
- *
20403
- * let post;
20404
- *
20405
- * const unsub = PostRepository.getPost(postId, response => {
20406
- * post = response.data;
20407
- * });
20408
- * ```
20409
- *
20410
- * Observe all mutation on a given {@link Amity.Post}
20411
- *
20412
- * @param postId the ID of the message to observe
20413
- * @param callback the function to call when new data are available
20414
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
20415
- *
20416
- * @category Post Live Object
20417
- */
20418
- const getPost = (postId, callback) => {
20419
- return liveObject(postId, callback, 'postId', getPost$1, [
20420
- onPostApproved,
20421
- onPostDeclined,
20422
- (callback) => {
20423
- return onPostDeleted((post) => {
20424
- var _a;
20425
- let targetPost = post;
20426
- // check if the deleted post is a child of the target post
20427
- if (post.parentPostId === postId && post.isDeleted) {
20428
- const parentPost = (_a = pullFromCache([
20429
- 'post',
20430
- 'get',
20431
- post.parentPostId,
20432
- ])) === null || _a === void 0 ? void 0 : _a.data;
20433
- if (parentPost) {
20434
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
20435
- pushToCache(['post', 'get', parentPost.postId], parentPost);
20436
- // if the deleted post is a child of the target post, then the target post is the parent post
20437
- targetPost = parentPost;
20438
- }
20439
- }
20440
- callback(targetPost);
20441
- });
20442
- },
20443
- onPostFlagged,
20444
- (callback) => {
20445
- return onPostReactionAdded((post) => {
20446
- callback(LinkedObject.post(post));
20447
- });
20448
- },
20449
- (callback) => {
20450
- return onPostReactionRemoved((post) => {
20451
- callback(LinkedObject.post(post));
20452
- });
20453
- },
20454
- onPostUnflagged,
20455
- onPostUpdated,
20456
- ]);
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 })
20617
+ * import { CommentRepository } from '@amityco/ts-sdk-react-native'
20618
+ * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
20464
20619
  * ```
20465
20620
  *
20466
- * Queries a paginable list of {@link Amity.Post} objects
20621
+ * Fetches a collection of {@link Amity.Comment} objects
20467
20622
  *
20468
- * @param query The query parameters
20469
- * @returns posts
20623
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
20624
+ * @returns the associated collection of {@link Amity.Comment} objects
20470
20625
  *
20471
- * @category Post API
20626
+ * @category Comment API
20472
20627
  * @async
20473
20628
  */
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) => {
20629
+ const getCommentByIds = async (commentIds) => {
20698
20630
  const client = getActiveClient();
20699
20631
  client.log('comment/getCommentByIds', commentIds);
20700
20632
  const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
@@ -20785,7 +20717,7 @@ const createComment = async (bundle) => {
20785
20717
  ingestInCache(data, { cachedAt });
20786
20718
  if (['post', 'content'].includes(bundle.referenceType)) {
20787
20719
  const post = await getPost$1(bundle.referenceId);
20788
- fireEvent('post.updated', {
20720
+ fireEvent('local.post.updated', {
20789
20721
  posts: [post.data],
20790
20722
  categories: [],
20791
20723
  comments: [],
@@ -20823,7 +20755,7 @@ const createComment = async (bundle) => {
20823
20755
  }
20824
20756
  }
20825
20757
  }
20826
- fireEvent('comment.created', data);
20758
+ fireEvent('local.comment.created', data);
20827
20759
  return {
20828
20760
  data: LinkedObject.comment(comments[0]),
20829
20761
  cachedAt,
@@ -20979,8 +20911,7 @@ const deleteComment = async (commentId, permanent = false) => {
20979
20911
  }
20980
20912
  else {
20981
20913
  const post = await getPost$1(comment.data.referenceId);
20982
- // @TODO: Need to separate Local / MQTT later
20983
- fireEvent('post.updated', {
20914
+ fireEvent('local.post.updated', {
20984
20915
  posts: [post.data],
20985
20916
  categories: [],
20986
20917
  comments: [],
@@ -20992,8 +20923,7 @@ const deleteComment = async (commentId, permanent = false) => {
20992
20923
  users: [],
20993
20924
  });
20994
20925
  }
20995
- // @TODO: Need to separate Local / MQTT later
20996
- fireEvent('comment.deleted', {
20926
+ fireEvent('local.comment.deleted', {
20997
20927
  comments: [deleted],
20998
20928
  commentChildren: [],
20999
20929
  files: [],
@@ -21462,7 +21392,7 @@ const getComments = (params, callback, config) => {
21462
21392
  };
21463
21393
  /* end_public_function */
21464
21394
 
21465
- var index$4 = /*#__PURE__*/Object.freeze({
21395
+ var index$5 = /*#__PURE__*/Object.freeze({
21466
21396
  __proto__: null,
21467
21397
  getCommentByIds: getCommentByIds,
21468
21398
  createComment: createComment,
@@ -21486,6 +21416,324 @@ var index$4 = /*#__PURE__*/Object.freeze({
21486
21416
  getComments: getComments
21487
21417
  });
21488
21418
 
21419
+ /* begin_public_function
21420
+ id: post.get
21421
+ */
21422
+ /**
21423
+ * ```js
21424
+ * import { PostRepository } from '@amityco/ts-sdk-react-native';
21425
+ *
21426
+ * let post;
21427
+ *
21428
+ * const unsub = PostRepository.getPost(postId, response => {
21429
+ * post = response.data;
21430
+ * });
21431
+ * ```
21432
+ *
21433
+ * Observe all mutation on a given {@link Amity.Post}
21434
+ *
21435
+ * @param postId the ID of the message to observe
21436
+ * @param callback the function to call when new data are available
21437
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
21438
+ *
21439
+ * @category Post Live Object
21440
+ */
21441
+ const getPost = (postId, callback) => {
21442
+ return liveObject(postId, callback, 'postId', getPost$1, [
21443
+ onPostApproved,
21444
+ onPostDeclined,
21445
+ (callback) => {
21446
+ return onPostDeleted((post) => {
21447
+ var _a;
21448
+ let targetPost = post;
21449
+ // check if the deleted post is a child of the target post
21450
+ if (post.parentPostId === postId && post.isDeleted) {
21451
+ const parentPost = (_a = pullFromCache([
21452
+ 'post',
21453
+ 'get',
21454
+ post.parentPostId,
21455
+ ])) === null || _a === void 0 ? void 0 : _a.data;
21456
+ if (parentPost) {
21457
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
21458
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
21459
+ // if the deleted post is a child of the target post, then the target post is the parent post
21460
+ targetPost = parentPost;
21461
+ }
21462
+ }
21463
+ callback(targetPost);
21464
+ });
21465
+ },
21466
+ onPostFlagged,
21467
+ (callback) => {
21468
+ return onPostReactionAdded((post) => {
21469
+ callback(LinkedObject.post(post));
21470
+ });
21471
+ },
21472
+ (callback) => {
21473
+ return onPostReactionRemoved((post) => {
21474
+ callback(LinkedObject.post(post));
21475
+ });
21476
+ },
21477
+ onPostUnflagged,
21478
+ onPostUpdated,
21479
+ convertEventPayload((callback) => {
21480
+ return onCommentCreated(async (comment) => {
21481
+ if (comment.referenceId === postId) {
21482
+ await getPost$1(postId);
21483
+ callback(comment);
21484
+ }
21485
+ });
21486
+ }, 'referenceId', 'post'),
21487
+ convertEventPayload((callback) => {
21488
+ return onCommentDeleted(async (comment) => {
21489
+ if (comment.referenceId === postId) {
21490
+ await getPost$1(postId);
21491
+ callback(comment);
21492
+ }
21493
+ });
21494
+ }, 'referenceId', 'post'),
21495
+ ]);
21496
+ };
21497
+ /* end_public_function */
21498
+
21499
+ /**
21500
+ * ```js
21501
+ * import { queryPosts } from '@amityco/ts-sdk-react-native'
21502
+ * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
21503
+ * ```
21504
+ *
21505
+ * Queries a paginable list of {@link Amity.Post} objects
21506
+ *
21507
+ * @param query The query parameters
21508
+ * @returns posts
21509
+ *
21510
+ * @category Post API
21511
+ * @async
21512
+ */
21513
+ const queryPosts = async (query) => {
21514
+ const client = getActiveClient();
21515
+ client.log('post/queryPosts', query);
21516
+ const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
21517
+ const { dataTypes, matchingOnlyParentPost } = params;
21518
+ const options = (() => {
21519
+ if (page)
21520
+ return { token: page };
21521
+ if (limit)
21522
+ return { limit };
21523
+ return undefined;
21524
+ })();
21525
+ // API-FIX: parameters should be querystring. (1)
21526
+ // API-FIX: backend should answer Amity.Response (2)
21527
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
21528
+ const { data } = await client.http.get(`/api/v4/posts`, {
21529
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
21530
+ /*
21531
+ * when creating post like image, file, video BE will create 2 posts
21532
+ * 1. parent post to store text with dataType=text
21533
+ * 2. child post to store dataTypes post data
21534
+ *
21535
+ * By default, BE queries only parent post
21536
+ */
21537
+ matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
21538
+ });
21539
+ // API-FIX: backend should answer Amity.Response (2)
21540
+ // const { paging, posts } = unwrapPayload(data)
21541
+ // unpacking
21542
+ const { paging } = data, payload = __rest(data, ["paging"]);
21543
+ const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
21544
+ const { posts } = payload;
21545
+ const cachedAt = client.cache && Date.now();
21546
+ if (client.cache) {
21547
+ ingestInCache(paperedPayload, { cachedAt });
21548
+ const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
21549
+ pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
21550
+ }
21551
+ return { data: posts.map(LinkedObject.post), cachedAt, paging };
21552
+ };
21553
+
21554
+ /* begin_public_function
21555
+ id: post.query
21556
+ */
21557
+ /**
21558
+ * ```js
21559
+ * import { PostRepository } from '@amityco/ts-sdk-react-native'
21560
+ *
21561
+ * let posts = []
21562
+ * const unsub = PostRepository.getPosts({
21563
+ * targetType: Amity.PostTargetType,
21564
+ * targetId: Amity.Post['targetId'],
21565
+ * }, response => merge(posts, response.data))
21566
+ * ```
21567
+ *
21568
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
21569
+ *
21570
+ * @param params.targetType the type of the target
21571
+ * @param params.targetId the ID of the target
21572
+ * @param callback the function to call when new data are available
21573
+ * @param config
21574
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
21575
+ *
21576
+ * @category Posts Live Collection
21577
+ */
21578
+ const getPosts = (params, callback, config) => {
21579
+ const { log, cache } = getActiveClient();
21580
+ if (!cache) {
21581
+ console.log(ENABLE_CACHE_MESSAGE);
21582
+ }
21583
+ const timestamp = Date.now();
21584
+ log(`getPosts(tmpid: ${timestamp}) > listen`);
21585
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
21586
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
21587
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
21588
+ const disposers = [];
21589
+ const cacheKey = [
21590
+ 'post',
21591
+ 'collection',
21592
+ { targetId: params.targetId, targetType: params.targetType },
21593
+ ];
21594
+ const responder = (data) => {
21595
+ var _a, _b, _c;
21596
+ let posts = (_a = data.data
21597
+ .map(postId => pullFromCache(['post', 'get', postId]))
21598
+ .filter(Boolean)
21599
+ .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
21600
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
21601
+ posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
21602
+ if (!params.includeDeleted) {
21603
+ posts = filterByPropEquality(posts, 'isDeleted', false);
21604
+ }
21605
+ if (params.tags) {
21606
+ 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); }); });
21607
+ }
21608
+ if (params.targetType === 'community' && params.feedType) {
21609
+ posts = filterByFeedType(posts, params.feedType);
21610
+ }
21611
+ if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
21612
+ posts = filterByPostDataTypes(posts, params.dataTypes);
21613
+ }
21614
+ callback({
21615
+ onNextPage: onFetch,
21616
+ data: posts,
21617
+ hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
21618
+ loading: data.loading,
21619
+ error: data.error,
21620
+ });
21621
+ };
21622
+ const realtimeRouter = (action) => (post) => {
21623
+ var _a, _b;
21624
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21625
+ if (!collection)
21626
+ return;
21627
+ if (post.parentPostId && post.isDeleted) {
21628
+ const parentPost = (_b = pullFromCache([
21629
+ 'post',
21630
+ 'get',
21631
+ post.parentPostId,
21632
+ ])) === null || _b === void 0 ? void 0 : _b.data;
21633
+ if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
21634
+ return;
21635
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
21636
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
21637
+ }
21638
+ else {
21639
+ if (params.targetId !== post.targetId)
21640
+ return;
21641
+ if (params.targetType !== post.targetType)
21642
+ return;
21643
+ }
21644
+ /*
21645
+ * This is not ideal, but currently this is the only way to update the
21646
+ * collection on post declined
21647
+ */
21648
+ if (action === 'onDeclined') {
21649
+ collection.data = collection.data.filter(postId => postId !== post.postId);
21650
+ }
21651
+ else {
21652
+ collection.data = [...new Set([post.postId, ...collection.data])];
21653
+ }
21654
+ pushToCache(cacheKey, collection);
21655
+ responder(collection);
21656
+ };
21657
+ const onFetch = (initial = false) => {
21658
+ var _a, _b, _c;
21659
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21660
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
21661
+ if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
21662
+ return;
21663
+ 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 }));
21664
+ runQuery(query, ({ data: result, error, loading, paging }) => {
21665
+ const data = {
21666
+ loading,
21667
+ error,
21668
+ params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
21669
+ data: posts,
21670
+ };
21671
+ if (result) {
21672
+ data.data = initial
21673
+ ? result.map(getResolver('post'))
21674
+ : [...new Set([...posts, ...result.map(getResolver('post'))])];
21675
+ }
21676
+ pushToCache(cacheKey, data);
21677
+ responder(data);
21678
+ }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
21679
+ };
21680
+ 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) => {
21681
+ return onCommentCreated(async (comment) => {
21682
+ var _a;
21683
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21684
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
21685
+ return;
21686
+ await getPost$1(comment.referenceId);
21687
+ callback(comment);
21688
+ });
21689
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')), convertEventPayload((callback) => {
21690
+ return onCommentDeleted(async (comment) => {
21691
+ var _a;
21692
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
21693
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
21694
+ return;
21695
+ await getPost$1(comment.referenceId);
21696
+ callback(comment);
21697
+ });
21698
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')));
21699
+ onFetch(true);
21700
+ disposers.push(() => dropFromCache(cacheKey));
21701
+ return () => {
21702
+ log(`getPosts(tmpid: ${timestamp}) > dispose`);
21703
+ disposers.forEach(fn => fn());
21704
+ };
21705
+ };
21706
+ /* end_public_function */
21707
+
21708
+ var index$4 = /*#__PURE__*/Object.freeze({
21709
+ __proto__: null,
21710
+ getPostByIds: getPostByIds,
21711
+ createPost: createPost,
21712
+ updatePost: updatePost,
21713
+ editPost: editPost,
21714
+ deletePost: deletePost,
21715
+ softDeletePost: softDeletePost,
21716
+ hardDeletePost: hardDeletePost,
21717
+ approvePost: approvePost,
21718
+ declinePost: declinePost,
21719
+ flagPost: flagPost,
21720
+ unflagPost: unflagPost,
21721
+ isPostFlaggedByMe: isPostFlaggedByMe,
21722
+ onPostCreated: onPostCreated,
21723
+ onPostUpdated: onPostUpdated,
21724
+ onPostDeleted: onPostDeleted,
21725
+ onPostApproved: onPostApproved,
21726
+ onPostDeclined: onPostDeclined,
21727
+ onPostFlagged: onPostFlagged,
21728
+ onPostUnflagged: onPostUnflagged,
21729
+ onPostReactionAdded: onPostReactionAdded,
21730
+ onPostReactionRemoved: onPostReactionRemoved,
21731
+ observePosts: observePosts,
21732
+ observePost: observePost,
21733
+ getPost: getPost,
21734
+ getPosts: getPosts
21735
+ });
21736
+
21489
21737
  /* begin_public_function
21490
21738
  id: stream.create
21491
21739
  */
@@ -23460,7 +23708,7 @@ class StoryLiveCollectionController extends LiveCollectionController {
23460
23708
  this.queryStreamController = new StoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
23461
23709
  this.paginationController = paginationController;
23462
23710
  this.callback = callback.bind(this);
23463
- this.loadPage(true);
23711
+ this.loadPage({ initial: true });
23464
23712
  }
23465
23713
  setup() {
23466
23714
  var _a;
@@ -23642,7 +23890,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
23642
23890
  this.queryStreamController = new GlobalStoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
23643
23891
  this.paginationController = paginationController;
23644
23892
  this.callback = callback.bind(this);
23645
- this.loadPage(true);
23893
+ this.loadPage({ initial: true });
23646
23894
  }
23647
23895
  setup() {
23648
23896
  var _a;
@@ -23678,7 +23926,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
23678
23926
  return rest;
23679
23927
  });
23680
23928
  this.callback({
23681
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
23929
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
23682
23930
  data,
23683
23931
  hasNextPage: !!this.paginationController.getNextToken(),
23684
23932
  loading,
@@ -23788,7 +24036,7 @@ exports.API_REGIONS = API_REGIONS;
23788
24036
  exports.CategoryRepository = index$7;
23789
24037
  exports.ChannelRepository = index$b;
23790
24038
  exports.Client = index$k;
23791
- exports.CommentRepository = index$4;
24039
+ exports.CommentRepository = index$5;
23792
24040
  exports.CommunityPostSettingMaps = CommunityPostSettingMaps;
23793
24041
  exports.CommunityPostSettings = CommunityPostSettings;
23794
24042
  exports.CommunityRepository = index$8;
@@ -23802,7 +24050,7 @@ exports.MessageContentType = MessageContentType;
23802
24050
  exports.MessageRepository = index$f;
23803
24051
  exports.PollRepository = index$2;
23804
24052
  exports.PostContentType = PostContentType;
23805
- exports.PostRepository = index$5;
24053
+ exports.PostRepository = index$4;
23806
24054
  exports.ReactionRepository = index$g;
23807
24055
  exports.StoryRepository = index;
23808
24056
  exports.StreamRepository = index$3;