@amityco/ts-sdk 7.6.1-bba8c29.0 → 7.6.1-ce05a481.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 (102) hide show
  1. package/dist/@types/core/payload.d.ts +1 -1
  2. package/dist/@types/core/payload.d.ts.map +1 -1
  3. package/dist/@types/domains/content.d.ts +8 -2
  4. package/dist/@types/domains/content.d.ts.map +1 -1
  5. package/dist/@types/domains/feed.d.ts +6 -1
  6. package/dist/@types/domains/feed.d.ts.map +1 -1
  7. package/dist/@types/domains/file.d.ts +3 -1
  8. package/dist/@types/domains/file.d.ts.map +1 -1
  9. package/dist/@types/domains/post.d.ts +3 -0
  10. package/dist/@types/domains/post.d.ts.map +1 -1
  11. package/dist/communityRepository/api/getCommunity.d.ts +1 -1
  12. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  13. package/dist/core/model/index.d.ts.map +1 -1
  14. package/dist/feedRepository/api/getCustomRankingGlobalFeed.d.ts +1 -1
  15. package/dist/feedRepository/api/getCustomRankingGlobalFeed.d.ts.map +1 -1
  16. package/dist/feedRepository/api/queryGlobalFeed.d.ts.map +1 -1
  17. package/dist/feedRepository/index.d.ts +1 -1
  18. package/dist/feedRepository/index.d.ts.map +1 -1
  19. package/dist/feedRepository/observers/getCustomRankingGlobalFeed/LiveCollectionController.d.ts +13 -0
  20. package/dist/feedRepository/observers/getCustomRankingGlobalFeed/LiveCollectionController.d.ts.map +1 -0
  21. package/dist/feedRepository/observers/getCustomRankingGlobalFeed/PaginationController.d.ts +5 -0
  22. package/dist/feedRepository/observers/getCustomRankingGlobalFeed/PaginationController.d.ts.map +1 -0
  23. package/dist/feedRepository/observers/getCustomRankingGlobalFeed/QueryStreamController.d.ts +15 -0
  24. package/dist/feedRepository/observers/getCustomRankingGlobalFeed/QueryStreamController.d.ts.map +1 -0
  25. package/dist/feedRepository/observers/getCustomRankingGlobalFeed.d.ts +23 -0
  26. package/dist/feedRepository/observers/getCustomRankingGlobalFeed.d.ts.map +1 -0
  27. package/dist/feedRepository/observers/getGlobalFeed/LiveCollectionController.d.ts +13 -0
  28. package/dist/feedRepository/observers/getGlobalFeed/LiveCollectionController.d.ts.map +1 -0
  29. package/dist/feedRepository/observers/getGlobalFeed/PaginationController.d.ts +5 -0
  30. package/dist/feedRepository/observers/getGlobalFeed/PaginationController.d.ts.map +1 -0
  31. package/dist/feedRepository/observers/getGlobalFeed/QueryStreamController.d.ts +15 -0
  32. package/dist/feedRepository/observers/getGlobalFeed/QueryStreamController.d.ts.map +1 -0
  33. package/dist/feedRepository/observers/getGlobalFeed.d.ts +22 -0
  34. package/dist/feedRepository/observers/getGlobalFeed.d.ts.map +1 -0
  35. package/dist/feedRepository/observers/index.d.ts +3 -0
  36. package/dist/feedRepository/observers/index.d.ts.map +1 -0
  37. package/dist/feedRepository/observers/utils.d.ts +6 -0
  38. package/dist/feedRepository/observers/utils.d.ts.map +1 -0
  39. package/dist/fileRepository/api/index.d.ts +1 -0
  40. package/dist/fileRepository/api/index.d.ts.map +1 -1
  41. package/dist/fileRepository/api/uploadClip.d.ts +17 -0
  42. package/dist/fileRepository/api/uploadClip.d.ts.map +1 -0
  43. package/dist/index.cjs.js +1565 -1195
  44. package/dist/index.esm.js +1657 -1287
  45. package/dist/index.umd.js +2 -2
  46. package/dist/messagePreview/utils/getSubChannelMessagePreviewWithUser.d.ts +1 -1
  47. package/dist/postRepository/api/createClipPost.d.ts +32 -0
  48. package/dist/postRepository/api/createClipPost.d.ts.map +1 -0
  49. package/dist/postRepository/api/index.d.ts +1 -0
  50. package/dist/postRepository/api/index.d.ts.map +1 -1
  51. package/dist/postRepository/events/utils.d.ts.map +1 -1
  52. package/dist/postRepository/observers/getGlobalPinnedPosts/GlobalPinnedPostLiveCollectionController.d.ts.map +1 -1
  53. package/dist/postRepository/observers/getPinnedPosts/PinnedPostLiveCollectionController.d.ts.map +1 -1
  54. package/dist/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.d.ts +6 -0
  55. package/dist/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.d.ts.map +1 -1
  56. package/dist/postRepository/observers/getPosts/PostLiveCollectionController.d.ts.map +1 -1
  57. package/dist/postRepository/observers/utils.d.ts +13 -0
  58. package/dist/postRepository/observers/utils.d.ts.map +1 -0
  59. package/dist/reactionRepository/api/addReaction.d.ts.map +1 -1
  60. package/dist/reactionRepository/api/removeReaction.d.ts.map +1 -1
  61. package/dist/utils/linkedObject/postLinkedObject.d.ts.map +1 -1
  62. package/dist/utils/postTypePredicate.d.ts +1 -0
  63. package/dist/utils/postTypePredicate.d.ts.map +1 -1
  64. package/dist/utils/tests/dummy/comment.d.ts +1 -1
  65. package/package.json +1 -1
  66. package/src/@types/core/payload.ts +1 -1
  67. package/src/@types/domains/content.ts +10 -0
  68. package/src/@types/domains/feed.ts +18 -1
  69. package/src/@types/domains/file.ts +5 -0
  70. package/src/@types/domains/post.ts +4 -0
  71. package/src/commentRepository/api/deleteComment.ts +6 -6
  72. package/src/communityRepository/api/getCommunity.ts +0 -9
  73. package/src/core/model/index.ts +2 -1
  74. package/src/feedRepository/api/getCustomRankingGlobalFeed.ts +1 -1
  75. package/src/feedRepository/api/queryGlobalFeed.ts +3 -1
  76. package/src/feedRepository/index.ts +1 -1
  77. package/src/feedRepository/observers/getCustomRankingGlobalFeed/LiveCollectionController.ts +95 -0
  78. package/src/feedRepository/observers/getCustomRankingGlobalFeed/PaginationController.ts +25 -0
  79. package/src/feedRepository/observers/getCustomRankingGlobalFeed/QueryStreamController.ts +101 -0
  80. package/src/feedRepository/observers/getCustomRankingGlobalFeed.ts +57 -0
  81. package/src/feedRepository/observers/getGlobalFeed/LiveCollectionController.ts +91 -0
  82. package/src/feedRepository/observers/getGlobalFeed/PaginationController.ts +23 -0
  83. package/src/feedRepository/observers/getGlobalFeed/QueryStreamController.ts +99 -0
  84. package/src/feedRepository/observers/getGlobalFeed.ts +56 -0
  85. package/src/feedRepository/observers/index.ts +2 -0
  86. package/src/feedRepository/observers/utils.ts +85 -0
  87. package/src/fileRepository/api/index.ts +1 -0
  88. package/src/fileRepository/api/uploadClip.ts +71 -0
  89. package/src/postRepository/api/createClipPost.ts +62 -0
  90. package/src/postRepository/api/index.ts +2 -0
  91. package/src/postRepository/api/queryPosts.ts +1 -1
  92. package/src/postRepository/events/utils.ts +35 -1
  93. package/src/postRepository/observers/getGlobalPinnedPosts/GlobalPinnedPostLiveCollectionController.ts +5 -0
  94. package/src/postRepository/observers/getPinnedPosts/PinnedPostLiveCollectionController.ts +7 -1
  95. package/src/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.ts +27 -0
  96. package/src/postRepository/observers/getPosts/PostLiveCollectionController.ts +2 -74
  97. package/src/postRepository/observers/getPosts/PostPaginationController.ts +1 -1
  98. package/src/postRepository/observers/utils.ts +97 -0
  99. package/src/reactionRepository/api/addReaction.ts +1 -0
  100. package/src/reactionRepository/api/removeReaction.ts +1 -0
  101. package/src/utils/linkedObject/postLinkedObject.ts +15 -5
  102. package/src/utils/postTypePredicate.ts +9 -0
package/dist/index.esm.js CHANGED
@@ -19,6 +19,7 @@ const FileType = Object.freeze({
19
19
  FILE: 'file',
20
20
  IMAGE: 'image',
21
21
  VIDEO: 'video',
22
+ CLIP: 'clip',
22
23
  });
23
24
  const VideoResolution = Object.freeze({
24
25
  '1080P': '1080p',
@@ -102,6 +103,7 @@ const PostContentType = Object.freeze({
102
103
  VIDEO: 'video',
103
104
  LIVESTREAM: 'liveStream',
104
105
  POLL: 'poll',
106
+ CLIP: 'clip',
105
107
  });
106
108
 
107
109
  var InvitationTypeEnum;
@@ -640,7 +642,8 @@ const PAYLOAD2MODEL = {
640
642
  };
641
643
  /** hidden */
642
644
  const isOutdated = (prevData, nextData) => {
643
- if ('updatedAt' in nextData && 'updatedAt' in nextData) {
645
+ // Check if the new value is outdated.
646
+ if ('updatedAt' in nextData && 'updatedAt' in prevData) {
644
647
  return new Date(nextData.updatedAt) < new Date(prevData.updatedAt);
645
648
  }
646
649
  return false;
@@ -22784,15 +22787,23 @@ function isAmityVideoPost(post) {
22784
22787
  'videoFileId' in post.data &&
22785
22788
  'thumbnailFileId' in post.data &&
22786
22789
  post.dataType === 'video');
22790
+ }
22791
+ function isAmityClipPost(post) {
22792
+ return !!(post.data &&
22793
+ typeof post.data !== 'string' &&
22794
+ 'fileId' in post.data &&
22795
+ post.dataType === 'clip');
22787
22796
  }
22788
22797
 
22789
22798
  const postLinkedObject = (post) => {
22790
- return Object.assign(Object.assign({}, post), { analytics: {
22799
+ return shallowClone(post, {
22800
+ analytics: {
22791
22801
  markAsViewed: () => {
22792
22802
  const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
22793
22803
  analyticsEngineInstance.markPostAsViewed(post.postId);
22794
22804
  },
22795
- }, get latestComments() {
22805
+ },
22806
+ get latestComments() {
22796
22807
  if (!post.comments)
22797
22808
  return [];
22798
22809
  return (post.comments
@@ -22838,7 +22849,14 @@ const postLinkedObject = (post) => {
22838
22849
  return isAmityFilePost(post)
22839
22850
  ? (_b = pullFromCache(['file', 'get', (_a = post === null || post === void 0 ? void 0 : post.data) === null || _a === void 0 ? void 0 : _a.fileId])) === null || _b === void 0 ? void 0 : _b.data
22840
22851
  : undefined;
22841
- } });
22852
+ },
22853
+ getClipInfo() {
22854
+ var _a, _b;
22855
+ return isAmityClipPost(post)
22856
+ ? (_b = pullFromCache(['file', 'get', (_a = post === null || post === void 0 ? void 0 : post.data) === null || _a === void 0 ? void 0 : _a.fileId])) === null || _b === void 0 ? void 0 : _b.data
22857
+ : undefined;
22858
+ },
22859
+ });
22842
22860
  };
22843
22861
 
22844
22862
  const getCachedMarker = (message) => {
@@ -30006,6 +30024,57 @@ const updateAltText = async (fileId, altText) => {
30006
30024
  };
30007
30025
  /* end_public_function */
30008
30026
 
30027
+ /* begin_public_function
30028
+ id: file.upload.clip
30029
+ */
30030
+ /**
30031
+ * ```js
30032
+ * import { FileRepository } from '@amityco/ts-sdk'
30033
+ * const created = await FileRepository.uploadClip(formData)
30034
+ * ```
30035
+ *
30036
+ * Creates an {@link Amity.File}
30037
+ *
30038
+ * @param formData The data necessary to create a new {@link Amity.File}
30039
+ * @param onProgress The callback to track the upload progress
30040
+ * @returns The newly created {@link Amity.File}
30041
+ *
30042
+ * @category File API
30043
+ * @async
30044
+ */
30045
+ const uploadClip = async (formData, feedType, onProgress) => {
30046
+ const client = getActiveClient();
30047
+ client.log('file/uploadClip', formData);
30048
+ const file = formData.get('files');
30049
+ if (!file)
30050
+ throw new Error('The formData object must have a `files` key.');
30051
+ const accessType = GlobalFileAccessType$1.getInstance().getFileAccessType();
30052
+ formData.append('accessType', accessType);
30053
+ formData.append('preferredFilename', file.name);
30054
+ if (feedType) {
30055
+ formData.append('feedType', feedType);
30056
+ }
30057
+ const headers = 'getHeaders' in formData
30058
+ ? formData.getHeaders()
30059
+ : { 'content-type': 'multipart/form-data' };
30060
+ const { data } = await client.upload.post('/api/v4/clips', formData, {
30061
+ headers,
30062
+ onUploadProgress({ loaded, total = 100 }) {
30063
+ onProgress && onProgress(Math.round((loaded * 100) / total));
30064
+ },
30065
+ });
30066
+ // API-FIX: payload should be serialized properly
30067
+ // const { files } = data
30068
+ const cachedAt = client.cache && Date.now();
30069
+ if (client.cache)
30070
+ ingestInCache({ files: data }, { cachedAt });
30071
+ return {
30072
+ data,
30073
+ cachedAt,
30074
+ };
30075
+ };
30076
+ /* end_public_function */
30077
+
30009
30078
  var index$k = /*#__PURE__*/Object.freeze({
30010
30079
  __proto__: null,
30011
30080
  getFile: getFile,
@@ -30014,7 +30083,8 @@ var index$k = /*#__PURE__*/Object.freeze({
30014
30083
  fileUrlWithSize: fileUrlWithSize,
30015
30084
  uploadVideo: uploadVideo,
30016
30085
  uploadImage: uploadImage,
30017
- updateAltText: updateAltText
30086
+ updateAltText: updateAltText,
30087
+ uploadClip: uploadClip
30018
30088
  });
30019
30089
 
30020
30090
  /**
@@ -30468,7 +30538,7 @@ const addReaction = async (referenceType, referenceId, reactionName) => {
30468
30538
  ]);
30469
30539
  if (!model || ((_a = model.data.myReactions) === null || _a === void 0 ? void 0 : _a.includes(reactionName)))
30470
30540
  return true;
30471
- const updatedModel = Object.assign(Object.assign({}, model.data), { reactionsCount: model.data.reactionsCount + 1, myReactions: [...((_b = model.data.myReactions) !== null && _b !== void 0 ? _b : []), reactionName], reactions: Object.assign(Object.assign({}, model.data.reactions), { [reactionName]: ((_c = model.data.reactions[reactionName]) !== null && _c !== void 0 ? _c : 0) + 1 }) });
30541
+ const updatedModel = Object.assign(Object.assign({}, model.data), { reactionsCount: model.data.reactionsCount + 1, myReactions: [...((_b = model.data.myReactions) !== null && _b !== void 0 ? _b : []), reactionName], reactions: Object.assign(Object.assign({}, model.data.reactions), { [reactionName]: ((_c = model.data.reactions[reactionName]) !== null && _c !== void 0 ? _c : 0) + 1 }), updatedAt: new Date().toISOString() });
30472
30542
  if (referenceType === 'comment') {
30473
30543
  fireEvent('local.comment.addReaction', {
30474
30544
  comment: updatedModel,
@@ -30591,7 +30661,7 @@ const removeReaction = async (referenceType, referenceId, reactionName) => {
30591
30661
  ]);
30592
30662
  if (!model)
30593
30663
  return true;
30594
- const updatedModel = Object.assign(Object.assign({}, model.data), { reactionsCount: Math.max(0, model.data.reactionsCount - 1), myReactions: ((_a = model.data.myReactions) !== null && _a !== void 0 ? _a : []).filter(item => item !== reactionName), reactions: Object.assign(Object.assign({}, model.data.reactions), { [reactionName]: Math.max(0, ((_b = model.data.reactions[reactionName]) !== null && _b !== void 0 ? _b : 0) - 1) }) });
30664
+ const updatedModel = Object.assign(Object.assign({}, model.data), { reactionsCount: Math.max(0, model.data.reactionsCount - 1), myReactions: ((_a = model.data.myReactions) !== null && _a !== void 0 ? _a : []).filter(item => item !== reactionName), reactions: Object.assign(Object.assign({}, model.data.reactions), { [reactionName]: Math.max(0, ((_b = model.data.reactions[reactionName]) !== null && _b !== void 0 ? _b : 0) - 1) }), updatedAt: new Date().toISOString() });
30595
30665
  if (referenceType === 'comment') {
30596
30666
  fireEvent('local.comment.removeReaction', {
30597
30667
  comment: updatedModel,
@@ -30693,6 +30763,26 @@ const prepareSemanticSearchPostPayload = (_a) => {
30693
30763
  return Object.assign(Object.assign({}, processedPostPayload), { polls });
30694
30764
  };
30695
30765
 
30766
+ const processDeleteChildPost = (payload) => {
30767
+ var _a;
30768
+ const post = payload.posts[0];
30769
+ if (!post.parentId)
30770
+ return;
30771
+ const parentPost = (_a = pullFromCache(['post', 'get', post.parentPostId])) === null || _a === void 0 ? void 0 : _a.data;
30772
+ if (!parentPost)
30773
+ return;
30774
+ pushToCache(['post', 'get', parentPost.postId], Object.assign(Object.assign({}, parentPost), { children: parentPost.children.filter(childId => childId !== post.postId) }));
30775
+ };
30776
+ const processCreateChildPost = (payload) => {
30777
+ var _a;
30778
+ const post = payload.posts[0];
30779
+ if (!post.parentId)
30780
+ return;
30781
+ const parentPost = (_a = pullFromCache(['post', 'get', post.parentPostId])) === null || _a === void 0 ? void 0 : _a.data;
30782
+ if (!parentPost)
30783
+ return;
30784
+ pushToCache(['post', 'get', parentPost.postId], Object.assign(Object.assign({}, parentPost), { children: [...new Set([post.postId, ...parentPost.children])] }));
30785
+ };
30696
30786
  const createPostEventSubscriber = (event, callback) => {
30697
30787
  const client = getActiveClient();
30698
30788
  const filter = (payload) => {
@@ -30717,6 +30807,7 @@ const createPostEventSubscriber = (event, callback) => {
30717
30807
  }
30718
30808
  if (event === 'post.deleted') {
30719
30809
  const { postId, postedUserId } = payload.posts[0];
30810
+ processDeleteChildPost(payload);
30720
30811
  try {
30721
30812
  isInTombstone('post', postId);
30722
30813
  }
@@ -30743,6 +30834,8 @@ const createPostEventSubscriber = (event, callback) => {
30743
30834
  }
30744
30835
  queries === null || queries === void 0 ? void 0 : queries.map(({ key, data }) => upsertInCache(key, data, { cachedAt: -1 }));
30745
30836
  }
30837
+ if (event === 'post.created')
30838
+ processCreateChildPost(payload);
30746
30839
  callback(post.data);
30747
30840
  }
30748
30841
  };
@@ -30769,6 +30862,8 @@ const createLocalPostEventSubscriber = (event, callback) => {
30769
30862
  });
30770
30863
  }
30771
30864
  const post = pullFromCache(['post', 'get', payload.posts[0].postId]);
30865
+ if (event === 'local.post.deleted')
30866
+ processDeleteChildPost(payload);
30772
30867
  callback(post.data);
30773
30868
  }
30774
30869
  };
@@ -35882,16 +35977,11 @@ const updateCommunity = async (communityId, patch) => {
35882
35977
  * @category Community API
35883
35978
  * @async
35884
35979
  */
35885
- const getCommunity$1 = async (communityId, type, includeDiscoverablePrivateCommunity) => {
35980
+ const getCommunity$1 = async (communityId) => {
35886
35981
  const client = getActiveClient();
35887
35982
  client.log('community/getCommunity', communityId);
35888
35983
  // API-FIX: endpoint should not be /list, parameters should be querystring.
35889
- const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`, {
35890
- params: {
35891
- type: 'communityJoinRequest',
35892
- includeDiscoverablePrivateCommunity: includeDiscoverablePrivateCommunity !== null && includeDiscoverablePrivateCommunity !== void 0 ? includeDiscoverablePrivateCommunity : true,
35893
- },
35894
- });
35984
+ const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
35895
35985
  const data = prepareCommunityPayload(payload);
35896
35986
  const cachedAt = client.cache && Date.now();
35897
35987
  if (client.cache) {
@@ -38595,1610 +38685,1914 @@ var index$a = /*#__PURE__*/Object.freeze({
38595
38685
  getCategories: getCategories
38596
38686
  });
38597
38687
 
38598
- /* begin_public_function
38599
- id: feed.query.global_feed
38600
- */
38601
- /**
38602
- * ```js
38603
- * import { queryGlobalFeed } from '@amityco/ts-sdk'
38604
- * const posts = await queryGlobalFeed()
38605
- * ```
38606
- *
38607
- * Queries a paginable list of {@link Amity.Post} objects
38608
- *
38609
- * @param query The query parameters
38610
- * @returns A page of {@link Amity.Post} objects
38611
- *
38612
- * @category Feed API
38613
- * @async
38614
- * */
38615
- const queryGlobalFeed = async (query) => {
38616
- const client = getActiveClient();
38617
- client.log('feed/queryGlobalFeed', query);
38618
- const _a = query !== null && query !== void 0 ? query : {}, { queryToken } = _a, params = __rest(_a, ["queryToken"]);
38619
- const options = (() => {
38620
- if (queryToken)
38621
- return { token: queryToken };
38622
- return undefined;
38623
- })();
38624
- const { data: queryPayload } = await client.http.get(`/api/v4/me/global-feeds`, {
38625
- params: Object.assign(Object.assign({}, params), { options }),
38626
- });
38627
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
38628
- const data = prepareMembershipPayload(payload, 'communityUsers');
38629
- const { posts } = data;
38630
- const { communities: processedCommunity } = prepareCommunityPayload(data);
38631
- const cachedAt = client.cache && Date.now();
38632
- if (client.cache) {
38633
- ingestInCache(Object.assign(Object.assign({}, data), { communitis: processedCommunity }));
38634
- const cacheKey = ['globalFeed', 'query', Object.assign(Object.assign({}, params), { options })];
38635
- pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
38688
+ class CustomRankingGlobalFeedPaginationController extends PaginationController {
38689
+ async getRequest(queryParams, token) {
38690
+ const { limit } = queryParams, params = __rest(queryParams, ["limit"]);
38691
+ const options = token ? { token } : { limit };
38692
+ const { data: queryResponse } = await this.http.get(`/api/v5/me/global-feeds`, {
38693
+ params: Object.assign(Object.assign({}, params), { options }),
38694
+ });
38695
+ return queryResponse;
38636
38696
  }
38637
- return {
38638
- data: posts.map(LinkedObject.post),
38639
- cachedAt,
38640
- paging,
38641
- };
38642
- };
38643
- /* end_public_function */
38644
- /**
38645
- * ```js
38646
- * import { queryGlobalFeed } from '@amityco/ts-sdk'
38647
- * const posts = await queryGlobalFeed.locally()
38648
- * ```
38649
- *
38650
- * Queries a paginable list of {@link Amity.Post} objects from cache
38651
- *
38652
- * @param query The query parameters
38653
- * @returns A page of {@link Amity.Post} objects
38654
- *
38655
- * @category Feed API
38656
- * @async
38657
- * */
38658
- queryGlobalFeed.locally = (query) => {
38659
- var _a, _b;
38660
- const client = getActiveClient();
38661
- client.log('post/queryGlobalFeed.locally', query);
38662
- if (!client.cache)
38663
- return;
38664
- const params = __rest(query !== null && query !== void 0 ? query : {}, []);
38665
- const queryKey = ['globalFeed', 'query', Object.assign({}, params)];
38666
- const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
38667
- if (!(data === null || data === void 0 ? void 0 : data.posts.length))
38668
- return;
38669
- const posts = data.posts
38670
- .map(postId => pullFromCache(['post', 'get', postId]))
38671
- .filter(Boolean)
38672
- .map(({ data }) => data)
38673
- .map(LinkedObject.post);
38674
- const { paging } = data;
38675
- return posts.length === ((_b = data === null || data === void 0 ? void 0 : data.posts) === null || _b === void 0 ? void 0 : _b.length)
38676
- ? {
38677
- data: posts,
38678
- cachedAt,
38679
- paging,
38680
- }
38681
- : undefined;
38682
- };
38697
+ }
38683
38698
 
38684
- /* begin_public_function
38685
- id: feed.query.custom_ranking_feed
38686
- */
38687
- /**
38688
- * ```js
38689
- * import { FeedRepository } from '@amityco/ts-sdk'
38690
- * const posts = await FeedRepository.getCustomRankingGlobalFeed()
38691
- * ```
38692
- *
38693
- * Queries a paginable list of {@link Amity.Post} objects
38694
- *
38695
- * @param query The query parameters
38696
- * @returns A page of {@link Amity.Post} objects
38697
- *
38698
- * @category Feed API
38699
- * @async
38700
- * */
38701
- const getCustomRankingGlobalFeed = async (query) => {
38702
- const client = getActiveClient();
38703
- client.log('feed/getCustomRankingGlobalFeed', query);
38704
- const _a = query !== null && query !== void 0 ? query : {}, { queryToken, limit } = _a, params = __rest(_a, ["queryToken", "limit"]);
38705
- const options = (() => {
38706
- if (queryToken)
38707
- return { token: queryToken };
38708
- return undefined;
38709
- })();
38710
- const { data: queryPayload } = await client.http.get(`/api/v5/me/global-feeds`, {
38711
- params: Object.assign(Object.assign({}, params), { limit: !queryToken ? limit : undefined, options }),
38712
- });
38713
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
38714
- const data = prepareMembershipPayload(payload, 'communityUsers');
38715
- const { posts } = data;
38716
- const cachedAt = client.cache && Date.now();
38717
- if (client.cache) {
38718
- ingestInCache(data);
38719
- const cacheKey = ['customGlobalFeed', 'query', Object.assign(Object.assign({}, params), { options })];
38720
- pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
38721
- }
38722
- return { data: posts.map(LinkedObject.post), cachedAt, paging };
38723
- };
38724
- /* end_public_function */
38725
- /**
38726
- * ```js
38727
- * import { FeedRepository } from '@amityco/ts-sdk'
38728
- * const posts = await FeedRepository.getCustomRankingGlobalFeed.locally()
38729
- * ```
38730
- *
38731
- * Queries a paginable list of {@link Amity.Post} objects from cache
38732
- *
38733
- * @param query The query parameters
38734
- * @returns A page of {@link Amity.Post} objects
38735
- *
38736
- * @category Feed API
38737
- * @async
38738
- * */
38739
- getCustomRankingGlobalFeed.locally = (query) => {
38740
- var _a, _b;
38741
- const client = getActiveClient();
38742
- client.log('post/getCustomRankingGlobalFeed.locally', query);
38743
- if (!client.cache)
38744
- return;
38745
- const params = __rest(query !== null && query !== void 0 ? query : {}, []);
38746
- const queryKey = ['customGlobalFeed', 'query', Object.assign({}, params)];
38747
- const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
38748
- if (!(data === null || data === void 0 ? void 0 : data.posts.length))
38749
- return;
38750
- const posts = data.posts
38751
- .map(postId => pullFromCache(['post', 'get', postId]))
38752
- .filter(Boolean)
38753
- .map(({ data }) => data);
38754
- const { paging } = data;
38755
- return posts.length === ((_b = data === null || data === void 0 ? void 0 : data.posts) === null || _b === void 0 ? void 0 : _b.length)
38756
- ? { data: posts.map(LinkedObject.post), cachedAt, paging }
38757
- : undefined;
38758
- };
38699
+ var EnumPostActions;
38700
+ (function (EnumPostActions) {
38701
+ EnumPostActions["OnPostCreated"] = "onPostCreated";
38702
+ EnumPostActions["OnPostUpdated"] = "onPostUpdated";
38703
+ EnumPostActions["OnPostDeleted"] = "onPostDeleted";
38704
+ EnumPostActions["OnPostFlagged"] = "onPostFlagged";
38705
+ EnumPostActions["OnPostUnflagged"] = "onPostUnflagged";
38706
+ EnumPostActions["OnPostReactionAdded"] = "onPostReactionAdded";
38707
+ EnumPostActions["OnPostReactionRemoved"] = "onPostReactionRemoved";
38708
+ EnumPostActions["OnPostApproved"] = "onPostApproved";
38709
+ EnumPostActions["OnPostDeclined"] = "onPostDeclined";
38710
+ })(EnumPostActions || (EnumPostActions = {}));
38759
38711
 
38760
- var index$9 = /*#__PURE__*/Object.freeze({
38761
- __proto__: null,
38762
- queryGlobalFeed: queryGlobalFeed,
38763
- getCustomRankingGlobalFeed: getCustomRankingGlobalFeed
38764
- });
38712
+ class CustomRankingGlobalFeedQueryStreamController extends QueryStreamController {
38713
+ constructor(query, cacheKey, notifyChange, preparePayload) {
38714
+ super(query, cacheKey);
38715
+ this.notifyChange = notifyChange;
38716
+ this.preparePayload = preparePayload;
38717
+ }
38718
+ async saveToMainDB(response) {
38719
+ const processedPayload = await this.preparePayload(response);
38720
+ const client = getActiveClient();
38721
+ const cachedAt = client.cache && Date.now();
38722
+ if (client.cache) {
38723
+ ingestInCache(processedPayload, { cachedAt });
38724
+ }
38725
+ }
38726
+ appendToQueryStream(response, direction, refresh = false) {
38727
+ var _a, _b;
38728
+ if (refresh) {
38729
+ pushToCache(this.cacheKey, {
38730
+ data: response.posts.map(getResolver('post')),
38731
+ });
38732
+ }
38733
+ else {
38734
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38735
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
38736
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...posts, ...response.posts.map(getResolver('post'))])] }));
38737
+ }
38738
+ }
38739
+ reactor(action) {
38740
+ return (post) => {
38741
+ var _a;
38742
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38743
+ if (!collection)
38744
+ return;
38745
+ if (post.parentPostId && !collection.data.includes(post.parentPostId))
38746
+ return;
38747
+ // Delete Action
38748
+ if (action === EnumPostActions.OnPostDeleted) {
38749
+ // Parent Post - Remove from collection
38750
+ collection.data = collection.data.filter(postId => postId !== post.postId);
38751
+ }
38752
+ if (action === EnumPostActions.OnPostCreated || action === EnumPostActions.OnPostApproved) {
38753
+ // If the query has dataTypes array with value, check if post.dataType is include in the array
38754
+ if (this.query.dataTypes && this.query.dataTypes.length > 0) {
38755
+ if (!this.query.dataTypes.includes(post.dataType))
38756
+ return;
38757
+ }
38758
+ collection.data = [...new Set([post.postId, ...collection.data])];
38759
+ }
38760
+ if (action === EnumPostActions.OnPostDeclined) {
38761
+ collection.data = collection.data.filter(postId => postId !== post.postId);
38762
+ }
38763
+ pushToCache(this.cacheKey, collection);
38764
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
38765
+ };
38766
+ }
38767
+ subscribeRTE(createSubscriber) {
38768
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
38769
+ }
38770
+ }
38765
38771
 
38766
38772
  /* begin_public_function
38767
- id: post.get_by_ids
38773
+ id: comment.get_by_ids
38768
38774
  */
38769
38775
  /**
38770
38776
  * ```js
38771
- * import { getPostByIds } from '@amityco/ts-sdk'
38772
- * const { data: posts } = await getPostByIds(['foo', 'bar'])
38777
+ * import { CommentRepository } from '@amityco/ts-sdk'
38778
+ * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
38773
38779
  * ```
38774
38780
  *
38775
- * Fetches a collection of {@link Amity.Post} objects
38781
+ * Fetches a collection of {@link Amity.Comment} objects
38776
38782
  *
38777
- * @param postIds the IDs of the {@link Amity.Post} to fetch
38778
- * @returns the associated collection of {@link Amity.Post} objects
38783
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
38784
+ * @returns the associated collection of {@link Amity.Comment} objects
38779
38785
  *
38780
- * @category Post API
38786
+ * @category Comment API
38781
38787
  * @async
38782
38788
  */
38783
- const getPostByIds = async (postIds) => {
38789
+ const getCommentByIds = async (commentIds) => {
38784
38790
  const client = getActiveClient();
38785
- client.log('post/getPostByIds', postIds);
38786
- const encodedPostIds = postIds.map(postId => encodeURIComponent(postId));
38787
- let payload;
38791
+ client.log('comment/getCommentByIds', commentIds);
38792
+ const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
38793
+ let data;
38788
38794
  try {
38789
38795
  // API-FIX: endpoint should not be /list, parameters should be querystring.
38790
- const response = await client.http.get(`/api/v3/posts/list`, {
38791
- params: { postIds: encodedPostIds },
38796
+ const response = await client.http.get(`/api/v3/comments/list`, {
38797
+ params: { commentIds: encodedCommentIds },
38792
38798
  });
38793
- payload = response.data;
38799
+ data = response.data;
38794
38800
  }
38795
38801
  catch (error) {
38796
- postIds.forEach(postId => {
38802
+ commentIds.forEach(commentId => {
38797
38803
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
38798
- pushToTombstone('post', postId);
38804
+ pushToTombstone('comment', commentId);
38799
38805
  }
38800
38806
  });
38801
38807
  throw error;
38802
38808
  }
38803
- const data = prepareMembershipPayload(payload, 'communityUsers');
38804
38809
  const cachedAt = client.cache && Date.now();
38805
38810
  if (client.cache)
38806
38811
  ingestInCache(data, { cachedAt });
38807
38812
  return {
38808
- data: data.posts.map(LinkedObject.post),
38813
+ data: data.comments.map(comment => LinkedObject.comment(comment)),
38809
38814
  cachedAt,
38810
38815
  };
38811
38816
  };
38812
38817
  /* end_public_function */
38813
38818
  /**
38814
38819
  * ```js
38815
- * import { getPostByIds } from '@amityco/ts-sdk'
38816
- * const { data: posts } = getPostByIds.locally(['foo', 'bar'])
38820
+ * import { getCommentByIds } from '@amityco/ts-sdk'
38821
+ * const comments = getCommentByIds.locally(['foo', 'bar'])
38817
38822
  * ```
38818
38823
  *
38819
- * Fetches a collection of {@link Amity.Post} objects from cache
38824
+ * Fetches a collection of {@link Amity.Comment} objects from cache
38820
38825
  *
38821
- * @param postIds the IDs of the {@link Amity.Post} to fetch
38822
- * @returns the associated collection of {@link Amity.Post} objects
38826
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
38827
+ * @returns the associated collection of {@link Amity.Comment} objects
38823
38828
  *
38824
- * @category Post API
38829
+ * @category Comment API
38825
38830
  */
38826
- getPostByIds.locally = (postIds) => {
38831
+ getCommentByIds.locally = (commentIds) => {
38827
38832
  var _a;
38828
38833
  const client = getActiveClient();
38829
- client.log('post/getPostByIds.locally', postIds);
38834
+ client.log('comment/getCommentByIds.locally', commentIds);
38830
38835
  if (!client.cache)
38831
38836
  return;
38832
- const cached = postIds
38833
- .map(postId => pullFromCache(['post', 'get', postId]))
38837
+ const cached = commentIds
38838
+ .map(commentId => pullFromCache(['comment', 'get', commentId]))
38834
38839
  .filter(Boolean);
38835
- const posts = cached.map(({ data }) => data);
38840
+ const comments = cached.map(({ data }) => data);
38836
38841
  const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
38837
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < postIds.length)
38842
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < commentIds.length)
38838
38843
  return;
38839
38844
  return {
38840
- data: posts.map(LinkedObject.post),
38845
+ data: comments.map(comment => LinkedObject.comment(comment)),
38841
38846
  cachedAt: oldest.cachedAt,
38842
38847
  };
38843
38848
  };
38844
38849
 
38845
38850
  /* begin_public_function
38846
- id: post.create.text_post, post.create.image_post, post.create.file_post, post.create.video_post, post.create.poll_post, post.create.livestream_post, post.create.custom_post
38851
+ id: comment.create
38847
38852
  */
38848
38853
  /**
38849
38854
  * ```js
38850
- * import { PostRepository } from '@amityco/ts-sdk'
38851
- * const created = await PostRepository.createPost({
38852
- * targetType: 'user',
38853
- * targetId: 'foobar',
38854
- * data: { text: 'hello world' }
38855
- * }))
38855
+ * import { CommentRepository } from '@amityco/ts-sdk'
38856
+ * const newComment = await CommentRepository.createComment(bundle)
38856
38857
  * ```
38857
38858
  *
38858
- * Creates an {@link Amity.Post}
38859
+ * Creates an {@link Amity.Comment}
38859
38860
  *
38860
- * @param bundle The data necessary to create a new {@link Amity.Post}
38861
- * @returns The newly created {@link Amity.Post}
38861
+ * @param bundle The data necessary to create a new {@link Amity.Comment}
38862
+ * @returns The newly created {@link Amity.Comment}
38862
38863
  *
38863
- * @category Post API
38864
+ * @category Comment API
38864
38865
  * @async
38865
38866
  */
38866
- const createPost = async (bundle) => {
38867
+ const createComment = async (bundle) => {
38868
+ var _a;
38867
38869
  const client = getActiveClient();
38868
- client.log('post/createPost', bundle);
38869
- if (!bundle.dataType || ['text', 'image', 'file', 'video'].includes(bundle.dataType)) {
38870
- // eslint-disable-next-line no-param-reassign
38871
- delete bundle.dataType;
38872
- }
38873
- const { data: payload } = await client.http.post('/api/v4/posts', bundle);
38874
- fireEvent('post.created', payload);
38875
- const data = prepareMembershipPayload(payload, 'communityUsers');
38870
+ client.log('comment/createComment', bundle);
38871
+ const { data } = await client.http.post('/api/v3/comments', bundle);
38872
+ const { comments } = data;
38873
+ // BE always returns an array of comments If it got record 0 from BE it might have a problem on creation logic
38874
+ if (comments.length === 0)
38875
+ throw new Error('Comment not created');
38876
38876
  const cachedAt = client.cache && Date.now();
38877
38877
  if (client.cache)
38878
38878
  ingestInCache(data, { cachedAt });
38879
- const { posts } = data;
38879
+ if (['post', 'content'].includes(bundle.referenceType)) {
38880
+ const post = (_a = pullFromCache(['post', 'get', bundle.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
38881
+ if (post) {
38882
+ post.commentsCount += 1;
38883
+ fireEvent('local.post.updated', {
38884
+ posts: [post],
38885
+ categories: [],
38886
+ comments: [],
38887
+ communities: [],
38888
+ communityUsers: data.communityUsers,
38889
+ feeds: [],
38890
+ files: data.files,
38891
+ postChildren: [],
38892
+ users: data.users,
38893
+ videoStreamings: [],
38894
+ });
38895
+ }
38896
+ }
38897
+ else if (bundle.referenceType === 'story') {
38898
+ const storyIndex = pullFromCache([
38899
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
38900
+ bundle.referenceId,
38901
+ ]);
38902
+ if (storyIndex === null || storyIndex === void 0 ? void 0 : storyIndex.data) {
38903
+ const cacheStory = pullFromCache([
38904
+ "story" /* STORY_KEY_CACHE.STORY */,
38905
+ 'get',
38906
+ storyIndex.data,
38907
+ ]);
38908
+ if (cacheStory === null || cacheStory === void 0 ? void 0 : cacheStory.data) {
38909
+ fireEvent('story.updated', {
38910
+ stories: [
38911
+ Object.assign(Object.assign({}, cacheStory.data), { commentsCount: cacheStory.data.commentsCount + 1, comments: [...new Set([...cacheStory.data.comments, comments[0].commentId])] }),
38912
+ ],
38913
+ categories: [],
38914
+ comments,
38915
+ communities: [],
38916
+ communityUsers: data.communityUsers,
38917
+ files: data.files,
38918
+ users: data.users,
38919
+ });
38920
+ }
38921
+ }
38922
+ }
38923
+ fireEvent('local.comment.created', data);
38880
38924
  return {
38881
- data: LinkedObject.post(posts[0]),
38925
+ data: LinkedObject.comment(comments[0]),
38882
38926
  cachedAt,
38883
38927
  };
38884
38928
  };
38885
38929
  /* end_public_function */
38886
38930
 
38887
38931
  /* begin_public_function
38888
- id: post.edit, post.edit.custom_post
38932
+ id: comment.update_comment
38889
38933
  */
38890
38934
  /**
38891
38935
  * ```js
38892
- * import { PostRepository } from '@amityco/ts-sdk'
38893
- * const updated = await PostRepository.editPost(postId, {
38936
+ * import { CommentRepository } from '@amityco/ts-sdk'
38937
+ * const updated = await CommentRepository.updateComment(commentId, {
38894
38938
  * data: { text: 'hello world' }
38895
38939
  * })
38896
38940
  * ```
38897
38941
  *
38898
- * Updates an {@link Amity.Post}
38942
+ * Updates an {@link Amity.Comment}
38899
38943
  *
38900
- * @param postId The ID of the {@link Amity.Post} to edit
38944
+ * @param commentId The ID of the {@link Amity.Comment} to edit
38901
38945
  * @param patch The patch data to apply
38902
- * @returns the updated {@link Amity.Post} object
38946
+ * @returns the updated {@link Amity.Comment} object
38903
38947
  *
38904
- * @category Post API
38948
+ * @category Comment API
38905
38949
  * @async
38906
38950
  */
38907
- const editPost = async (postId, patch) => {
38951
+ const updateComment = async (commentId, patch) => {
38908
38952
  const client = getActiveClient();
38909
- client.log('user/editPost', patch);
38910
- const { data: payload } = await client.http.put(`/api/v4/posts/${encodeURIComponent(postId)}`, patch);
38911
- const data = prepareMembershipPayload(payload, 'communityUsers');
38953
+ client.log('user/updateComment', patch);
38954
+ const { data } = await client.http.put(`/api/v3/comments/${encodeURIComponent(commentId)}`, patch);
38912
38955
  const cachedAt = client.cache && Date.now();
38913
38956
  if (client.cache)
38914
38957
  ingestInCache(data, { cachedAt });
38915
- fireEvent('local.post.updated', data);
38916
- const { posts } = data;
38958
+ fireEvent('comment.updated', data);
38959
+ const { comments } = data;
38917
38960
  return {
38918
- data: LinkedObject.post(posts.find(post => post.postId === postId)),
38961
+ data: LinkedObject.comment(comments.find(comment => comment.commentId === commentId)),
38919
38962
  cachedAt,
38920
38963
  };
38921
38964
  };
38922
38965
  /* end_public_function */
38923
38966
 
38967
+ // Due to we have optimistic logic, we will use referenceId as a id in SDK instead of storyId
38968
+ const applyMissingField = (rawData, isCreated = false) => {
38969
+ const { storyId, referenceId } = rawData;
38970
+ if (!isCreated) {
38971
+ if (referenceId)
38972
+ return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */ });
38973
+ }
38974
+ return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */, referenceId: storyId });
38975
+ };
38976
+ const convertRawStoryToInternal = (data, isCreated = false) => {
38977
+ const { stories } = data;
38978
+ const storiesData = stories.map(story => applyMissingField(story, isCreated));
38979
+ return Object.assign(Object.assign({}, data), { stories: storiesData });
38980
+ };
38981
+
38982
+ const getStoryByStoryId$1 = async (storyId) => {
38983
+ const client = getActiveClient();
38984
+ client.log('story/getStoryByStoryId', storyId);
38985
+ // Get story referenceId from cache
38986
+ const cacheReferenceId = pullFromCache([
38987
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
38988
+ storyId,
38989
+ ]);
38990
+ if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
38991
+ const { data: referenceId } = cacheReferenceId;
38992
+ isInTombstone('story', referenceId);
38993
+ }
38994
+ let data;
38995
+ try {
38996
+ const response = await client.http.get(`/api/v4/stories/${storyId}`);
38997
+ data = convertRawStoryToInternal(response.data);
38998
+ }
38999
+ catch (error) {
39000
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39001
+ pushToTombstone('story', storyId);
39002
+ }
39003
+ throw error;
39004
+ }
39005
+ const cachedAt = client.cache && Date.now();
39006
+ if (client.cache) {
39007
+ ingestInCache(data, { cachedAt });
39008
+ }
39009
+ return {
39010
+ data: data.stories[0],
39011
+ cachedAt,
39012
+ };
39013
+ };
39014
+ getStoryByStoryId$1.locally = (storyId) => {
39015
+ const client = getActiveClient();
39016
+ client.log('story/getStorybyStoryId', storyId);
39017
+ // Get story referenceId from cache
39018
+ const cacheReferenceId = pullFromCache([
39019
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39020
+ storyId,
39021
+ ]);
39022
+ if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
39023
+ const { data: referenceId } = cacheReferenceId;
39024
+ isInTombstone('story', referenceId);
39025
+ }
39026
+ const cachedAt = client.cache && Date.now();
39027
+ const storyCache = pullFromCache(['story', 'get', storyId]);
39028
+ if (!storyCache)
39029
+ return;
39030
+ return {
39031
+ data: storyCache.data,
39032
+ cachedAt,
39033
+ };
39034
+ };
39035
+
39036
+ /* begin_public_function
39037
+ id: comment.soft_delete, comment.hard_delete
39038
+ */
38924
39039
  /**
38925
39040
  * ```js
38926
- * import { deletePost } from '@amityco/ts-sdk'
38927
- * const success = await deletePost('foobar')
39041
+ * import { CommentRepository } from '@amityco/ts-sdk'
39042
+ * const success = await CommentRepository.deleteComment('foobar')
38928
39043
  * ```
38929
39044
  *
38930
- * Deletes a {@link Amity.Post}
39045
+ * Deletes a {@link Amity.Comment}
38931
39046
  *
38932
- * @param postId The {@link Amity.Post} ID to delete
38933
- * @return A success boolean if the {@link Amity.Post} was deleted
39047
+ * @param commentId The {@link Amity.Comment} ID to delete
39048
+ * @return A success boolean if the {@link Amity.Comment} was deleted
38934
39049
  *
38935
- * @private
39050
+ * @category Comment API
38936
39051
  * @async
38937
39052
  */
38938
- const deletePost = async (postId, permanent = false) => {
39053
+ const deleteComment = async (commentId, permanent = false) => {
38939
39054
  var _a;
38940
39055
  const client = getActiveClient();
38941
- const post = await getPost$2(postId);
38942
- await client.http.delete(`/api/v4/posts/${encodeURIComponent(postId)}`, {
39056
+ const comment = await getComment$2(commentId);
39057
+ // API-FIX: This endpoint has not been implemented yet.
39058
+ await client.http.delete(`/api/v4/comments/${encodeURIComponent(commentId)}`, {
38943
39059
  params: {
38944
- postId,
39060
+ commentId,
38945
39061
  permanent,
38946
39062
  },
38947
39063
  });
38948
- // there is currently a limitation which doesn't allow us to fire event to tell that community
38949
- // has been updated. reason is that, when the object is deleted, we don't have its `communityId`
38950
- // and so we cannot refetch the community or advertise on events. hopefully this should be solved
38951
- // later when realtime events covers that for us.
38952
- if (post.data.targetType === 'community') {
38953
- const community = await getCommunity$1(post.data.targetId);
38954
- const communityUsersCache = (_a = queryCache(['communityUsers', 'get'])) !== null && _a !== void 0 ? _a : [];
38955
- const communityUsers = communityUsersCache
38956
- .filter(({ key }) => {
38957
- // cache key is ['communityUsers', 'get', `${communityId}#`${userId}`}]
38958
- if (key[0] !== 'communityUsers')
38959
- return false;
38960
- if (key[1] !== 'get')
38961
- return false;
38962
- if (typeof key[2] === 'string')
38963
- return key[2].includes(community.data.communityId);
38964
- return false;
38965
- })
38966
- .map(({ data }) => data);
38967
- fireEvent('community.updated', {
38968
- communities: [community.data],
39064
+ // to support hard deletion
39065
+ const deleted = Object.assign(Object.assign({}, comment.data), { isDeleted: true });
39066
+ if (permanent) {
39067
+ scheduleTask(() => pushToTombstone('comment', commentId));
39068
+ }
39069
+ else {
39070
+ upsertInCache(['comment', 'get', commentId], { isDeleted: true });
39071
+ }
39072
+ if (comment.data.referenceType === 'story') {
39073
+ const story = await getStoryByStoryId$1(comment.data.referenceId);
39074
+ fireEvent('local.story.updated', {
39075
+ stories: [story.data],
38969
39076
  categories: [],
38970
- communityUsers,
38971
- feeds: [],
39077
+ comments: [],
39078
+ communities: [],
39079
+ communityUsers: [],
38972
39080
  files: [],
38973
39081
  users: [],
38974
39082
  });
38975
39083
  }
38976
- // to support hard deletion
38977
- const deleted = Object.assign(Object.assign({}, post.data), { isDeleted: true });
38978
- if (permanent) {
38979
- setTimeout(() => {
38980
- pushToTombstone('post', postId);
38981
- }, 0);
38982
- }
38983
39084
  else {
38984
- upsertInCache(['post', 'get', postId], { isDeleted: true });
39085
+ const post = (_a = pullFromCache(['post', 'get', comment.data.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
39086
+ if (post) {
39087
+ let removeCount;
39088
+ if (!deleted.parentId) {
39089
+ // NOTE: delete the parent comment will remove all children comments
39090
+ removeCount = deleted.childrenNumber + 1;
39091
+ }
39092
+ else
39093
+ removeCount = 1;
39094
+ post.commentsCount -= removeCount;
39095
+ fireEvent('local.post.updated', {
39096
+ posts: [post],
39097
+ categories: [],
39098
+ comments: [],
39099
+ communities: [],
39100
+ communityUsers: [],
39101
+ feeds: [],
39102
+ files: [],
39103
+ postChildren: [],
39104
+ users: [],
39105
+ videoStreamings: [],
39106
+ });
39107
+ }
38985
39108
  }
38986
- fireEvent('local.post.deleted', {
38987
- posts: [deleted],
38988
- categories: [],
38989
- comments: [],
38990
- communities: [],
38991
- communityUsers: [],
38992
- feeds: [],
39109
+ fireEvent('local.comment.deleted', {
39110
+ comments: [deleted],
39111
+ commentChildren: [],
38993
39112
  files: [],
38994
- postChildren: [],
38995
39113
  users: [],
38996
- videoStreamings: [],
39114
+ communityUsers: [],
38997
39115
  });
38998
- return LinkedObject.post(deleted);
38999
- };
39000
-
39001
- /* begin_public_function
39002
- id: post.soft_delete
39003
- */
39004
- /**
39005
- * ```js
39006
- * import { PostRepository } from '@amityco/ts-sdk'
39007
- * const success = await PostRepository.softDeletePost('foobar')
39008
- * ```
39009
- *
39010
- * Soft deletes a {@link Amity.Post}
39011
- *
39012
- * @param postId The {@link Amity.Post} ID to soft delete
39013
- * @return A success boolean if the {@link Amity.Post} was deleted
39014
- *
39015
- * @category Post API
39016
- * @async
39017
- */
39018
- const softDeletePost = async (postId) => {
39019
- const client = getActiveClient();
39020
- client.log('post/softDeletePost', postId);
39021
- const softDeleted = await deletePost(postId, false);
39022
- return LinkedObject.post(softDeleted);
39023
- };
39024
- /* end_public_function */
39025
-
39026
- /* begin_public_function
39027
- id: post.hard_delete
39028
- */
39029
- /**
39030
- * ```js
39031
- * import { hardDeletePost } from '@amityco/ts-sdk'
39032
- * const success = await hardDeletePost('foobar')
39033
- * ```
39034
- *
39035
- * Hard deletes a {@link Amity.Post}
39036
- *
39037
- * @param postId The {@link Amity.Post} ID to be hard delete
39038
- * @return A success boolean if the {@link Amity.Post} was deleted
39039
- *
39040
- * @category Post API
39041
- * @async
39042
- */
39043
- const hardDeletePost = async (postId) => {
39044
- const client = getActiveClient();
39045
- client.log('post/hardDeletePost', postId);
39046
- const hardDeleted = await deletePost(postId, true);
39047
- return LinkedObject.post(hardDeleted);
39116
+ return deleted;
39048
39117
  };
39049
39118
  /* end_public_function */
39050
39119
 
39051
39120
  /* begin_public_function
39052
- id: post.approve
39121
+ id: comment.soft_delete
39053
39122
  */
39054
39123
  /**
39055
39124
  * ```js
39056
- * import { approvePost } from '@amityco/ts-sdk'
39057
- *
39058
- * const { data: post } = await approvePost('postId')
39125
+ * import { CommentRepository } from '@amityco/ts-sdk'
39126
+ * const success = await CommentRepository.softDeleteComment('foobar')
39059
39127
  * ```
39060
39128
  *
39061
- * Approves a {@link Amity.Post}
39129
+ * Deletes a {@link Amity.Comment}
39062
39130
  *
39063
- * @param postId The {@link Amity.Post} ID to be approved
39064
- * @return A {@link Amity.Post} that was approved
39131
+ * @param commentId The {@link Amity.Comment} ID to delete
39132
+ * @return A success boolean if the {@link Amity.Comment} was deleted
39065
39133
  *
39066
- * @category Post API
39134
+ * @category Comment API
39067
39135
  * @async
39068
39136
  */
39069
- const approvePost = async (postId) => {
39137
+ const softDeleteComment = async (commentId) => {
39070
39138
  const client = getActiveClient();
39071
- client.log('post/approvePost', postId);
39072
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/approve`);
39073
- fireEvent('post.approved', payload);
39074
- // fire virtual event for community update
39075
- if (payload.posts[0].targetType === 'community') {
39076
- fireEvent('community.updated', payload);
39077
- }
39078
- const data = prepareMembershipPayload(payload, 'communityUsers');
39079
- const cachedAt = client.cache && Date.now();
39080
- if (client.cache)
39081
- ingestInCache(data, { cachedAt });
39082
- return {
39083
- data: LinkedObject.post(data.posts.find(post => post.postId === postId)),
39084
- cachedAt,
39085
- };
39139
+ client.log('comment/softDeleteComment', commentId);
39140
+ const softDeleted = deleteComment(commentId);
39141
+ return softDeleted;
39086
39142
  };
39087
39143
  /* end_public_function */
39088
39144
 
39089
39145
  /* begin_public_function
39090
- id: post.decline
39146
+ id: comment.hard_delete
39091
39147
  */
39092
39148
  /**
39093
39149
  * ```js
39094
- * import { declinePost } from '@amityco/ts-sdk'
39095
- *
39096
- * const {data: post} = await declinePost('postId')
39150
+ * import { CommentRepository } from '@amityco/ts-sdk'
39151
+ * const success = await CommentRepository.hardDeleteComment('foobar')
39097
39152
  * ```
39098
39153
  *
39099
- * Declines a {@link Amity.Post}
39154
+ * Deletes a {@link Amity.Comment}
39100
39155
  *
39101
- * @param postId The {@link Amity.Post} ID to be declined
39102
- * @return A {@link Amity.Post} that was declined
39156
+ * @param commentId The {@link Amity.Comment} ID to delete
39157
+ * @return A success boolean if the {@link Amity.Comment} was deleted
39103
39158
  *
39104
- * @category Post API
39159
+ * @category Comment API
39105
39160
  * @async
39106
39161
  */
39107
- const declinePost = async (postId) => {
39162
+ const hardDeleteComment = async (commentId) => {
39108
39163
  const client = getActiveClient();
39109
- client.log('post/declinePost', postId);
39110
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/decline`);
39111
- // fire virtual event
39112
- if (payload.posts[0].targetType === 'community') {
39113
- fireEvent('community.updated', payload);
39114
- }
39115
- fireEvent('post.declined', payload);
39116
- const data = prepareMembershipPayload(payload, 'communityUsers');
39117
- const cachedAt = client.cache && Date.now();
39118
- if (client.cache)
39119
- ingestInCache(data, { cachedAt });
39120
- return {
39121
- data: LinkedObject.post(payload.posts.find(post => post.postId === postId)),
39122
- cachedAt,
39123
- };
39164
+ client.log('comment/hardDeleteComment', commentId);
39165
+ const hardDeleted = deleteComment(commentId, true);
39166
+ return hardDeleted;
39124
39167
  };
39125
39168
  /* end_public_function */
39126
39169
 
39127
39170
  /* begin_public_function
39128
- id: post.flag
39171
+ id: comment.flag
39129
39172
  */
39130
39173
  /**
39131
39174
  * ```js
39132
- * import { PostRepository } from '@amityco/ts-sdk'
39133
- * const flagged = await PostRepository.flagPost(postId, reason)
39175
+ * import { CommentRepository } from '@amityco/ts-sdk'
39176
+ * const flagged = await CommentRepository.flagComment(commentId, reason)
39134
39177
  * ```
39135
39178
  *
39136
- * @param postId of the post to flag
39137
- * @param reason the reason to flag the post
39138
- * @returns a boolean
39179
+ * @param commentId The ID of the comment to flag
39180
+ * @param reason the reason to flag the comment
39181
+ * @returns the created report result
39139
39182
  *
39140
- * @category Post API
39183
+ * @category Comment API
39141
39184
  * @async
39142
39185
  * */
39143
- const flagPost = async (postId, reason) => {
39186
+ const flagComment = async (commentId, reason) => {
39144
39187
  const client = getActiveClient();
39145
- client.log('post/flagPost', postId);
39188
+ client.log('comment/flagComment', commentId);
39146
39189
  const isPredefinedReason = reason &&
39147
39190
  Object.entries(ContentFlagReasonEnum).some(([key, value]) => key !== ContentFlagReasonEnum.Others && value === reason);
39148
39191
  const body = {
39149
39192
  reason: reason && isPredefinedReason ? reason : ContentFlagReasonEnum.Others,
39150
39193
  detail: reason && !isPredefinedReason ? reason : '',
39151
39194
  };
39152
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/flag`, body);
39195
+ const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/flag`, body);
39153
39196
  if (client.cache) {
39154
- ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
39197
+ ingestInCache(payload);
39155
39198
  }
39156
- fireEvent('post.flagged', payload);
39199
+ fireEvent('comment.flagged', payload);
39157
39200
  return !!payload;
39158
39201
  };
39159
39202
  /* end_public_function */
39160
39203
 
39161
39204
  /* begin_public_function
39162
- id: post.unflag
39205
+ id: comment.unflag
39163
39206
  */
39164
39207
  /**
39165
39208
  * ```js
39166
- * import { PostRepository } from '@amityco/ts-sdk'
39167
- * const unflagged = await PostRepository.unflagPost(postId)
39209
+ * import { CommentRepository } from '@amityco/ts-sdk'
39210
+ * const unflagged = await CommentRepository.unflagComment('commentId')
39168
39211
  * ```
39169
39212
  *
39170
- * @param postId of the post to unflag
39171
- * @returns the unflag post result
39213
+ * @param commentId The ID of comment to unflag
39214
+ * @returns the unflagged result
39172
39215
  *
39173
- * @category Post API
39216
+ * @category Comment API
39174
39217
  * @async
39175
39218
  * */
39176
- const unflagPost = async (postId) => {
39219
+ const unflagComment = async (commentId) => {
39177
39220
  const client = getActiveClient();
39178
- client.log('post/unflagPost', postId);
39179
- const { data: payload } = await client.http.delete(`/api/v3/posts/${encodeURIComponent(postId)}/unflag`);
39221
+ client.log('comment/unflagComment', commentId);
39222
+ const { data: payload } = await client.http.delete(`/api/v3/comments/${encodeURIComponent(commentId)}/unflag`);
39180
39223
  if (client.cache) {
39181
- ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
39224
+ ingestInCache(payload);
39182
39225
  }
39183
- fireEvent('post.unflagged', payload);
39226
+ fireEvent('comment.unflagged', payload);
39184
39227
  return !!payload;
39185
39228
  };
39186
39229
  /* end_public_function */
39187
39230
 
39188
39231
  /* begin_public_function
39189
- id: post.check_flag_by_me
39232
+ id: comment.check_flag_by_me
39190
39233
  */
39191
39234
  /**
39192
39235
  * ```js
39193
- * import { PostRepository } from '@amityco/ts-sdk'
39194
- * const isReported = await PostRepository.isPostFlaggedByMe('post', postId)
39236
+ * import { CommentRepository } from '@amityco/ts-sdk'
39237
+ * const isReported = await CommentRepository.isCommentFlaggedByMe('commentId')
39195
39238
  * ```
39196
39239
  *
39197
- * @param postId of the post to check if flagged by current user
39198
- * @returns `true` if the post is flagged by me, `false` if doesn't.
39240
+ * @param commentId The ID of the comment to check if flagged by current user
39241
+ * @returns `true` if the comment is flagged by me, `false` if doesn't.
39199
39242
  *
39200
- * @category Post API
39243
+ * @category Comment API
39201
39244
  * @async
39202
39245
  * */
39203
- const isPostFlaggedByMe = async (postId) => {
39246
+ const isCommentFlaggedByMe = async (commentId) => {
39204
39247
  const client = getActiveClient();
39205
- client.log('post/isPostFlaggedByMe', postId);
39206
- const { data: { result }, } = await client.http.get(`/api/v3/posts/${postId}/isflagbyme`);
39248
+ client.log('comment/isCommentFlaggedByMe', commentId);
39249
+ const { data: { result }, } = await client.http.get(`/api/v3/comments/${commentId}/isflagbyme`);
39207
39250
  return result;
39208
39251
  };
39209
39252
  /* end_public_function */
39210
39253
 
39211
- /* begin_public_function
39212
- id: comment.get_by_ids
39213
- */
39214
- /**
39215
- * ```js
39216
- * import { CommentRepository } from '@amityco/ts-sdk'
39217
- * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
39218
- * ```
39219
- *
39220
- * Fetches a collection of {@link Amity.Comment} objects
39221
- *
39222
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
39223
- * @returns the associated collection of {@link Amity.Comment} objects
39224
- *
39225
- * @category Comment API
39226
- * @async
39227
- */
39228
- const getCommentByIds = async (commentIds) => {
39254
+ const getComment$1 = async (commentId) => {
39229
39255
  const client = getActiveClient();
39230
- client.log('comment/getCommentByIds', commentIds);
39231
- const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
39256
+ client.log('comment/getComment', commentId);
39257
+ isInTombstone('comment', commentId);
39232
39258
  let data;
39233
39259
  try {
39234
39260
  // API-FIX: endpoint should not be /list, parameters should be querystring.
39235
- const response = await client.http.get(`/api/v3/comments/list`, {
39236
- params: { commentIds: encodedCommentIds },
39237
- });
39261
+ const response = await client.http.get(`/api/v3/comments/${encodeURIComponent(commentId)}`);
39238
39262
  data = response.data;
39239
39263
  }
39240
39264
  catch (error) {
39241
- commentIds.forEach(commentId => {
39242
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39243
- pushToTombstone('comment', commentId);
39244
- }
39245
- });
39265
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39266
+ pushToTombstone('comment', commentId);
39267
+ }
39246
39268
  throw error;
39247
39269
  }
39248
39270
  const cachedAt = client.cache && Date.now();
39249
39271
  if (client.cache)
39250
39272
  ingestInCache(data, { cachedAt });
39273
+ const { comments } = data;
39251
39274
  return {
39252
- data: data.comments.map(comment => LinkedObject.comment(comment)),
39275
+ data: comments.find(comment => comment.commentId === commentId),
39253
39276
  cachedAt,
39254
39277
  };
39255
39278
  };
39256
- /* end_public_function */
39279
+ getComment$1.locally = (commentId) => {
39280
+ const client = getActiveClient();
39281
+ client.log('comment/getComment.locally', commentId);
39282
+ if (!client.cache)
39283
+ return;
39284
+ const cached = pullFromCache(['comment', 'get', commentId]);
39285
+ if (!cached)
39286
+ return;
39287
+ return {
39288
+ data: cached.data,
39289
+ cachedAt: cached.cachedAt,
39290
+ };
39291
+ };
39292
+
39257
39293
  /**
39258
39294
  * ```js
39259
- * import { getCommentByIds } from '@amityco/ts-sdk'
39260
- * const comments = getCommentByIds.locally(['foo', 'bar'])
39295
+ * import { onCommentDeleteLocal } from '@amityco/ts-sdk'
39296
+ * const dispose = onCommentDeleteLocal(comment => {
39297
+ * // ...
39298
+ * })
39261
39299
  * ```
39262
39300
  *
39263
- * Fetches a collection of {@link Amity.Comment} objects from cache
39301
+ * Fired when a {@link Amity.InternalComment} has been deleted
39264
39302
  *
39265
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
39266
- * @returns the associated collection of {@link Amity.Comment} objects
39303
+ * @param callback The function to call when the event was fired
39304
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39267
39305
  *
39268
- * @category Comment API
39306
+ * @category Comment Events
39269
39307
  */
39270
- getCommentByIds.locally = (commentIds) => {
39271
- var _a;
39308
+ const onCommentDeleteLocal = (callback) => createLocalCommentEventSubscriber('local.comment.deleted', callback);
39309
+
39310
+ /**
39311
+ * ```js
39312
+ * import { onLocalCommentReactionAdded } from '@amityco/ts-sdk'
39313
+ * const dispose = onLocalCommentReactionAdded(comment => {
39314
+ * // ...
39315
+ * })
39316
+ * ```
39317
+ *
39318
+ * Fired when a {@link Amity.InternalComment} has been reacted
39319
+ *
39320
+ * @param callback The function to call when the event was fired
39321
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39322
+ *
39323
+ * @category Comment Events
39324
+ */
39325
+ const onLocalCommentReactionAdded = (callback) => {
39272
39326
  const client = getActiveClient();
39273
- client.log('comment/getCommentByIds.locally', commentIds);
39274
- if (!client.cache)
39275
- return;
39276
- const cached = commentIds
39277
- .map(commentId => pullFromCache(['comment', 'get', commentId]))
39278
- .filter(Boolean);
39279
- const comments = cached.map(({ data }) => data);
39280
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
39281
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < commentIds.length)
39282
- return;
39283
- return {
39284
- data: comments.map(comment => LinkedObject.comment(comment)),
39285
- cachedAt: oldest.cachedAt,
39327
+ const filter = ({ comment }) => {
39328
+ if (!client.cache) {
39329
+ callback(comment);
39330
+ }
39331
+ else {
39332
+ upsertInCache(['comment', 'get', comment.commentId], comment);
39333
+ callback(commentLinkedObject(comment));
39334
+ }
39286
39335
  };
39336
+ return createEventSubscriber(client, 'local.comment.addReaction', 'local.comment.addReaction', filter);
39287
39337
  };
39288
39338
 
39289
- /* begin_public_function
39290
- id: comment.create
39291
- */
39292
39339
  /**
39293
39340
  * ```js
39294
- * import { CommentRepository } from '@amityco/ts-sdk'
39295
- * const newComment = await CommentRepository.createComment(bundle)
39341
+ * import { onLocalCommentReactionRemoved } from '@amityco/ts-sdk'
39342
+ * const dispose = onLocalCommentReactionRemoved(comment => {
39343
+ * // ...
39344
+ * })
39296
39345
  * ```
39297
39346
  *
39298
- * Creates an {@link Amity.Comment}
39347
+ * Fired when a {@link Amity.InternalComment} has been reacted
39299
39348
  *
39300
- * @param bundle The data necessary to create a new {@link Amity.Comment}
39301
- * @returns The newly created {@link Amity.Comment}
39349
+ * @param callback The function to call when the event was fired
39350
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39302
39351
  *
39303
- * @category Comment API
39304
- * @async
39352
+ * @category Comment Events
39305
39353
  */
39306
- const createComment = async (bundle) => {
39307
- var _a;
39354
+ const onLocalCommentReactionRemoved = (callback) => {
39308
39355
  const client = getActiveClient();
39309
- client.log('comment/createComment', bundle);
39310
- const { data } = await client.http.post('/api/v3/comments', bundle);
39311
- const { comments } = data;
39312
- // BE always returns an array of comments If it got record 0 from BE it might have a problem on creation logic
39313
- if (comments.length === 0)
39314
- throw new Error('Comment not created');
39315
- const cachedAt = client.cache && Date.now();
39316
- if (client.cache)
39317
- ingestInCache(data, { cachedAt });
39318
- if (['post', 'content'].includes(bundle.referenceType)) {
39319
- const post = (_a = pullFromCache(['post', 'get', bundle.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
39320
- if (post) {
39321
- post.commentsCount += 1;
39322
- fireEvent('local.post.updated', {
39323
- posts: [post],
39324
- categories: [],
39325
- comments: [],
39326
- communities: [],
39327
- communityUsers: data.communityUsers,
39328
- feeds: [],
39329
- files: data.files,
39330
- postChildren: [],
39331
- users: data.users,
39332
- videoStreamings: [],
39333
- });
39356
+ const filter = ({ comment }) => {
39357
+ if (!client.cache) {
39358
+ callback(comment);
39334
39359
  }
39335
- }
39336
- else if (bundle.referenceType === 'story') {
39337
- const storyIndex = pullFromCache([
39338
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39339
- bundle.referenceId,
39340
- ]);
39341
- if (storyIndex === null || storyIndex === void 0 ? void 0 : storyIndex.data) {
39342
- const cacheStory = pullFromCache([
39343
- "story" /* STORY_KEY_CACHE.STORY */,
39344
- 'get',
39345
- storyIndex.data,
39346
- ]);
39347
- if (cacheStory === null || cacheStory === void 0 ? void 0 : cacheStory.data) {
39348
- fireEvent('story.updated', {
39349
- stories: [
39350
- Object.assign(Object.assign({}, cacheStory.data), { commentsCount: cacheStory.data.commentsCount + 1, comments: [...new Set([...cacheStory.data.comments, comments[0].commentId])] }),
39351
- ],
39352
- categories: [],
39353
- comments,
39354
- communities: [],
39355
- communityUsers: data.communityUsers,
39356
- files: data.files,
39357
- users: data.users,
39358
- });
39359
- }
39360
+ else {
39361
+ upsertInCache(['comment', 'get', comment.commentId], comment);
39362
+ callback(commentLinkedObject(comment));
39360
39363
  }
39361
- }
39362
- fireEvent('local.comment.created', data);
39363
- return {
39364
- data: LinkedObject.comment(comments[0]),
39365
- cachedAt,
39366
39364
  };
39367
- };
39368
- /* end_public_function */
39365
+ return createEventSubscriber(client, 'local.comment.removeReaction', 'local.comment.removeReaction', filter);
39366
+ };
39369
39367
 
39370
39368
  /* begin_public_function
39371
- id: comment.update_comment
39369
+ id: comment.get
39372
39370
  */
39373
39371
  /**
39374
39372
  * ```js
39375
- * import { CommentRepository } from '@amityco/ts-sdk'
39376
- * const updated = await CommentRepository.updateComment(commentId, {
39377
- * data: { text: 'hello world' }
39378
- * })
39373
+ * import { CommentRepository } from '@amityco/ts-sdk';
39374
+ *
39375
+ * let comment;
39376
+ *
39377
+ * const unsub = CommentRepository.getComment(commentId, response => {
39378
+ * comment = response.data;
39379
+ * });
39379
39380
  * ```
39380
39381
  *
39381
- * Updates an {@link Amity.Comment}
39382
+ * Observe all mutation on a given {@link Amity.Comment}
39382
39383
  *
39383
- * @param commentId The ID of the {@link Amity.Comment} to edit
39384
- * @param patch The patch data to apply
39385
- * @returns the updated {@link Amity.Comment} object
39384
+ * @param commentId the ID of the comment to observe
39385
+ * @param callback the function to call when new data are available
39386
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
39386
39387
  *
39387
- * @category Comment API
39388
- * @async
39388
+ * @category Comment Live Object
39389
39389
  */
39390
- const updateComment = async (commentId, patch) => {
39391
- const client = getActiveClient();
39392
- client.log('user/updateComment', patch);
39393
- const { data } = await client.http.put(`/api/v3/comments/${encodeURIComponent(commentId)}`, patch);
39394
- const cachedAt = client.cache && Date.now();
39395
- if (client.cache)
39396
- ingestInCache(data, { cachedAt });
39397
- fireEvent('comment.updated', data);
39398
- const { comments } = data;
39399
- return {
39400
- data: LinkedObject.comment(comments.find(comment => comment.commentId === commentId)),
39401
- cachedAt,
39402
- };
39390
+ const getComment = (commentId, callback) => {
39391
+ return liveObject(commentId, callback, 'commentId', getComment$1, [
39392
+ onCommentDeleteLocal,
39393
+ onCommentDeleted,
39394
+ onCommentFlagged,
39395
+ onCommentReactionAdded,
39396
+ onCommentReactionRemoved,
39397
+ onCommentUnflagged,
39398
+ onCommentUpdated,
39399
+ onLocalCommentReactionAdded,
39400
+ onLocalCommentReactionRemoved,
39401
+ ]);
39403
39402
  };
39404
39403
  /* end_public_function */
39405
39404
 
39406
- // Due to we have optimistic logic, we will use referenceId as a id in SDK instead of storyId
39407
- const applyMissingField = (rawData, isCreated = false) => {
39408
- const { storyId, referenceId } = rawData;
39409
- if (!isCreated) {
39410
- if (referenceId)
39411
- return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */ });
39412
- }
39413
- return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */, referenceId: storyId });
39414
- };
39415
- const convertRawStoryToInternal = (data, isCreated = false) => {
39416
- const { stories } = data;
39417
- const storiesData = stories.map(story => applyMissingField(story, isCreated));
39418
- return Object.assign(Object.assign({}, data), { stories: storiesData });
39405
+ class CommentPaginationController extends PaginationController {
39406
+ async getRequest(queryParams, token) {
39407
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
39408
+ const baseOptions = {
39409
+ type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
39410
+ };
39411
+ const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
39412
+ const { data: queryResponse } = await this.http.get(`/api/v3/comments`, {
39413
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
39414
+ });
39415
+ return queryResponse;
39416
+ }
39417
+ }
39418
+
39419
+ var EnumCommentActions;
39420
+ (function (EnumCommentActions) {
39421
+ EnumCommentActions["OnCommentCreated"] = "onCommentCreated";
39422
+ EnumCommentActions["OnCommentUpdated"] = "onCommentUpdated";
39423
+ EnumCommentActions["OnCommentDeleted"] = "onCommentDeleted";
39424
+ EnumCommentActions["OnCommentFlagged"] = "onCommentFlagged";
39425
+ EnumCommentActions["OnCommentUnflagged"] = "onCommentUnflagged";
39426
+ EnumCommentActions["OnCommentReactionAdded"] = "onCommentReactionAdded";
39427
+ EnumCommentActions["OnCommentReactionRemoved"] = "onCommentReactionRemoved";
39428
+ })(EnumCommentActions || (EnumCommentActions = {}));
39429
+
39430
+ class CommentQueryStreamController extends QueryStreamController {
39431
+ constructor(query, cacheKey, notifyChange, preparePayload) {
39432
+ super(query, cacheKey);
39433
+ this.notifyChange = notifyChange;
39434
+ this.preparePayload = preparePayload;
39435
+ }
39436
+ async saveToMainDB(response) {
39437
+ const processedPayload = await this.preparePayload(response);
39438
+ const client = getActiveClient();
39439
+ const cachedAt = client.cache && Date.now();
39440
+ if (client.cache) {
39441
+ ingestInCache(processedPayload, { cachedAt });
39442
+ }
39443
+ }
39444
+ appendToQueryStream(response, direction, refresh = false) {
39445
+ var _a, _b;
39446
+ if (refresh) {
39447
+ pushToCache(this.cacheKey, {
39448
+ data: response.comments.map(getResolver('comment')),
39449
+ });
39450
+ }
39451
+ else {
39452
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39453
+ const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
39454
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...response.comments.map(getResolver('comment'))])] }));
39455
+ }
39456
+ }
39457
+ reactor(action) {
39458
+ return (comment) => {
39459
+ var _a;
39460
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39461
+ if (this.query.referenceId !== comment.referenceId ||
39462
+ this.query.referenceType !== comment.referenceType ||
39463
+ !collection) {
39464
+ return;
39465
+ }
39466
+ if (this.query.parentId && this.query.parentId !== comment.parentId) {
39467
+ return;
39468
+ }
39469
+ if (!this.query.parentId && comment.parentId) {
39470
+ return;
39471
+ }
39472
+ if (action === EnumCommentActions.OnCommentCreated) {
39473
+ collection.data = [...new Set([comment.commentId, ...collection.data])];
39474
+ }
39475
+ pushToCache(this.cacheKey, collection);
39476
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
39477
+ };
39478
+ }
39479
+ subscribeRTE(createSubscriber) {
39480
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
39481
+ }
39482
+ }
39483
+
39484
+ /**
39485
+ * ```js
39486
+ * import { onCommentCreated } from '@amityco/ts-sdk'
39487
+ * const dispose = onCommentCreated(comment => {
39488
+ * // ...
39489
+ * })
39490
+ * ```
39491
+ *
39492
+ * Fired when a {@link Amity.InternalComment} has been created
39493
+ *
39494
+ * @param callback The function to call when the event was fired
39495
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39496
+ *
39497
+ * @category Comment Events
39498
+ */
39499
+ const onCommentCreatedLocal = (callback) => {
39500
+ return createLocalCommentEventSubscriber('local.comment.created', callback);
39419
39501
  };
39420
39502
 
39421
- const getStoryByStoryId$1 = async (storyId) => {
39422
- const client = getActiveClient();
39423
- client.log('story/getStoryByStoryId', storyId);
39424
- // Get story referenceId from cache
39425
- const cacheReferenceId = pullFromCache([
39426
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39427
- storyId,
39428
- ]);
39429
- if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
39430
- const { data: referenceId } = cacheReferenceId;
39431
- isInTombstone('story', referenceId);
39503
+ class CommentLiveCollectionController extends LiveCollectionController {
39504
+ constructor(query, callback) {
39505
+ const queryStreamId = hash(query);
39506
+ const cacheKey = ['comments', 'collection', queryStreamId];
39507
+ const paginationController = new CommentPaginationController(query);
39508
+ super(paginationController, queryStreamId, cacheKey, callback);
39509
+ this.query = query;
39510
+ this.queryStreamController = new CommentQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommentPayload);
39511
+ this.callback = callback.bind(this);
39512
+ this.loadPage({ initial: true });
39432
39513
  }
39433
- let data;
39514
+ setup() {
39515
+ var _a;
39516
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39517
+ if (!collection) {
39518
+ pushToCache(this.cacheKey, {
39519
+ data: [],
39520
+ params: {},
39521
+ });
39522
+ }
39523
+ }
39524
+ async persistModel(queryPayload) {
39525
+ await this.queryStreamController.saveToMainDB(queryPayload);
39526
+ }
39527
+ persistQueryStream({ response, direction, refresh, }) {
39528
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
39529
+ }
39530
+ startSubscription() {
39531
+ return this.queryStreamController.subscribeRTE([
39532
+ { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
39533
+ { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
39534
+ { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
39535
+ { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
39536
+ { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
39537
+ { fn: onCommentFlagged, action: EnumCommentActions.OnCommentFlagged },
39538
+ { fn: onCommentUnflagged, action: EnumCommentActions.OnCommentUnflagged },
39539
+ { fn: onCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
39540
+ { fn: onCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
39541
+ { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
39542
+ { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
39543
+ ]);
39544
+ }
39545
+ notifyChange({ origin, loading, error }) {
39546
+ var _a, _b;
39547
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39548
+ if (!collection)
39549
+ return;
39550
+ const data = this.applyFilter((_b = collection.data
39551
+ .map(id => pullFromCache(['comment', 'get', id]))
39552
+ .filter(isNonNullable)
39553
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.comment);
39554
+ if (!this.shouldNotify(data) && origin === 'event')
39555
+ return;
39556
+ this.callback({
39557
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
39558
+ data,
39559
+ hasNextPage: !!this.paginationController.getNextToken(),
39560
+ loading,
39561
+ error,
39562
+ });
39563
+ }
39564
+ applyFilter(data) {
39565
+ let comments = data;
39566
+ if (!this.query.includeDeleted) {
39567
+ comments = filterByPropEquality(comments, 'isDeleted', false);
39568
+ }
39569
+ if (this.query.parentId) {
39570
+ comments = comments.filter(comment => comment.parentId === this.query.parentId);
39571
+ }
39572
+ if (typeof this.query.hasFlag === 'boolean') {
39573
+ if (this.query.hasFlag) {
39574
+ comments = comments.filter(comment => comment.hashFlag != null);
39575
+ }
39576
+ else {
39577
+ comments = comments.filter(comment => comment.hashFlag == null);
39578
+ }
39579
+ }
39580
+ if (this.query.dataTypes) {
39581
+ if (this.query.dataTypes.matchType === 'exact') {
39582
+ comments = comments.filter(comment => {
39583
+ var _a, _b;
39584
+ const sortedDataTypesQueryValue = ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.sort()) || [];
39585
+ const sortedDataTypesCommentValue = ((_b = comment.dataTypes) === null || _b === void 0 ? void 0 : _b.sort()) || [];
39586
+ if (sortedDataTypesCommentValue.length !== sortedDataTypesQueryValue.length) {
39587
+ return false;
39588
+ }
39589
+ return sortedDataTypesQueryValue.every((value, index) => value === sortedDataTypesCommentValue[index]);
39590
+ });
39591
+ }
39592
+ if (this.query.dataTypes.matchType === 'any') {
39593
+ comments = comments.filter(comment => { var _a; return (_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.some(value => { var _a; return (_a = comment.dataTypes) === null || _a === void 0 ? void 0 : _a.includes(value); }); });
39594
+ }
39595
+ }
39596
+ switch (this.query.sortBy) {
39597
+ case 'firstCreated':
39598
+ comments = comments.sort(sortByFirstCreated);
39599
+ break;
39600
+ case 'lastCreated':
39601
+ default:
39602
+ comments = comments.sort(sortByLastCreated);
39603
+ break;
39604
+ }
39605
+ return comments;
39606
+ }
39607
+ }
39608
+
39609
+ /* begin_public_function
39610
+ id: comment.query
39611
+ */
39612
+ /**
39613
+ * ```js
39614
+ * import { getComments } from '@amityco/ts-sdk'
39615
+ *
39616
+ * let comments = []
39617
+ * const unsub = getComments({
39618
+ * referenceType: Amity.InternalComment['referenceType'];
39619
+ * referenceId: Amity.InternalComment['referenceId'];
39620
+ * }, response => merge(comments, response.data))
39621
+ * ```
39622
+ *
39623
+ * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
39624
+ *
39625
+ * @param referenceType the type of the target
39626
+ * @param referenceId the ID of the target
39627
+ * @param callback the function to call when new data are available
39628
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
39629
+ *
39630
+ * @category Comments Live Collection
39631
+ */
39632
+ const getComments = (params, callback, config) => {
39633
+ const { log, cache } = getActiveClient();
39634
+ if (!cache) {
39635
+ console.log('For using Live Collection feature you need to enable Cache!');
39636
+ }
39637
+ const timestamp = Date.now();
39638
+ log(`getComments(tmpid: ${timestamp}) > listen`);
39639
+ const commentsLiveCollection = new CommentLiveCollectionController(params, callback);
39640
+ const disposers = commentsLiveCollection.startSubscription();
39641
+ const cacheKey = commentsLiveCollection.getCacheKey();
39642
+ disposers.push(() => dropFromCache(cacheKey));
39643
+ return () => {
39644
+ log(`getComments(tmpid: ${timestamp}) > dispose`);
39645
+ disposers.forEach(fn => fn());
39646
+ };
39647
+ };
39648
+ /* end_public_function */
39649
+
39650
+ var index$9 = /*#__PURE__*/Object.freeze({
39651
+ __proto__: null,
39652
+ getCommentByIds: getCommentByIds,
39653
+ createComment: createComment,
39654
+ updateComment: updateComment,
39655
+ deleteComment: deleteComment,
39656
+ softDeleteComment: softDeleteComment,
39657
+ hardDeleteComment: hardDeleteComment,
39658
+ flagComment: flagComment,
39659
+ unflagComment: unflagComment,
39660
+ isCommentFlaggedByMe: isCommentFlaggedByMe,
39661
+ onCommentCreated: onCommentCreated,
39662
+ onCommentUpdated: onCommentUpdated,
39663
+ onCommentDeleted: onCommentDeleted,
39664
+ onCommentFlagged: onCommentFlagged,
39665
+ onCommentUnflagged: onCommentUnflagged,
39666
+ onCommentReactionAdded: onCommentReactionAdded,
39667
+ onCommentReactionRemoved: onCommentReactionRemoved,
39668
+ getComment: getComment,
39669
+ getComments: getComments
39670
+ });
39671
+
39672
+ const getPost$1 = async (postId) => {
39673
+ const client = getActiveClient();
39674
+ client.log('post/getPost', postId);
39675
+ isInTombstone('post', postId);
39676
+ let payload;
39434
39677
  try {
39435
- const response = await client.http.get(`/api/v4/stories/${storyId}`);
39436
- data = convertRawStoryToInternal(response.data);
39678
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
39679
+ const response = await client.http.get(`/api/v3/posts/${encodeURIComponent(postId)}`);
39680
+ payload = response.data;
39437
39681
  }
39438
39682
  catch (error) {
39439
39683
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39440
- pushToTombstone('story', storyId);
39684
+ pushToTombstone('post', postId);
39441
39685
  }
39442
39686
  throw error;
39443
39687
  }
39688
+ const data = prepareMembershipPayload(payload, 'communityUsers');
39444
39689
  const cachedAt = client.cache && Date.now();
39445
- if (client.cache) {
39690
+ if (client.cache)
39446
39691
  ingestInCache(data, { cachedAt });
39447
- }
39692
+ const { posts } = data;
39693
+ const result = posts.find(post => post.postId === postId);
39448
39694
  return {
39449
- data: data.stories[0],
39695
+ data: result,
39450
39696
  cachedAt,
39451
39697
  };
39452
39698
  };
39453
- getStoryByStoryId$1.locally = (storyId) => {
39699
+ getPost$1.locally = (postId) => {
39454
39700
  const client = getActiveClient();
39455
- client.log('story/getStorybyStoryId', storyId);
39456
- // Get story referenceId from cache
39457
- const cacheReferenceId = pullFromCache([
39458
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39459
- storyId,
39460
- ]);
39461
- if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
39462
- const { data: referenceId } = cacheReferenceId;
39463
- isInTombstone('story', referenceId);
39464
- }
39465
- const cachedAt = client.cache && Date.now();
39466
- const storyCache = pullFromCache(['story', 'get', storyId]);
39467
- if (!storyCache)
39701
+ client.log('post/getPost.locally', postId);
39702
+ if (!client.cache)
39703
+ return;
39704
+ const cached = pullFromCache(['post', 'get', postId]);
39705
+ if (!cached)
39468
39706
  return;
39469
39707
  return {
39470
- data: storyCache.data,
39471
- cachedAt,
39708
+ data: cached.data,
39709
+ cachedAt: cached.cachedAt,
39472
39710
  };
39473
39711
  };
39474
39712
 
39475
- /* begin_public_function
39476
- id: comment.soft_delete, comment.hard_delete
39477
- */
39478
39713
  /**
39479
39714
  * ```js
39480
- * import { CommentRepository } from '@amityco/ts-sdk'
39481
- * const success = await CommentRepository.deleteComment('foobar')
39715
+ * import { onLocalPostDeleted } from '@amityco/ts-sdk'
39716
+ * const dispose = onLocalPostDeleted(post => {
39717
+ * // ...
39718
+ * })
39482
39719
  * ```
39483
39720
  *
39484
- * Deletes a {@link Amity.Comment}
39721
+ * Fired when a {@link Amity.InternalPost} has been deleted
39485
39722
  *
39486
- * @param commentId The {@link Amity.Comment} ID to delete
39487
- * @return A success boolean if the {@link Amity.Comment} was deleted
39723
+ * @param callback The function to call when the event was fired
39724
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39488
39725
  *
39489
- * @category Comment API
39490
- * @async
39726
+ * @category Post Events
39491
39727
  */
39492
- const deleteComment = async (commentId, permanent = false) => {
39493
- var _a;
39728
+ const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.post.deleted', callback);
39729
+
39730
+ /**
39731
+ * ```js
39732
+ * import { onLocalPostReactionAdded } from '@amityco/ts-sdk'
39733
+ * const dispose = onPostReactionAdded(post => {
39734
+ * // ...
39735
+ * })
39736
+ * ```
39737
+ *
39738
+ * Fired when a {@link Amity.InternalPost} has been reacted
39739
+ *
39740
+ * @param callback The function to call when the event was fired
39741
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39742
+ *
39743
+ * @category Post Events
39744
+ */
39745
+ const onLocalPostReactionAdded = (callback) => {
39494
39746
  const client = getActiveClient();
39495
- const comment = await getComment$2(commentId);
39496
- // API-FIX: This endpoint has not been implemented yet.
39497
- await client.http.delete(`/api/v4/comments/${encodeURIComponent(commentId)}`, {
39498
- params: {
39499
- commentId,
39500
- permanent,
39501
- },
39747
+ const filter = ({ post }) => {
39748
+ if (!client.cache) {
39749
+ callback(post);
39750
+ }
39751
+ else {
39752
+ upsertInCache(['post', 'get', post.postId], post);
39753
+ callback(post);
39754
+ }
39755
+ };
39756
+ return createEventSubscriber(client, 'local.post.addReaction', 'local.post.addReaction', filter);
39757
+ };
39758
+
39759
+ /**
39760
+ * ```js
39761
+ * import { onLocalPostReactionRemoved } from '@amityco/ts-sdk'
39762
+ * const dispose = onPostReactionRemoved(post => {
39763
+ * // ...
39764
+ * })
39765
+ * ```
39766
+ *
39767
+ * Fired when a {@link Amity.InternalPost} has been reacted
39768
+ *
39769
+ * @param callback The function to call when the event was fired
39770
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39771
+ *
39772
+ * @category Post Events
39773
+ */
39774
+ const onLocalPostReactionRemoved = (callback) => {
39775
+ const client = getActiveClient();
39776
+ const filter = ({ post }) => {
39777
+ if (!client.cache) {
39778
+ callback(post);
39779
+ }
39780
+ else {
39781
+ upsertInCache(['post', 'get', post.postId], post);
39782
+ callback(post);
39783
+ }
39784
+ };
39785
+ return createEventSubscriber(client, 'local.post.removeReaction', 'local.post.removeReaction', filter);
39786
+ };
39787
+
39788
+ /**
39789
+ * ```js
39790
+ * import { onPostUpdatedLocal } from '@amityco/ts-sdk'
39791
+ * const dispose = onPostUpdatedLocal(post => {
39792
+ * // ...
39793
+ * })
39794
+ * ```
39795
+ *
39796
+ * Fired when a {@link Amity.InternalPost} has been updated
39797
+ *
39798
+ * @param callback The function to call when the event was fired
39799
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39800
+ *
39801
+ * @category Post Events
39802
+ */
39803
+ const onPostUpdatedLocal = (callback) => createLocalPostEventSubscriber('local.post.updated', callback);
39804
+
39805
+ const commentEventHanlder$1 = (callback, eventHandler, cacheKey) => {
39806
+ return eventHandler(async (comment) => {
39807
+ var _a;
39808
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39809
+ if (!currentCollection || !currentCollection.data.includes(comment.referenceId))
39810
+ return;
39811
+ await getPost$1(comment.referenceId);
39812
+ callback(comment);
39502
39813
  });
39503
- // to support hard deletion
39504
- const deleted = Object.assign(Object.assign({}, comment.data), { isDeleted: true });
39505
- if (comment.data.referenceType === 'story') {
39506
- const story = await getStoryByStoryId$1(comment.data.referenceId);
39507
- fireEvent('local.story.updated', {
39508
- stories: [story.data],
39509
- categories: [],
39510
- comments: [],
39511
- communities: [],
39512
- communityUsers: [],
39513
- files: [],
39514
- users: [],
39814
+ };
39815
+ const generateCommentSubscriptions$1 = (cacheKey) => {
39816
+ const eventHandlers = [
39817
+ onCommentCreated,
39818
+ onCommentDeleted,
39819
+ onCommentReactionAdded,
39820
+ onCommentReactionRemoved,
39821
+ onCommentCreatedLocal,
39822
+ onCommentDeleteLocal,
39823
+ onLocalCommentReactionAdded,
39824
+ onLocalCommentReactionRemoved,
39825
+ ];
39826
+ return eventHandlers.map(handler => ({
39827
+ fn: convertEventPayload((callback) => commentEventHanlder$1(callback, handler, cacheKey), 'referenceId', 'post'),
39828
+ action: EnumPostActions.OnPostUpdated,
39829
+ }));
39830
+ };
39831
+ const getGlobalFeedSubscriptions = (cacheKey) => {
39832
+ return [
39833
+ { fn: onPostCreated, action: EnumPostActions.OnPostCreated },
39834
+ { fn: onPostUpdated, action: EnumPostActions.OnPostUpdated },
39835
+ { fn: onPostUpdatedLocal, action: EnumPostActions.OnPostUpdated },
39836
+ { fn: onPostDeleted, action: EnumPostActions.OnPostDeleted },
39837
+ { fn: onPostFlagged, action: EnumPostActions.OnPostFlagged },
39838
+ { fn: onPostUnflagged, action: EnumPostActions.OnPostUnflagged },
39839
+ { fn: onPostApproved, action: EnumPostActions.OnPostApproved },
39840
+ { fn: onPostDeclined, action: EnumPostActions.OnPostDeclined },
39841
+ { fn: onPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
39842
+ { fn: onPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
39843
+ { fn: onLocalPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
39844
+ { fn: onLocalPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
39845
+ { fn: onLocalPostDeleted, action: EnumPostActions.OnPostDeleted },
39846
+ ...generateCommentSubscriptions$1(cacheKey),
39847
+ ];
39848
+ };
39849
+
39850
+ class CustomRankingGlobalFeedLiveCollectionController extends LiveCollectionController {
39851
+ constructor(query, callback) {
39852
+ const queryStreamId = hash(query);
39853
+ const cacheKey = ['customRankingGlobalFeed', 'collection', queryStreamId];
39854
+ const paginationController = new CustomRankingGlobalFeedPaginationController(query);
39855
+ super(paginationController, queryStreamId, cacheKey, callback);
39856
+ this.query = query;
39857
+ this.queryStreamController = new CustomRankingGlobalFeedQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), preparePostPayload);
39858
+ this.callback = callback.bind(this);
39859
+ this.loadPage({ initial: true });
39860
+ }
39861
+ setup() {
39862
+ var _a;
39863
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39864
+ if (!collection) {
39865
+ pushToCache(this.cacheKey, {
39866
+ data: [],
39867
+ params: {},
39868
+ });
39869
+ }
39870
+ }
39871
+ async persistModel(queryPayload) {
39872
+ await this.queryStreamController.saveToMainDB(queryPayload);
39873
+ }
39874
+ persistQueryStream({ response, direction, refresh, }) {
39875
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
39876
+ }
39877
+ startSubscription() {
39878
+ return this.queryStreamController.subscribeRTE(getGlobalFeedSubscriptions(this.cacheKey));
39879
+ }
39880
+ notifyChange({ origin, loading, error }) {
39881
+ var _a, _b;
39882
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39883
+ if (!collection)
39884
+ return;
39885
+ const data = ((_b = collection.data
39886
+ .map(id => pullFromCache(['post', 'get', id]))
39887
+ .filter(isNonNullable)
39888
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.post);
39889
+ if (!this.shouldNotify(data) && origin === 'event')
39890
+ return;
39891
+ this.callback({
39892
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
39893
+ data,
39894
+ hasNextPage: !!this.paginationController.getNextToken(),
39895
+ loading,
39896
+ error,
39515
39897
  });
39516
39898
  }
39517
- else {
39518
- const post = (_a = pullFromCache(['post', 'get', comment.data.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
39519
- if (post) {
39520
- let removeCount;
39521
- if (!deleted.parentId) {
39522
- // NOTE: delete the parent comment will remove all children comments
39523
- removeCount = deleted.childrenNumber + 1;
39899
+ }
39900
+
39901
+ /* begin_public_function
39902
+ id: post.query
39903
+ */
39904
+ /**
39905
+ * ```js
39906
+ * import { PostRepository } from '@amityco/ts-sdk'
39907
+ *
39908
+ * let posts = []
39909
+ * const unsub = PostRepository.getPosts({
39910
+ * targetType: Amity.PostTargetType,
39911
+ * targetId: Amity.Post['targetId'],
39912
+ * }, response => merge(posts, response.data))
39913
+ * ```
39914
+ *
39915
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
39916
+ *
39917
+ * @param params.targetType the type of the target
39918
+ * @param params.targetId the ID of the target
39919
+ * @param callback the function to call when new data are available
39920
+ * @param config
39921
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
39922
+ *
39923
+ * @category Posts Live Collection
39924
+ */
39925
+ const getCustomRankingGlobalFeed = (params, callback, config) => {
39926
+ const { log, cache } = getActiveClient();
39927
+ if (!cache) {
39928
+ console.log(ENABLE_CACHE_MESSAGE);
39929
+ }
39930
+ const timestamp = Date.now();
39931
+ log(`getCustomRankingGlobalFeed(tmpid: ${timestamp}) > listen`);
39932
+ const liveCollection = new CustomRankingGlobalFeedLiveCollectionController(params, callback);
39933
+ const disposers = liveCollection.startSubscription();
39934
+ const cacheKey = liveCollection.getCacheKey();
39935
+ disposers.push(() => dropFromCache(cacheKey));
39936
+ return () => {
39937
+ log(`getCustomRankingGlobalFeed(tmpid: ${timestamp}) > dispose`);
39938
+ disposers.forEach(fn => fn());
39939
+ };
39940
+ };
39941
+ /* end_public_function */
39942
+
39943
+ class GlobalFeedPaginationController extends PaginationController {
39944
+ async getRequest(queryParams, token) {
39945
+ const { limit, resolveParent } = queryParams, params = __rest(queryParams, ["limit", "resolveParent"]);
39946
+ const options = token ? { token } : { limit };
39947
+ const { data: queryResponse } = await this.http.get(`/api/v4/me/global-feeds`, {
39948
+ params: Object.assign(Object.assign({}, params), { resolveParent: resolveParent !== null && resolveParent !== void 0 ? resolveParent : true, options }),
39949
+ });
39950
+ return queryResponse;
39951
+ }
39952
+ }
39953
+
39954
+ class GlobalFeedQueryStreamController extends QueryStreamController {
39955
+ constructor(query, cacheKey, notifyChange, preparePayload) {
39956
+ super(query, cacheKey);
39957
+ this.notifyChange = notifyChange;
39958
+ this.preparePayload = preparePayload;
39959
+ }
39960
+ async saveToMainDB(response) {
39961
+ const processedPayload = await this.preparePayload(response);
39962
+ const client = getActiveClient();
39963
+ const cachedAt = client.cache && Date.now();
39964
+ if (client.cache) {
39965
+ ingestInCache(processedPayload, { cachedAt });
39966
+ }
39967
+ }
39968
+ appendToQueryStream(response, direction, refresh = false) {
39969
+ var _a, _b;
39970
+ if (refresh) {
39971
+ pushToCache(this.cacheKey, {
39972
+ data: response.posts.map(getResolver('post')),
39973
+ });
39974
+ }
39975
+ else {
39976
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39977
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
39978
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...posts, ...response.posts.map(getResolver('post'))])] }));
39979
+ }
39980
+ }
39981
+ reactor(action) {
39982
+ return (post) => {
39983
+ var _a;
39984
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39985
+ if (!collection)
39986
+ return;
39987
+ if (post.parentPostId && !collection.data.includes(post.parentPostId))
39988
+ return;
39989
+ // Delete Action
39990
+ if (action === EnumPostActions.OnPostDeleted) {
39991
+ // Parent Post - Remove from collection
39992
+ collection.data = collection.data.filter(postId => postId !== post.postId);
39524
39993
  }
39525
- else
39526
- removeCount = 1;
39527
- post.commentsCount -= removeCount;
39528
- fireEvent('local.post.updated', {
39529
- posts: [post],
39530
- categories: [],
39531
- comments: [],
39532
- communities: [],
39533
- communityUsers: [],
39534
- feeds: [],
39535
- files: [],
39536
- postChildren: [],
39537
- users: [],
39538
- videoStreamings: [],
39994
+ if (action === EnumPostActions.OnPostCreated || action === EnumPostActions.OnPostApproved) {
39995
+ // If the query has dataTypes array with value, check if post.dataType is include in the array
39996
+ if (this.query.dataTypes && this.query.dataTypes.length > 0) {
39997
+ if (!this.query.dataTypes.includes(post.dataType))
39998
+ return;
39999
+ }
40000
+ collection.data = [...new Set([post.postId, ...collection.data])];
40001
+ }
40002
+ if (action === EnumPostActions.OnPostDeclined) {
40003
+ collection.data = collection.data.filter(postId => postId !== post.postId);
40004
+ }
40005
+ pushToCache(this.cacheKey, collection);
40006
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
40007
+ };
40008
+ }
40009
+ subscribeRTE(createSubscriber) {
40010
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
40011
+ }
40012
+ }
40013
+
40014
+ class GlobalFeedLiveCollectionController extends LiveCollectionController {
40015
+ constructor(query, callback) {
40016
+ const queryStreamId = hash(query);
40017
+ const cacheKey = ['globalFeed', 'collection', queryStreamId];
40018
+ const paginationController = new GlobalFeedPaginationController(query);
40019
+ super(paginationController, queryStreamId, cacheKey, callback);
40020
+ this.query = query;
40021
+ this.queryStreamController = new GlobalFeedQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), preparePostPayload);
40022
+ this.callback = callback.bind(this);
40023
+ this.loadPage({ initial: true });
40024
+ }
40025
+ setup() {
40026
+ var _a;
40027
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40028
+ if (!collection) {
40029
+ pushToCache(this.cacheKey, {
40030
+ data: [],
40031
+ params: {},
39539
40032
  });
39540
40033
  }
39541
40034
  }
39542
- fireEvent('local.comment.deleted', {
39543
- comments: [deleted],
39544
- commentChildren: [],
39545
- files: [],
39546
- users: [],
39547
- communityUsers: [],
39548
- });
39549
- if (permanent) {
39550
- scheduleTask(() => pushToTombstone('comment', commentId));
40035
+ async persistModel(queryPayload) {
40036
+ await this.queryStreamController.saveToMainDB(queryPayload);
39551
40037
  }
39552
- else {
39553
- upsertInCache(['comment', 'get', commentId], { isDeleted: true });
40038
+ persistQueryStream({ response, direction, refresh, }) {
40039
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
40040
+ }
40041
+ startSubscription() {
40042
+ return this.queryStreamController.subscribeRTE(getGlobalFeedSubscriptions(this.cacheKey));
40043
+ }
40044
+ notifyChange({ origin, loading, error }) {
40045
+ var _a, _b;
40046
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40047
+ if (!collection)
40048
+ return;
40049
+ const data = ((_b = collection.data
40050
+ .map(id => pullFromCache(['post', 'get', id]))
40051
+ .filter(isNonNullable)
40052
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.post);
40053
+ if (!this.shouldNotify(data) && origin === 'event')
40054
+ return;
40055
+ this.callback({
40056
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
40057
+ data,
40058
+ hasNextPage: !!this.paginationController.getNextToken(),
40059
+ loading,
40060
+ error,
40061
+ });
39554
40062
  }
39555
- return deleted;
39556
- };
39557
- /* end_public_function */
40063
+ }
39558
40064
 
39559
40065
  /* begin_public_function
39560
- id: comment.soft_delete
40066
+ id: post.query
39561
40067
  */
39562
40068
  /**
39563
40069
  * ```js
39564
- * import { CommentRepository } from '@amityco/ts-sdk'
39565
- * const success = await CommentRepository.softDeleteComment('foobar')
39566
- * ```
39567
- *
39568
- * Deletes a {@link Amity.Comment}
39569
- *
39570
- * @param commentId The {@link Amity.Comment} ID to delete
39571
- * @return A success boolean if the {@link Amity.Comment} was deleted
40070
+ * import { PostRepository } from '@amityco/ts-sdk'
39572
40071
  *
39573
- * @category Comment API
39574
- * @async
39575
- */
39576
- const softDeleteComment = async (commentId) => {
39577
- const client = getActiveClient();
39578
- client.log('comment/softDeleteComment', commentId);
39579
- const softDeleted = deleteComment(commentId);
39580
- return softDeleted;
39581
- };
39582
- /* end_public_function */
39583
-
39584
- /* begin_public_function
39585
- id: comment.hard_delete
39586
- */
39587
- /**
39588
- * ```js
39589
- * import { CommentRepository } from '@amityco/ts-sdk'
39590
- * const success = await CommentRepository.hardDeleteComment('foobar')
40072
+ * let posts = []
40073
+ * const unsub = PostRepository.getPosts({
40074
+ * targetType: Amity.PostTargetType,
40075
+ * targetId: Amity.Post['targetId'],
40076
+ * }, response => merge(posts, response.data))
39591
40077
  * ```
39592
40078
  *
39593
- * Deletes a {@link Amity.Comment}
39594
- *
39595
- * @param commentId The {@link Amity.Comment} ID to delete
39596
- * @return A success boolean if the {@link Amity.Comment} was deleted
40079
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
40080
+ * @param params.targetType the type of the target
40081
+ * @param params.targetId the ID of the target
40082
+ * @param callback the function to call when new data are available
40083
+ * @param config
40084
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
39597
40085
  *
39598
- * @category Comment API
39599
- * @async
40086
+ * @category Posts Live Collection
39600
40087
  */
39601
- const hardDeleteComment = async (commentId) => {
39602
- const client = getActiveClient();
39603
- client.log('comment/hardDeleteComment', commentId);
39604
- const hardDeleted = deleteComment(commentId, true);
39605
- return hardDeleted;
39606
- };
39607
- /* end_public_function */
39608
-
39609
- /* begin_public_function
39610
- id: comment.flag
39611
- */
39612
- /**
39613
- * ```js
39614
- * import { CommentRepository } from '@amityco/ts-sdk'
39615
- * const flagged = await CommentRepository.flagComment(commentId, reason)
39616
- * ```
39617
- *
39618
- * @param commentId The ID of the comment to flag
39619
- * @param reason the reason to flag the comment
39620
- * @returns the created report result
39621
- *
39622
- * @category Comment API
39623
- * @async
39624
- * */
39625
- const flagComment = async (commentId, reason) => {
39626
- const client = getActiveClient();
39627
- client.log('comment/flagComment', commentId);
39628
- const isPredefinedReason = reason &&
39629
- Object.entries(ContentFlagReasonEnum).some(([key, value]) => key !== ContentFlagReasonEnum.Others && value === reason);
39630
- const body = {
39631
- reason: reason && isPredefinedReason ? reason : ContentFlagReasonEnum.Others,
39632
- detail: reason && !isPredefinedReason ? reason : '',
39633
- };
39634
- const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/flag`, body);
39635
- if (client.cache) {
39636
- ingestInCache(payload);
40088
+ const getGlobalFeed = (params, callback, config) => {
40089
+ const { log, cache } = getActiveClient();
40090
+ if (!cache) {
40091
+ console.log(ENABLE_CACHE_MESSAGE);
39637
40092
  }
39638
- fireEvent('comment.flagged', payload);
39639
- return !!payload;
40093
+ const timestamp = Date.now();
40094
+ log(`getGlobalFeed(tmpid: ${timestamp}) > listen`);
40095
+ const liveCollection = new GlobalFeedLiveCollectionController(params, callback);
40096
+ const disposers = liveCollection.startSubscription();
40097
+ const cacheKey = liveCollection.getCacheKey();
40098
+ disposers.push(() => dropFromCache(cacheKey));
40099
+ return () => {
40100
+ log(`getGlobalFeed(tmpid: ${timestamp}) > dispose`);
40101
+ disposers.forEach(fn => fn());
40102
+ };
39640
40103
  };
39641
40104
  /* end_public_function */
39642
40105
 
39643
- /* begin_public_function
39644
- id: comment.unflag
39645
- */
39646
- /**
39647
- * ```js
39648
- * import { CommentRepository } from '@amityco/ts-sdk'
39649
- * const unflagged = await CommentRepository.unflagComment('commentId')
39650
- * ```
39651
- *
39652
- * @param commentId The ID of comment to unflag
39653
- * @returns the unflagged result
39654
- *
39655
- * @category Comment API
39656
- * @async
39657
- * */
39658
- const unflagComment = async (commentId) => {
39659
- const client = getActiveClient();
39660
- client.log('comment/unflagComment', commentId);
39661
- const { data: payload } = await client.http.delete(`/api/v3/comments/${encodeURIComponent(commentId)}/unflag`);
39662
- if (client.cache) {
39663
- ingestInCache(payload);
39664
- }
39665
- fireEvent('comment.unflagged', payload);
39666
- return !!payload;
39667
- };
39668
- /* end_public_function */
40106
+ var index$8 = /*#__PURE__*/Object.freeze({
40107
+ __proto__: null,
40108
+ getCustomRankingGlobalFeed: getCustomRankingGlobalFeed,
40109
+ getGlobalFeed: getGlobalFeed
40110
+ });
39669
40111
 
39670
40112
  /* begin_public_function
39671
- id: comment.check_flag_by_me
40113
+ id: post.get_by_ids
39672
40114
  */
39673
40115
  /**
39674
40116
  * ```js
39675
- * import { CommentRepository } from '@amityco/ts-sdk'
39676
- * const isReported = await CommentRepository.isCommentFlaggedByMe('commentId')
40117
+ * import { getPostByIds } from '@amityco/ts-sdk'
40118
+ * const { data: posts } = await getPostByIds(['foo', 'bar'])
39677
40119
  * ```
39678
40120
  *
39679
- * @param commentId The ID of the comment to check if flagged by current user
39680
- * @returns `true` if the comment is flagged by me, `false` if doesn't.
40121
+ * Fetches a collection of {@link Amity.Post} objects
39681
40122
  *
39682
- * @category Comment API
40123
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
40124
+ * @returns the associated collection of {@link Amity.Post} objects
40125
+ *
40126
+ * @category Post API
39683
40127
  * @async
39684
- * */
39685
- const isCommentFlaggedByMe = async (commentId) => {
39686
- const client = getActiveClient();
39687
- client.log('comment/isCommentFlaggedByMe', commentId);
39688
- const { data: { result }, } = await client.http.get(`/api/v3/comments/${commentId}/isflagbyme`);
39689
- return result;
39690
- };
39691
- /* end_public_function */
39692
-
39693
- const getComment$1 = async (commentId) => {
40128
+ */
40129
+ const getPostByIds = async (postIds) => {
39694
40130
  const client = getActiveClient();
39695
- client.log('comment/getComment', commentId);
39696
- isInTombstone('comment', commentId);
39697
- let data;
40131
+ client.log('post/getPostByIds', postIds);
40132
+ const encodedPostIds = postIds.map(postId => encodeURIComponent(postId));
40133
+ let payload;
39698
40134
  try {
39699
40135
  // API-FIX: endpoint should not be /list, parameters should be querystring.
39700
- const response = await client.http.get(`/api/v3/comments/${encodeURIComponent(commentId)}`);
39701
- data = response.data;
40136
+ const response = await client.http.get(`/api/v3/posts/list`, {
40137
+ params: { postIds: encodedPostIds },
40138
+ });
40139
+ payload = response.data;
39702
40140
  }
39703
40141
  catch (error) {
39704
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39705
- pushToTombstone('comment', commentId);
39706
- }
40142
+ postIds.forEach(postId => {
40143
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
40144
+ pushToTombstone('post', postId);
40145
+ }
40146
+ });
39707
40147
  throw error;
39708
40148
  }
40149
+ const data = prepareMembershipPayload(payload, 'communityUsers');
39709
40150
  const cachedAt = client.cache && Date.now();
39710
40151
  if (client.cache)
39711
40152
  ingestInCache(data, { cachedAt });
39712
- const { comments } = data;
39713
40153
  return {
39714
- data: comments.find(comment => comment.commentId === commentId),
40154
+ data: data.posts.map(LinkedObject.post),
39715
40155
  cachedAt,
39716
40156
  };
39717
40157
  };
39718
- getComment$1.locally = (commentId) => {
40158
+ /* end_public_function */
40159
+ /**
40160
+ * ```js
40161
+ * import { getPostByIds } from '@amityco/ts-sdk'
40162
+ * const { data: posts } = getPostByIds.locally(['foo', 'bar'])
40163
+ * ```
40164
+ *
40165
+ * Fetches a collection of {@link Amity.Post} objects from cache
40166
+ *
40167
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
40168
+ * @returns the associated collection of {@link Amity.Post} objects
40169
+ *
40170
+ * @category Post API
40171
+ */
40172
+ getPostByIds.locally = (postIds) => {
40173
+ var _a;
39719
40174
  const client = getActiveClient();
39720
- client.log('comment/getComment.locally', commentId);
40175
+ client.log('post/getPostByIds.locally', postIds);
39721
40176
  if (!client.cache)
39722
40177
  return;
39723
- const cached = pullFromCache(['comment', 'get', commentId]);
39724
- if (!cached)
40178
+ const cached = postIds
40179
+ .map(postId => pullFromCache(['post', 'get', postId]))
40180
+ .filter(Boolean);
40181
+ const posts = cached.map(({ data }) => data);
40182
+ const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
40183
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < postIds.length)
39725
40184
  return;
39726
40185
  return {
39727
- data: cached.data,
39728
- cachedAt: cached.cachedAt,
40186
+ data: posts.map(LinkedObject.post),
40187
+ cachedAt: oldest.cachedAt,
39729
40188
  };
39730
40189
  };
39731
40190
 
40191
+ /* begin_public_function
40192
+ id: post.create.text_post, post.create.image_post, post.create.file_post, post.create.video_post, post.create.poll_post, post.create.livestream_post, post.create.custom_post
40193
+ */
39732
40194
  /**
39733
40195
  * ```js
39734
- * import { onCommentDeleteLocal } from '@amityco/ts-sdk'
39735
- * const dispose = onCommentDeleteLocal(comment => {
39736
- * // ...
39737
- * })
40196
+ * import { PostRepository } from '@amityco/ts-sdk'
40197
+ * const created = await PostRepository.createPost({
40198
+ * targetType: 'user',
40199
+ * targetId: 'foobar',
40200
+ * data: { text: 'hello world' }
40201
+ * }))
39738
40202
  * ```
39739
40203
  *
39740
- * Fired when a {@link Amity.InternalComment} has been deleted
40204
+ * Creates an {@link Amity.Post}
39741
40205
  *
39742
- * @param callback The function to call when the event was fired
39743
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40206
+ * @param bundle The data necessary to create a new {@link Amity.Post}
40207
+ * @returns The newly created {@link Amity.Post}
39744
40208
  *
39745
- * @category Comment Events
40209
+ * @category Post API
40210
+ * @async
39746
40211
  */
39747
- const onCommentDeleteLocal = (callback) => createLocalCommentEventSubscriber('local.comment.deleted', callback);
40212
+ const createPost = async (bundle) => {
40213
+ const client = getActiveClient();
40214
+ client.log('post/createPost', bundle);
40215
+ if (!bundle.dataType || ['text', 'image', 'file', 'video'].includes(bundle.dataType)) {
40216
+ // eslint-disable-next-line no-param-reassign
40217
+ delete bundle.dataType;
40218
+ }
40219
+ const { data: payload } = await client.http.post('/api/v4/posts', bundle);
40220
+ fireEvent('post.created', payload);
40221
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40222
+ const cachedAt = client.cache && Date.now();
40223
+ if (client.cache)
40224
+ ingestInCache(data, { cachedAt });
40225
+ const { posts } = data;
40226
+ return {
40227
+ data: LinkedObject.post(posts[0]),
40228
+ cachedAt,
40229
+ };
40230
+ };
40231
+ /* end_public_function */
39748
40232
 
40233
+ /* begin_public_function
40234
+ id: post.edit, post.edit.custom_post
40235
+ */
39749
40236
  /**
39750
40237
  * ```js
39751
- * import { onLocalCommentReactionAdded } from '@amityco/ts-sdk'
39752
- * const dispose = onLocalCommentReactionAdded(comment => {
39753
- * // ...
40238
+ * import { PostRepository } from '@amityco/ts-sdk'
40239
+ * const updated = await PostRepository.editPost(postId, {
40240
+ * data: { text: 'hello world' }
39754
40241
  * })
39755
40242
  * ```
39756
40243
  *
39757
- * Fired when a {@link Amity.InternalComment} has been reacted
40244
+ * Updates an {@link Amity.Post}
39758
40245
  *
39759
- * @param callback The function to call when the event was fired
39760
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40246
+ * @param postId The ID of the {@link Amity.Post} to edit
40247
+ * @param patch The patch data to apply
40248
+ * @returns the updated {@link Amity.Post} object
39761
40249
  *
39762
- * @category Comment Events
40250
+ * @category Post API
40251
+ * @async
39763
40252
  */
39764
- const onLocalCommentReactionAdded = (callback) => {
40253
+ const editPost = async (postId, patch) => {
39765
40254
  const client = getActiveClient();
39766
- const filter = ({ comment }) => {
39767
- if (!client.cache) {
39768
- callback(comment);
39769
- }
39770
- else {
39771
- upsertInCache(['comment', 'get', comment.commentId], comment);
39772
- callback(commentLinkedObject(comment));
39773
- }
40255
+ client.log('user/editPost', patch);
40256
+ const { data: payload } = await client.http.put(`/api/v4/posts/${encodeURIComponent(postId)}`, patch);
40257
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40258
+ const cachedAt = client.cache && Date.now();
40259
+ if (client.cache)
40260
+ ingestInCache(data, { cachedAt });
40261
+ fireEvent('local.post.updated', data);
40262
+ const { posts } = data;
40263
+ return {
40264
+ data: LinkedObject.post(posts.find(post => post.postId === postId)),
40265
+ cachedAt,
39774
40266
  };
39775
- return createEventSubscriber(client, 'local.comment.addReaction', 'local.comment.addReaction', filter);
39776
- };
40267
+ };
40268
+ /* end_public_function */
39777
40269
 
39778
40270
  /**
39779
40271
  * ```js
39780
- * import { onLocalCommentReactionRemoved } from '@amityco/ts-sdk'
39781
- * const dispose = onLocalCommentReactionRemoved(comment => {
39782
- * // ...
39783
- * })
40272
+ * import { deletePost } from '@amityco/ts-sdk'
40273
+ * const success = await deletePost('foobar')
39784
40274
  * ```
39785
40275
  *
39786
- * Fired when a {@link Amity.InternalComment} has been reacted
40276
+ * Deletes a {@link Amity.Post}
39787
40277
  *
39788
- * @param callback The function to call when the event was fired
39789
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40278
+ * @param postId The {@link Amity.Post} ID to delete
40279
+ * @return A success boolean if the {@link Amity.Post} was deleted
39790
40280
  *
39791
- * @category Comment Events
40281
+ * @private
40282
+ * @async
39792
40283
  */
39793
- const onLocalCommentReactionRemoved = (callback) => {
40284
+ const deletePost = async (postId, permanent = false) => {
40285
+ var _a;
39794
40286
  const client = getActiveClient();
39795
- const filter = ({ comment }) => {
39796
- if (!client.cache) {
39797
- callback(comment);
39798
- }
39799
- else {
39800
- upsertInCache(['comment', 'get', comment.commentId], comment);
39801
- callback(commentLinkedObject(comment));
39802
- }
39803
- };
39804
- return createEventSubscriber(client, 'local.comment.removeReaction', 'local.comment.removeReaction', filter);
40287
+ const post = await getPost$2(postId);
40288
+ await client.http.delete(`/api/v4/posts/${encodeURIComponent(postId)}`, {
40289
+ params: {
40290
+ postId,
40291
+ permanent,
40292
+ },
40293
+ });
40294
+ // there is currently a limitation which doesn't allow us to fire event to tell that community
40295
+ // has been updated. reason is that, when the object is deleted, we don't have its `communityId`
40296
+ // and so we cannot refetch the community or advertise on events. hopefully this should be solved
40297
+ // later when realtime events covers that for us.
40298
+ if (post.data.targetType === 'community') {
40299
+ const community = await getCommunity$1(post.data.targetId);
40300
+ const communityUsersCache = (_a = queryCache(['communityUsers', 'get'])) !== null && _a !== void 0 ? _a : [];
40301
+ const communityUsers = communityUsersCache
40302
+ .filter(({ key }) => {
40303
+ // cache key is ['communityUsers', 'get', `${communityId}#`${userId}`}]
40304
+ if (key[0] !== 'communityUsers')
40305
+ return false;
40306
+ if (key[1] !== 'get')
40307
+ return false;
40308
+ if (typeof key[2] === 'string')
40309
+ return key[2].includes(community.data.communityId);
40310
+ return false;
40311
+ })
40312
+ .map(({ data }) => data);
40313
+ fireEvent('community.updated', {
40314
+ communities: [community.data],
40315
+ categories: [],
40316
+ communityUsers,
40317
+ feeds: [],
40318
+ files: [],
40319
+ users: [],
40320
+ });
40321
+ }
40322
+ // to support hard deletion
40323
+ const deleted = Object.assign(Object.assign({}, post.data), { isDeleted: true });
40324
+ if (permanent) {
40325
+ setTimeout(() => {
40326
+ pushToTombstone('post', postId);
40327
+ }, 0);
40328
+ }
40329
+ else {
40330
+ upsertInCache(['post', 'get', postId], { isDeleted: true });
40331
+ }
40332
+ fireEvent('local.post.deleted', {
40333
+ posts: [deleted],
40334
+ categories: [],
40335
+ comments: [],
40336
+ communities: [],
40337
+ communityUsers: [],
40338
+ feeds: [],
40339
+ files: [],
40340
+ postChildren: [],
40341
+ users: [],
40342
+ videoStreamings: [],
40343
+ });
40344
+ return LinkedObject.post(deleted);
39805
40345
  };
39806
40346
 
39807
40347
  /* begin_public_function
39808
- id: comment.get
40348
+ id: post.soft_delete
39809
40349
  */
39810
40350
  /**
39811
40351
  * ```js
39812
- * import { CommentRepository } from '@amityco/ts-sdk';
39813
- *
39814
- * let comment;
39815
- *
39816
- * const unsub = CommentRepository.getComment(commentId, response => {
39817
- * comment = response.data;
39818
- * });
40352
+ * import { PostRepository } from '@amityco/ts-sdk'
40353
+ * const success = await PostRepository.softDeletePost('foobar')
39819
40354
  * ```
39820
40355
  *
39821
- * Observe all mutation on a given {@link Amity.Comment}
39822
- *
39823
- * @param commentId the ID of the comment to observe
39824
- * @param callback the function to call when new data are available
39825
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
40356
+ * Soft deletes a {@link Amity.Post}
39826
40357
  *
39827
- * @category Comment Live Object
39828
- */
39829
- const getComment = (commentId, callback) => {
39830
- return liveObject(commentId, callback, 'commentId', getComment$1, [
39831
- onCommentDeleteLocal,
39832
- onCommentDeleted,
39833
- onCommentFlagged,
39834
- onCommentReactionAdded,
39835
- onCommentReactionRemoved,
39836
- onCommentUnflagged,
39837
- onCommentUpdated,
39838
- onLocalCommentReactionAdded,
39839
- onLocalCommentReactionRemoved,
39840
- ]);
39841
- };
39842
- /* end_public_function */
39843
-
39844
- class CommentPaginationController extends PaginationController {
39845
- async getRequest(queryParams, token) {
39846
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
39847
- const baseOptions = {
39848
- type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
39849
- };
39850
- const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
39851
- const { data: queryResponse } = await this.http.get(`/api/v3/comments`, {
39852
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
39853
- });
39854
- return queryResponse;
39855
- }
39856
- }
39857
-
39858
- var EnumCommentActions;
39859
- (function (EnumCommentActions) {
39860
- EnumCommentActions["OnCommentCreated"] = "onCommentCreated";
39861
- EnumCommentActions["OnCommentUpdated"] = "onCommentUpdated";
39862
- EnumCommentActions["OnCommentDeleted"] = "onCommentDeleted";
39863
- EnumCommentActions["OnCommentFlagged"] = "onCommentFlagged";
39864
- EnumCommentActions["OnCommentUnflagged"] = "onCommentUnflagged";
39865
- EnumCommentActions["OnCommentReactionAdded"] = "onCommentReactionAdded";
39866
- EnumCommentActions["OnCommentReactionRemoved"] = "onCommentReactionRemoved";
39867
- })(EnumCommentActions || (EnumCommentActions = {}));
39868
-
39869
- class CommentQueryStreamController extends QueryStreamController {
39870
- constructor(query, cacheKey, notifyChange, preparePayload) {
39871
- super(query, cacheKey);
39872
- this.notifyChange = notifyChange;
39873
- this.preparePayload = preparePayload;
39874
- }
39875
- async saveToMainDB(response) {
39876
- const processedPayload = await this.preparePayload(response);
39877
- const client = getActiveClient();
39878
- const cachedAt = client.cache && Date.now();
39879
- if (client.cache) {
39880
- ingestInCache(processedPayload, { cachedAt });
39881
- }
39882
- }
39883
- appendToQueryStream(response, direction, refresh = false) {
39884
- var _a, _b;
39885
- if (refresh) {
39886
- pushToCache(this.cacheKey, {
39887
- data: response.comments.map(getResolver('comment')),
39888
- });
39889
- }
39890
- else {
39891
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39892
- const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
39893
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...response.comments.map(getResolver('comment'))])] }));
39894
- }
39895
- }
39896
- reactor(action) {
39897
- return (comment) => {
39898
- var _a;
39899
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39900
- if (this.query.referenceId !== comment.referenceId ||
39901
- this.query.referenceType !== comment.referenceType ||
39902
- !collection) {
39903
- return;
39904
- }
39905
- if (this.query.parentId && this.query.parentId !== comment.parentId) {
39906
- return;
39907
- }
39908
- if (!this.query.parentId && comment.parentId) {
39909
- return;
39910
- }
39911
- if (action === EnumCommentActions.OnCommentCreated) {
39912
- collection.data = [...new Set([comment.commentId, ...collection.data])];
39913
- }
39914
- pushToCache(this.cacheKey, collection);
39915
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
39916
- };
39917
- }
39918
- subscribeRTE(createSubscriber) {
39919
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
39920
- }
39921
- }
40358
+ * @param postId The {@link Amity.Post} ID to soft delete
40359
+ * @return A success boolean if the {@link Amity.Post} was deleted
40360
+ *
40361
+ * @category Post API
40362
+ * @async
40363
+ */
40364
+ const softDeletePost = async (postId) => {
40365
+ const client = getActiveClient();
40366
+ client.log('post/softDeletePost', postId);
40367
+ const softDeleted = await deletePost(postId, false);
40368
+ return LinkedObject.post(softDeleted);
40369
+ };
40370
+ /* end_public_function */
39922
40371
 
40372
+ /* begin_public_function
40373
+ id: post.hard_delete
40374
+ */
39923
40375
  /**
39924
40376
  * ```js
39925
- * import { onCommentCreated } from '@amityco/ts-sdk'
39926
- * const dispose = onCommentCreated(comment => {
39927
- * // ...
39928
- * })
40377
+ * import { hardDeletePost } from '@amityco/ts-sdk'
40378
+ * const success = await hardDeletePost('foobar')
39929
40379
  * ```
39930
40380
  *
39931
- * Fired when a {@link Amity.InternalComment} has been created
40381
+ * Hard deletes a {@link Amity.Post}
39932
40382
  *
39933
- * @param callback The function to call when the event was fired
39934
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40383
+ * @param postId The {@link Amity.Post} ID to be hard delete
40384
+ * @return A success boolean if the {@link Amity.Post} was deleted
39935
40385
  *
39936
- * @category Comment Events
40386
+ * @category Post API
40387
+ * @async
39937
40388
  */
39938
- const onCommentCreatedLocal = (callback) => {
39939
- return createLocalCommentEventSubscriber('local.comment.created', callback);
39940
- };
39941
-
39942
- class CommentLiveCollectionController extends LiveCollectionController {
39943
- constructor(query, callback) {
39944
- const queryStreamId = hash(query);
39945
- const cacheKey = ['comments', 'collection', queryStreamId];
39946
- const paginationController = new CommentPaginationController(query);
39947
- super(paginationController, queryStreamId, cacheKey, callback);
39948
- this.query = query;
39949
- this.queryStreamController = new CommentQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommentPayload);
39950
- this.callback = callback.bind(this);
39951
- this.loadPage({ initial: true });
39952
- }
39953
- setup() {
39954
- var _a;
39955
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39956
- if (!collection) {
39957
- pushToCache(this.cacheKey, {
39958
- data: [],
39959
- params: {},
39960
- });
39961
- }
39962
- }
39963
- async persistModel(queryPayload) {
39964
- await this.queryStreamController.saveToMainDB(queryPayload);
39965
- }
39966
- persistQueryStream({ response, direction, refresh, }) {
39967
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
39968
- }
39969
- startSubscription() {
39970
- return this.queryStreamController.subscribeRTE([
39971
- { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
39972
- { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
39973
- { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
39974
- { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
39975
- { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
39976
- { fn: onCommentFlagged, action: EnumCommentActions.OnCommentFlagged },
39977
- { fn: onCommentUnflagged, action: EnumCommentActions.OnCommentUnflagged },
39978
- { fn: onCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
39979
- { fn: onCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
39980
- { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
39981
- { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
39982
- ]);
39983
- }
39984
- notifyChange({ origin, loading, error }) {
39985
- var _a, _b;
39986
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39987
- if (!collection)
39988
- return;
39989
- const data = this.applyFilter((_b = collection.data
39990
- .map(id => pullFromCache(['comment', 'get', id]))
39991
- .filter(isNonNullable)
39992
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.comment);
39993
- if (!this.shouldNotify(data) && origin === 'event')
39994
- return;
39995
- this.callback({
39996
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
39997
- data,
39998
- hasNextPage: !!this.paginationController.getNextToken(),
39999
- loading,
40000
- error,
40001
- });
40002
- }
40003
- applyFilter(data) {
40004
- let comments = data;
40005
- if (!this.query.includeDeleted) {
40006
- comments = filterByPropEquality(comments, 'isDeleted', false);
40007
- }
40008
- if (this.query.parentId) {
40009
- comments = comments.filter(comment => comment.parentId === this.query.parentId);
40010
- }
40011
- if (typeof this.query.hasFlag === 'boolean') {
40012
- if (this.query.hasFlag) {
40013
- comments = comments.filter(comment => comment.hashFlag != null);
40014
- }
40015
- else {
40016
- comments = comments.filter(comment => comment.hashFlag == null);
40017
- }
40018
- }
40019
- if (this.query.dataTypes) {
40020
- if (this.query.dataTypes.matchType === 'exact') {
40021
- comments = comments.filter(comment => {
40022
- var _a, _b;
40023
- const sortedDataTypesQueryValue = ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.sort()) || [];
40024
- const sortedDataTypesCommentValue = ((_b = comment.dataTypes) === null || _b === void 0 ? void 0 : _b.sort()) || [];
40025
- if (sortedDataTypesCommentValue.length !== sortedDataTypesQueryValue.length) {
40026
- return false;
40027
- }
40028
- return sortedDataTypesQueryValue.every((value, index) => value === sortedDataTypesCommentValue[index]);
40029
- });
40030
- }
40031
- if (this.query.dataTypes.matchType === 'any') {
40032
- comments = comments.filter(comment => { var _a; return (_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.some(value => { var _a; return (_a = comment.dataTypes) === null || _a === void 0 ? void 0 : _a.includes(value); }); });
40033
- }
40034
- }
40035
- switch (this.query.sortBy) {
40036
- case 'firstCreated':
40037
- comments = comments.sort(sortByFirstCreated);
40038
- break;
40039
- case 'lastCreated':
40040
- default:
40041
- comments = comments.sort(sortByLastCreated);
40042
- break;
40043
- }
40044
- return comments;
40045
- }
40046
- }
40389
+ const hardDeletePost = async (postId) => {
40390
+ const client = getActiveClient();
40391
+ client.log('post/hardDeletePost', postId);
40392
+ const hardDeleted = await deletePost(postId, true);
40393
+ return LinkedObject.post(hardDeleted);
40394
+ };
40395
+ /* end_public_function */
40047
40396
 
40048
40397
  /* begin_public_function
40049
- id: comment.query
40398
+ id: post.approve
40050
40399
  */
40051
40400
  /**
40052
40401
  * ```js
40053
- * import { getComments } from '@amityco/ts-sdk'
40402
+ * import { approvePost } from '@amityco/ts-sdk'
40054
40403
  *
40055
- * let comments = []
40056
- * const unsub = getComments({
40057
- * referenceType: Amity.InternalComment['referenceType'];
40058
- * referenceId: Amity.InternalComment['referenceId'];
40059
- * }, response => merge(comments, response.data))
40404
+ * const { data: post } = await approvePost('postId')
40060
40405
  * ```
40061
40406
  *
40062
- * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
40407
+ * Approves a {@link Amity.Post}
40063
40408
  *
40064
- * @param referenceType the type of the target
40065
- * @param referenceId the ID of the target
40066
- * @param callback the function to call when new data are available
40067
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
40409
+ * @param postId The {@link Amity.Post} ID to be approved
40410
+ * @return A {@link Amity.Post} that was approved
40068
40411
  *
40069
- * @category Comments Live Collection
40412
+ * @category Post API
40413
+ * @async
40070
40414
  */
40071
- const getComments = (params, callback, config) => {
40072
- const { log, cache } = getActiveClient();
40073
- if (!cache) {
40074
- console.log('For using Live Collection feature you need to enable Cache!');
40415
+ const approvePost = async (postId) => {
40416
+ const client = getActiveClient();
40417
+ client.log('post/approvePost', postId);
40418
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/approve`);
40419
+ fireEvent('post.approved', payload);
40420
+ // fire virtual event for community update
40421
+ if (payload.posts[0].targetType === 'community') {
40422
+ fireEvent('community.updated', payload);
40075
40423
  }
40076
- const timestamp = Date.now();
40077
- log(`getComments(tmpid: ${timestamp}) > listen`);
40078
- const commentsLiveCollection = new CommentLiveCollectionController(params, callback);
40079
- const disposers = commentsLiveCollection.startSubscription();
40080
- const cacheKey = commentsLiveCollection.getCacheKey();
40081
- disposers.push(() => dropFromCache(cacheKey));
40082
- return () => {
40083
- log(`getComments(tmpid: ${timestamp}) > dispose`);
40084
- disposers.forEach(fn => fn());
40424
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40425
+ const cachedAt = client.cache && Date.now();
40426
+ if (client.cache)
40427
+ ingestInCache(data, { cachedAt });
40428
+ return {
40429
+ data: LinkedObject.post(data.posts.find(post => post.postId === postId)),
40430
+ cachedAt,
40085
40431
  };
40086
40432
  };
40087
40433
  /* end_public_function */
40088
40434
 
40089
- var index$8 = /*#__PURE__*/Object.freeze({
40090
- __proto__: null,
40091
- getCommentByIds: getCommentByIds,
40092
- createComment: createComment,
40093
- updateComment: updateComment,
40094
- deleteComment: deleteComment,
40095
- softDeleteComment: softDeleteComment,
40096
- hardDeleteComment: hardDeleteComment,
40097
- flagComment: flagComment,
40098
- unflagComment: unflagComment,
40099
- isCommentFlaggedByMe: isCommentFlaggedByMe,
40100
- onCommentCreated: onCommentCreated,
40101
- onCommentUpdated: onCommentUpdated,
40102
- onCommentDeleted: onCommentDeleted,
40103
- onCommentFlagged: onCommentFlagged,
40104
- onCommentUnflagged: onCommentUnflagged,
40105
- onCommentReactionAdded: onCommentReactionAdded,
40106
- onCommentReactionRemoved: onCommentReactionRemoved,
40107
- getComment: getComment,
40108
- getComments: getComments
40109
- });
40110
-
40435
+ /* begin_public_function
40436
+ id: post.decline
40437
+ */
40111
40438
  /**
40112
40439
  * ```js
40113
- * import { onPostUpdatedLocal } from '@amityco/ts-sdk'
40114
- * const dispose = onPostUpdatedLocal(post => {
40115
- * // ...
40116
- * })
40440
+ * import { declinePost } from '@amityco/ts-sdk'
40441
+ *
40442
+ * const {data: post} = await declinePost('postId')
40117
40443
  * ```
40118
40444
  *
40119
- * Fired when a {@link Amity.InternalPost} has been updated
40445
+ * Declines a {@link Amity.Post}
40120
40446
  *
40121
- * @param callback The function to call when the event was fired
40122
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40447
+ * @param postId The {@link Amity.Post} ID to be declined
40448
+ * @return A {@link Amity.Post} that was declined
40123
40449
  *
40124
- * @category Post Events
40450
+ * @category Post API
40451
+ * @async
40125
40452
  */
40126
- const onPostUpdatedLocal = (callback) => createLocalPostEventSubscriber('local.post.updated', callback);
40453
+ const declinePost = async (postId) => {
40454
+ const client = getActiveClient();
40455
+ client.log('post/declinePost', postId);
40456
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/decline`);
40457
+ // fire virtual event
40458
+ if (payload.posts[0].targetType === 'community') {
40459
+ fireEvent('community.updated', payload);
40460
+ }
40461
+ fireEvent('post.declined', payload);
40462
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40463
+ const cachedAt = client.cache && Date.now();
40464
+ if (client.cache)
40465
+ ingestInCache(data, { cachedAt });
40466
+ return {
40467
+ data: LinkedObject.post(payload.posts.find(post => post.postId === postId)),
40468
+ cachedAt,
40469
+ };
40470
+ };
40471
+ /* end_public_function */
40127
40472
 
40473
+ /* begin_public_function
40474
+ id: post.flag
40475
+ */
40128
40476
  /**
40129
40477
  * ```js
40130
- * import { onLocalPostReactionAdded } from '@amityco/ts-sdk'
40131
- * const dispose = onPostReactionAdded(post => {
40132
- * // ...
40133
- * })
40478
+ * import { PostRepository } from '@amityco/ts-sdk'
40479
+ * const flagged = await PostRepository.flagPost(postId, reason)
40134
40480
  * ```
40135
40481
  *
40136
- * Fired when a {@link Amity.InternalPost} has been reacted
40137
- *
40138
- * @param callback The function to call when the event was fired
40139
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40482
+ * @param postId of the post to flag
40483
+ * @param reason the reason to flag the post
40484
+ * @returns a boolean
40140
40485
  *
40141
- * @category Post Events
40142
- */
40143
- const onLocalPostReactionAdded = (callback) => {
40486
+ * @category Post API
40487
+ * @async
40488
+ * */
40489
+ const flagPost = async (postId, reason) => {
40144
40490
  const client = getActiveClient();
40145
- const filter = ({ post }) => {
40146
- if (!client.cache) {
40147
- callback(post);
40148
- }
40149
- else {
40150
- upsertInCache(['post', 'get', post.postId], post);
40151
- callback(post);
40152
- }
40491
+ client.log('post/flagPost', postId);
40492
+ const isPredefinedReason = reason &&
40493
+ Object.entries(ContentFlagReasonEnum).some(([key, value]) => key !== ContentFlagReasonEnum.Others && value === reason);
40494
+ const body = {
40495
+ reason: reason && isPredefinedReason ? reason : ContentFlagReasonEnum.Others,
40496
+ detail: reason && !isPredefinedReason ? reason : '',
40153
40497
  };
40154
- return createEventSubscriber(client, 'local.post.addReaction', 'local.post.addReaction', filter);
40155
- };
40498
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/flag`, body);
40499
+ if (client.cache) {
40500
+ ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
40501
+ }
40502
+ fireEvent('post.flagged', payload);
40503
+ return !!payload;
40504
+ };
40505
+ /* end_public_function */
40156
40506
 
40507
+ /* begin_public_function
40508
+ id: post.unflag
40509
+ */
40157
40510
  /**
40158
40511
  * ```js
40159
- * import { onLocalPostReactionRemoved } from '@amityco/ts-sdk'
40160
- * const dispose = onPostReactionRemoved(post => {
40161
- * // ...
40162
- * })
40512
+ * import { PostRepository } from '@amityco/ts-sdk'
40513
+ * const unflagged = await PostRepository.unflagPost(postId)
40163
40514
  * ```
40164
40515
  *
40165
- * Fired when a {@link Amity.InternalPost} has been reacted
40516
+ * @param postId of the post to unflag
40517
+ * @returns the unflag post result
40166
40518
  *
40167
- * @param callback The function to call when the event was fired
40168
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40519
+ * @category Post API
40520
+ * @async
40521
+ * */
40522
+ const unflagPost = async (postId) => {
40523
+ const client = getActiveClient();
40524
+ client.log('post/unflagPost', postId);
40525
+ const { data: payload } = await client.http.delete(`/api/v3/posts/${encodeURIComponent(postId)}/unflag`);
40526
+ if (client.cache) {
40527
+ ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
40528
+ }
40529
+ fireEvent('post.unflagged', payload);
40530
+ return !!payload;
40531
+ };
40532
+ /* end_public_function */
40533
+
40534
+ /* begin_public_function
40535
+ id: post.check_flag_by_me
40536
+ */
40537
+ /**
40538
+ * ```js
40539
+ * import { PostRepository } from '@amityco/ts-sdk'
40540
+ * const isReported = await PostRepository.isPostFlaggedByMe('post', postId)
40541
+ * ```
40169
40542
  *
40170
- * @category Post Events
40171
- */
40172
- const onLocalPostReactionRemoved = (callback) => {
40543
+ * @param postId of the post to check if flagged by current user
40544
+ * @returns `true` if the post is flagged by me, `false` if doesn't.
40545
+ *
40546
+ * @category Post API
40547
+ * @async
40548
+ * */
40549
+ const isPostFlaggedByMe = async (postId) => {
40173
40550
  const client = getActiveClient();
40174
- const filter = ({ post }) => {
40175
- if (!client.cache) {
40176
- callback(post);
40177
- }
40178
- else {
40179
- upsertInCache(['post', 'get', post.postId], post);
40180
- callback(post);
40181
- }
40182
- };
40183
- return createEventSubscriber(client, 'local.post.removeReaction', 'local.post.removeReaction', filter);
40184
- };
40551
+ client.log('post/isPostFlaggedByMe', postId);
40552
+ const { data: { result }, } = await client.http.get(`/api/v3/posts/${postId}/isflagbyme`);
40553
+ return result;
40554
+ };
40555
+ /* end_public_function */
40185
40556
 
40557
+ /* begin_public_function
40558
+ id: post.create.clip_post
40559
+ */
40186
40560
  /**
40187
40561
  * ```js
40188
- * import { onLocalPostDeleted } from '@amityco/ts-sdk'
40189
- * const dispose = onLocalPostDeleted(post => {
40190
- * // ...
40191
- * })
40562
+ * import { PostRepository } from '@amityco/ts-sdk'
40563
+ * const created = await PostRepository.createClipPost({
40564
+ * targetType: 'user',
40565
+ * targetId: 'foobar',
40566
+ * dataType: 'clip',
40567
+ * data: { text: 'hello world' },
40568
+ * attachments: [{ type: 'clip', fileId: 'fileId123', displayMode: 'fill', isMuted: false }]
40569
+ * }))
40192
40570
  * ```
40193
40571
  *
40194
- * Fired when a {@link Amity.InternalPost} has been deleted
40572
+ * Creates an {@link Amity.Post}
40195
40573
  *
40196
- * @param callback The function to call when the event was fired
40197
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40574
+ * @param bundle The data necessary to create a new {@link Amity.Post}
40575
+ * @returns The newly created {@link Amity.Post}
40198
40576
  *
40199
- * @category Post Events
40577
+ * @category Post API
40578
+ * @async
40200
40579
  */
40201
- const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.post.deleted', callback);
40580
+ const createClipPost = async (bundle) => {
40581
+ const client = getActiveClient();
40582
+ client.log('post/createPost', bundle);
40583
+ const { data: payload } = await client.http.post('/api/v4/posts', bundle);
40584
+ fireEvent('post.created', payload);
40585
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40586
+ const cachedAt = client.cache && Date.now();
40587
+ if (client.cache)
40588
+ ingestInCache(data, { cachedAt });
40589
+ const { posts } = data;
40590
+ return {
40591
+ data: LinkedObject.post(posts[0]),
40592
+ cachedAt,
40593
+ };
40594
+ };
40595
+ /* end_public_function */
40202
40596
 
40203
40597
  /* begin_public_function
40204
40598
  id: post.get
@@ -40222,7 +40616,7 @@ const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.p
40222
40616
  *
40223
40617
  * @category Post Live Object
40224
40618
  */
40225
- const getPost$1 = (postId, callback) => {
40619
+ const getPost = (postId, callback) => {
40226
40620
  const responder = (snapshot) => {
40227
40621
  const { data } = snapshot;
40228
40622
  callback(Object.assign(Object.assign({}, snapshot), { data: data ? LinkedObject.post(snapshot.data) : data }));
@@ -40296,7 +40690,7 @@ class PostPaginationController extends PaginationController {
40296
40690
  type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
40297
40691
  };
40298
40692
  const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
40299
- const { data: queryResponse } = await this.http.get(`/api/v4/posts`, {
40693
+ const { data: queryResponse } = await this.http.get(`/api/v5/posts`, {
40300
40694
  params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
40301
40695
  /*
40302
40696
  * when creating post like image, file, video BE will create 2 posts
@@ -40311,19 +40705,6 @@ class PostPaginationController extends PaginationController {
40311
40705
  }
40312
40706
  }
40313
40707
 
40314
- var EnumPostActions;
40315
- (function (EnumPostActions) {
40316
- EnumPostActions["OnPostCreated"] = "onPostCreated";
40317
- EnumPostActions["OnPostUpdated"] = "onPostUpdated";
40318
- EnumPostActions["OnPostDeleted"] = "onPostDeleted";
40319
- EnumPostActions["OnPostFlagged"] = "onPostFlagged";
40320
- EnumPostActions["OnPostUnflagged"] = "onPostUnflagged";
40321
- EnumPostActions["OnPostReactionAdded"] = "onPostReactionAdded";
40322
- EnumPostActions["OnPostReactionRemoved"] = "onPostReactionRemoved";
40323
- EnumPostActions["OnPostApproved"] = "onPostApproved";
40324
- EnumPostActions["OnPostDeclined"] = "onPostDeclined";
40325
- })(EnumPostActions || (EnumPostActions = {}));
40326
-
40327
40708
  class PostQueryStreamController extends QueryStreamController {
40328
40709
  constructor(query, cacheKey, notifyChange, preparePayload) {
40329
40710
  super(query, cacheKey);
@@ -40389,45 +40770,50 @@ class PostQueryStreamController extends QueryStreamController {
40389
40770
  }
40390
40771
  }
40391
40772
 
40392
- const getPost = async (postId) => {
40393
- const client = getActiveClient();
40394
- client.log('post/getPost', postId);
40395
- isInTombstone('post', postId);
40396
- let payload;
40397
- try {
40398
- // API-FIX: endpoint should not be /list, parameters should be querystring.
40399
- const response = await client.http.get(`/api/v3/posts/${encodeURIComponent(postId)}`);
40400
- payload = response.data;
40401
- }
40402
- catch (error) {
40403
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
40404
- pushToTombstone('post', postId);
40405
- }
40406
- throw error;
40407
- }
40408
- const data = prepareMembershipPayload(payload, 'communityUsers');
40409
- const cachedAt = client.cache && Date.now();
40410
- if (client.cache)
40411
- ingestInCache(data, { cachedAt });
40412
- const { posts } = data;
40413
- const result = posts.find(post => post.postId === postId);
40414
- return {
40415
- data: result,
40416
- cachedAt,
40417
- };
40773
+ const commentEventHanlder = (callback, eventHandler, cacheKey, resolveId) => {
40774
+ return eventHandler(async (comment) => {
40775
+ var _a;
40776
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40777
+ if (!currentCollection ||
40778
+ !currentCollection.data.includes(resolveId ? resolveId(comment.referenceId) : comment.referenceId))
40779
+ return;
40780
+ await getPost$1(comment.referenceId);
40781
+ callback(comment);
40782
+ });
40418
40783
  };
40419
- getPost.locally = (postId) => {
40420
- const client = getActiveClient();
40421
- client.log('post/getPost.locally', postId);
40422
- if (!client.cache)
40423
- return;
40424
- const cached = pullFromCache(['post', 'get', postId]);
40425
- if (!cached)
40426
- return;
40427
- return {
40428
- data: cached.data,
40429
- cachedAt: cached.cachedAt,
40430
- };
40784
+ const generateCommentSubscriptions = ({ cacheKey, resolveId, }) => {
40785
+ const eventHandlers = [
40786
+ onCommentCreated,
40787
+ onCommentDeleted,
40788
+ onCommentReactionAdded,
40789
+ onCommentReactionRemoved,
40790
+ onCommentCreatedLocal,
40791
+ onCommentDeleteLocal,
40792
+ onLocalCommentReactionAdded,
40793
+ onLocalCommentReactionRemoved,
40794
+ ];
40795
+ return eventHandlers.map(handler => ({
40796
+ fn: convertEventPayload((callback) => commentEventHanlder(callback, handler, cacheKey, resolveId), 'referenceId', 'post'),
40797
+ action: EnumPostActions.OnPostUpdated,
40798
+ }));
40799
+ };
40800
+ const getPostSubscription = (cacheKey) => {
40801
+ return [
40802
+ { fn: onPostCreated, action: EnumPostActions.OnPostCreated },
40803
+ { fn: onPostUpdated, action: EnumPostActions.OnPostUpdated },
40804
+ { fn: onPostUpdatedLocal, action: EnumPostActions.OnPostUpdated },
40805
+ { fn: onPostDeleted, action: EnumPostActions.OnPostDeleted },
40806
+ { fn: onPostFlagged, action: EnumPostActions.OnPostFlagged },
40807
+ { fn: onPostUnflagged, action: EnumPostActions.OnPostUnflagged },
40808
+ { fn: onPostApproved, action: EnumPostActions.OnPostApproved },
40809
+ { fn: onPostDeclined, action: EnumPostActions.OnPostDeclined },
40810
+ { fn: onPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
40811
+ { fn: onPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
40812
+ { fn: onLocalPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
40813
+ { fn: onLocalPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
40814
+ { fn: onLocalPostDeleted, action: EnumPostActions.OnPostDeleted },
40815
+ ...generateCommentSubscriptions({ cacheKey }),
40816
+ ];
40431
40817
  };
40432
40818
 
40433
40819
  class PostLiveCollectionController extends LiveCollectionController {
@@ -40458,47 +40844,7 @@ class PostLiveCollectionController extends LiveCollectionController {
40458
40844
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
40459
40845
  }
40460
40846
  startSubscription() {
40461
- return this.queryStreamController.subscribeRTE([
40462
- { fn: onPostCreated, action: EnumPostActions.OnPostCreated },
40463
- { fn: onPostUpdated, action: EnumPostActions.OnPostUpdated },
40464
- { fn: onPostUpdatedLocal, action: EnumPostActions.OnPostUpdated },
40465
- { fn: onPostDeleted, action: EnumPostActions.OnPostDeleted },
40466
- { fn: onPostFlagged, action: EnumPostActions.OnPostFlagged },
40467
- { fn: onPostUnflagged, action: EnumPostActions.OnPostUnflagged },
40468
- { fn: onPostApproved, action: EnumPostActions.OnPostApproved },
40469
- { fn: onPostDeclined, action: EnumPostActions.OnPostDeclined },
40470
- { fn: onPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
40471
- { fn: onPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
40472
- { fn: onLocalPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
40473
- { fn: onLocalPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
40474
- { fn: onLocalPostDeleted, action: EnumPostActions.OnPostDeleted },
40475
- {
40476
- fn: convertEventPayload((callback) => {
40477
- return onCommentCreated(async (comment) => {
40478
- var _a;
40479
- const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40480
- if (!currentCollection || currentCollection.data.includes(comment.referenceId))
40481
- return;
40482
- await getPost(comment.referenceId);
40483
- callback(comment);
40484
- });
40485
- }, 'referenceId', 'post'),
40486
- action: EnumPostActions.OnPostUpdated,
40487
- },
40488
- {
40489
- fn: convertEventPayload((callback) => {
40490
- return onCommentDeleted(async (comment) => {
40491
- var _a;
40492
- const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40493
- if (!currentCollection || currentCollection.data.includes(comment.referenceId))
40494
- return;
40495
- await getPost(comment.referenceId);
40496
- callback(comment);
40497
- });
40498
- }, 'referenceId', 'post'),
40499
- action: EnumPostActions.OnPostUpdated,
40500
- },
40501
- ]);
40847
+ return this.queryStreamController.subscribeRTE(getPostSubscription(this.cacheKey));
40502
40848
  }
40503
40849
  notifyChange({ origin, loading, error }) {
40504
40850
  var _a, _b;
@@ -40633,6 +40979,22 @@ class PinnedPostQueryStreamController extends QueryStreamController {
40633
40979
  });
40634
40980
  }
40635
40981
  }
40982
+ reactor(action) {
40983
+ return (post) => {
40984
+ var _a;
40985
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40986
+ if (!collection)
40987
+ return;
40988
+ if (action === EnumPostActions.OnPostDeleted) {
40989
+ collection.data = collection.data.filter(referenceId => referenceId !== `global#${post.postId}`);
40990
+ }
40991
+ pushToCache(this.cacheKey, collection);
40992
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
40993
+ };
40994
+ }
40995
+ subscribeRTE(createSubscriber) {
40996
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
40997
+ }
40636
40998
  }
40637
40999
 
40638
41000
  class PinnedPostLiveCollectionController extends LiveCollectionController {
@@ -40664,7 +41026,10 @@ class PinnedPostLiveCollectionController extends LiveCollectionController {
40664
41026
  }
40665
41027
  // eslint-disable-next-line class-methods-use-this
40666
41028
  startSubscription() {
40667
- return [];
41029
+ return this.queryStreamController.subscribeRTE(generateCommentSubscriptions({
41030
+ cacheKey: this.cacheKey,
41031
+ resolveId: id => `${this.query.placement}#${id}`,
41032
+ }));
40668
41033
  }
40669
41034
  notifyChange({ origin, loading, error }) {
40670
41035
  var _a, _b;
@@ -40816,6 +41181,10 @@ class GlobalPinnedPostLiveCollectionController extends LiveCollectionController
40816
41181
  fn: onPostDeleted,
40817
41182
  action: EnumPostActions.OnPostDeleted,
40818
41183
  },
41184
+ ...generateCommentSubscriptions({
41185
+ cacheKey: this.cacheKey,
41186
+ resolveId: id => `global#${id}`,
41187
+ }),
40819
41188
  ]);
40820
41189
  }
40821
41190
  notifyChange({ origin, loading, error }) {
@@ -41108,6 +41477,7 @@ var index$7 = /*#__PURE__*/Object.freeze({
41108
41477
  flagPost: flagPost,
41109
41478
  unflagPost: unflagPost,
41110
41479
  isPostFlaggedByMe: isPostFlaggedByMe,
41480
+ createClipPost: createClipPost,
41111
41481
  onPostCreated: onPostCreated,
41112
41482
  onPostUpdated: onPostUpdated,
41113
41483
  onPostDeleted: onPostDeleted,
@@ -41117,7 +41487,7 @@ var index$7 = /*#__PURE__*/Object.freeze({
41117
41487
  onPostUnflagged: onPostUnflagged,
41118
41488
  onPostReactionAdded: onPostReactionAdded,
41119
41489
  onPostReactionRemoved: onPostReactionRemoved,
41120
- getPost: getPost$1,
41490
+ getPost: getPost,
41121
41491
  getPosts: getPosts,
41122
41492
  getPinnedPosts: getPinnedPosts,
41123
41493
  getGlobalPinnedPosts: getGlobalPinnedPosts,
@@ -44097,4 +44467,4 @@ var index = /*#__PURE__*/Object.freeze({
44097
44467
  getMyCommunityInvitations: getMyCommunityInvitations
44098
44468
  });
44099
44469
 
44100
- export { API_REGIONS, index$2 as AdRepository, index$a as CategoryRepository, index$e as ChannelRepository, index$n as Client, index$8 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$b as CommunityRepository, ContentFeedType, ContentFlagReasonEnum, DefaultCommunityPostSetting, index$9 as FeedRepository, FileAccessTypeEnum, index$k as FileRepository, FileType, index as InvitationRepository, InvitationSortByEnum, InvitationStatusEnum, InvitationTypeEnum, JoinRequestStatusEnum, JoinResultStatusEnum, index$4 as LiveStreamPlayer, MembershipAcceptanceTypeEnum, MessageContentType, index$i as MessageRepository, index$5 as PollRepository, PostContentType, index$7 as PostRepository, index$j as ReactionRepository, index$3 as StoryRepository, index$6 as StreamRepository, index$h as SubChannelRepository, SubscriptionLevels, index$l as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, index$1 as notificationTray, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };
44470
+ export { API_REGIONS, index$2 as AdRepository, index$a as CategoryRepository, index$e as ChannelRepository, index$n as Client, index$9 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$b as CommunityRepository, ContentFeedType, ContentFlagReasonEnum, DefaultCommunityPostSetting, index$8 as FeedRepository, FileAccessTypeEnum, index$k as FileRepository, FileType, index as InvitationRepository, InvitationSortByEnum, InvitationStatusEnum, InvitationTypeEnum, JoinRequestStatusEnum, JoinResultStatusEnum, index$4 as LiveStreamPlayer, MembershipAcceptanceTypeEnum, MessageContentType, index$i as MessageRepository, index$5 as PollRepository, PostContentType, index$7 as PostRepository, index$j as ReactionRepository, index$3 as StoryRepository, index$6 as StreamRepository, index$h as SubChannelRepository, SubscriptionLevels, index$l as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, index$1 as notificationTray, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };