@amityco/ts-sdk 7.7.1-bd711609.0 → 7.7.1-c6a1e2a.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 (76) hide show
  1. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/core/payload.d.ts +8 -3
  2. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/core/payload.d.ts.map +1 -1
  3. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/core/payload.js.map +1 -1
  4. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/domains/feed.d.ts +0 -31
  5. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/domains/feed.d.ts.map +1 -1
  6. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/domains/feed.js +1 -21
  7. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/domains/feed.js.map +1 -1
  8. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/channelRepository/events/onChannelSetMuted.d.ts.map +1 -1
  9. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/channelRepository/events/onChannelSetMuted.js +6 -8
  10. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/channelRepository/events/onChannelSetMuted.js.map +1 -1
  11. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/index.d.ts +0 -1
  12. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/index.d.ts.map +1 -1
  13. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/index.js +0 -1
  14. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/index.js.map +1 -1
  15. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/streamRepository/events/onStreamViewerBanned.d.ts.map +1 -1
  16. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/streamRepository/events/onStreamViewerBanned.js +5 -8
  17. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/streamRepository/events/onStreamViewerBanned.js.map +1 -1
  18. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/streamRepository/events/onStreamViewerUnbanned.d.ts.map +1 -1
  19. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/streamRepository/events/onStreamViewerUnbanned.js +3 -6
  20. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/streamRepository/events/onStreamViewerUnbanned.js.map +1 -1
  21. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/tsconfig.tsbuildinfo +1 -1
  22. package/dist/@types/core/payload.d.ts +8 -3
  23. package/dist/@types/core/payload.d.ts.map +1 -1
  24. package/dist/@types/domains/feed.d.ts +0 -31
  25. package/dist/@types/domains/feed.d.ts.map +1 -1
  26. package/dist/channelRepository/events/onChannelSetMuted.d.ts.map +1 -1
  27. package/dist/feedRepository/index.d.ts +0 -1
  28. package/dist/feedRepository/index.d.ts.map +1 -1
  29. package/dist/index.cjs.js +1104 -1349
  30. package/dist/index.esm.js +1103 -1348
  31. package/dist/index.umd.js +1 -1
  32. package/dist/streamRepository/events/onStreamViewerBanned.d.ts.map +1 -1
  33. package/dist/streamRepository/events/onStreamViewerUnbanned.d.ts.map +1 -1
  34. package/package.json +1 -1
  35. package/src/@types/core/payload.ts +4 -3
  36. package/src/@types/domains/feed.ts +0 -43
  37. package/src/channelRepository/events/onChannelSetMuted.ts +6 -8
  38. package/src/feedRepository/index.ts +0 -1
  39. package/src/streamRepository/events/onStreamViewerBanned.ts +5 -8
  40. package/src/streamRepository/events/onStreamViewerUnbanned.ts +4 -6
  41. package/tsconfig.tsbuildinfo +1 -1
  42. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/LiveCollectionController.d.ts +0 -14
  43. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/LiveCollectionController.d.ts.map +0 -1
  44. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/LiveCollectionController.js +0 -129
  45. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/LiveCollectionController.js.map +0 -1
  46. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/PaginationController.d.ts +0 -5
  47. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/PaginationController.d.ts.map +0 -1
  48. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/PaginationController.js +0 -15
  49. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/PaginationController.js.map +0 -1
  50. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/QueryStreamController.d.ts +0 -15
  51. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/QueryStreamController.d.ts.map +0 -1
  52. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/QueryStreamController.js +0 -78
  53. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/QueryStreamController.js.map +0 -1
  54. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed.d.ts +0 -23
  55. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed.d.ts.map +0 -1
  56. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed.js +0 -46
  57. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed.js.map +0 -1
  58. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/index.d.ts +0 -2
  59. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/index.d.ts.map +0 -1
  60. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/index.js +0 -2
  61. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/index.js.map +0 -1
  62. package/dist/feedRepository/observers/getUserFeed/LiveCollectionController.d.ts +0 -14
  63. package/dist/feedRepository/observers/getUserFeed/LiveCollectionController.d.ts.map +0 -1
  64. package/dist/feedRepository/observers/getUserFeed/PaginationController.d.ts +0 -5
  65. package/dist/feedRepository/observers/getUserFeed/PaginationController.d.ts.map +0 -1
  66. package/dist/feedRepository/observers/getUserFeed/QueryStreamController.d.ts +0 -15
  67. package/dist/feedRepository/observers/getUserFeed/QueryStreamController.d.ts.map +0 -1
  68. package/dist/feedRepository/observers/getUserFeed.d.ts +0 -23
  69. package/dist/feedRepository/observers/getUserFeed.d.ts.map +0 -1
  70. package/dist/feedRepository/observers/index.d.ts +0 -2
  71. package/dist/feedRepository/observers/index.d.ts.map +0 -1
  72. package/src/feedRepository/observers/getUserFeed/LiveCollectionController.ts +0 -193
  73. package/src/feedRepository/observers/getUserFeed/PaginationController.ts +0 -37
  74. package/src/feedRepository/observers/getUserFeed/QueryStreamController.ts +0 -119
  75. package/src/feedRepository/observers/getUserFeed.ts +0 -56
  76. package/src/feedRepository/observers/index.ts +0 -1
package/dist/index.cjs.js CHANGED
@@ -6362,19 +6362,17 @@ const dispose$7 = (cb) => {
6362
6362
  const onChannelSetMuted = (callback) => {
6363
6363
  if (callbacks$7.length === 0) {
6364
6364
  const client = getActiveClient();
6365
- const filter = async (payloads) => {
6365
+ const filter = async (payload) => {
6366
6366
  var _a;
6367
- payloads.forEach(payload => {
6368
- upsertInCache(['channel', 'get', payload.channelId], {
6369
- // If muteTimeout > now => user is muted
6370
- // Otherwise => user is unmuted
6371
- isMuted: Date.parse(payload.muteTimeout) > Date.now(),
6372
- });
6367
+ upsertInCache(['channel', 'get', payload.channelId], {
6368
+ // If muteTimeout > now => user is muted
6369
+ // Otherwise => user is unmuted
6370
+ isMuted: Date.parse(payload.muteTimeout) > Date.now(),
6373
6371
  });
6374
6372
  const channel = (_a = pullFromCache([
6375
6373
  'channel',
6376
6374
  'get',
6377
- payloads[0].channelId,
6375
+ payload.channelId,
6378
6376
  ])) === null || _a === void 0 ? void 0 : _a.data;
6379
6377
  if (channel) {
6380
6378
  callbacks$7.forEach(cb => cb(channel));
@@ -17737,23 +17735,20 @@ const onStreamViewerBanned = (callback) => {
17737
17735
  const client = getActiveClient();
17738
17736
  const filter = (payloads) => {
17739
17737
  var _a;
17740
- payloads.forEach(streamBanned => {
17738
+ const { list } = payloads;
17739
+ list.forEach(payload => {
17741
17740
  var _a;
17742
- mergeInCache(['stream', 'get', streamBanned.streamId], { watcherUrl: null });
17741
+ mergeInCache(['stream', 'get', payload.streamId], { watcherUrl: null });
17743
17742
  // Update isDeleted = true in banned user's messages
17744
17743
  const messageCache = (_a = queryCache(['message', 'get'])) === null || _a === void 0 ? void 0 : _a.filter(
17745
17744
  // Check if creator id and user id are internal or external id
17746
- ({ data }) => data.creatorId === streamBanned.userId);
17745
+ ({ data }) => data.creatorId === payload.userId);
17747
17746
  // Update isDeleted for each relavant messages
17748
17747
  messageCache === null || messageCache === void 0 ? void 0 : messageCache.forEach(message => {
17749
17748
  mergeInCache(message.key, { isDeleted: true });
17750
17749
  });
17751
17750
  });
17752
- const stream = (_a = pullFromCache([
17753
- 'stream',
17754
- 'get',
17755
- payloads[0].streamId,
17756
- ])) === null || _a === void 0 ? void 0 : _a.data;
17751
+ const stream = (_a = pullFromCache(['stream', 'get', list[0].streamId])) === null || _a === void 0 ? void 0 : _a.data;
17757
17752
  if (!stream)
17758
17753
  return;
17759
17754
  callback(stream);
@@ -23181,1035 +23176,1010 @@ getCustomRankingGlobalFeed.locally = (query) => {
23181
23176
  : undefined;
23182
23177
  };
23183
23178
 
23184
- class UserFeedPaginationController extends PaginationController {
23185
- async getRequest(queryParams, token) {
23186
- const { userId, feedSources, dataTypes, includeDeleted, matchingOnlyParentPost, limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["userId", "feedSources", "dataTypes", "includeDeleted", "matchingOnlyParentPost", "limit"]);
23187
- const options = token ? { token } : { limit };
23188
- const { data: queryResponse } = await this.http.get(`/api/v4/user-feeds/${userId}`, {
23189
- params: Object.assign(Object.assign({}, params), { options, dataTypes: (dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length) ? dataTypes : undefined, includePostedFeed: feedSources, isDeleted: inferIsDeleted(includeDeleted), matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length) }),
23190
- });
23191
- return queryResponse;
23192
- }
23193
- }
23194
-
23195
- var EnumPostActions;
23196
- (function (EnumPostActions) {
23197
- EnumPostActions["OnPostCreated"] = "onPostCreated";
23198
- EnumPostActions["OnPostUpdated"] = "onPostUpdated";
23199
- EnumPostActions["OnPostDeleted"] = "onPostDeleted";
23200
- EnumPostActions["OnPostFlagged"] = "onPostFlagged";
23201
- EnumPostActions["OnPostUnflagged"] = "onPostUnflagged";
23202
- EnumPostActions["OnPostReactionAdded"] = "onPostReactionAdded";
23203
- EnumPostActions["OnPostReactionRemoved"] = "onPostReactionRemoved";
23204
- EnumPostActions["OnPostApproved"] = "onPostApproved";
23205
- EnumPostActions["OnPostDeclined"] = "onPostDeclined";
23206
- })(EnumPostActions || (EnumPostActions = {}));
23207
-
23208
- class UserFeedQueryStreamController extends QueryStreamController {
23209
- constructor(query, cacheKey, notifyChange, preparePayload) {
23210
- super(query, cacheKey);
23211
- this.notifyChange = notifyChange;
23212
- this.preparePayload = preparePayload;
23213
- }
23214
- async saveToMainDB(response) {
23215
- const processedPayload = await this.preparePayload(response);
23216
- const client = getActiveClient();
23217
- const cachedAt = client.cache && Date.now();
23218
- if (client.cache) {
23219
- ingestInCache(processedPayload, { cachedAt });
23220
- }
23221
- }
23222
- appendToQueryStream(response, direction, refresh = false) {
23223
- var _a, _b;
23224
- if (refresh) {
23225
- pushToCache(this.cacheKey, {
23226
- data: response.posts.map(getResolver('post')),
23227
- });
23228
- }
23229
- else {
23230
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23231
- const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
23232
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...posts, ...response.posts.map(getResolver('post'))])] }));
23233
- }
23234
- }
23235
- reactor(action) {
23236
- return (post) => {
23237
- var _a, _b;
23238
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23239
- if (!collection)
23240
- return;
23241
- // if the collection is parent post collection and
23242
- // post is not included in the collection or post is child post
23243
- if ((!this.query.dataTypes || this.query.dataTypes.length === 0) &&
23244
- !collection.data.includes(post.parentPostId ? post.parentPostId : post.postId))
23245
- return;
23246
- if (action === EnumPostActions.OnPostDeleted) {
23247
- collection.data = collection.data.filter(postId => postId !== post.postId);
23248
- }
23249
- if (post.parentPostId && post.isDeleted) {
23250
- const parentPost = (_b = pullFromCache([
23251
- 'post',
23252
- 'get',
23253
- post.parentPostId,
23254
- ])) === null || _b === void 0 ? void 0 : _b.data;
23255
- if (!parentPost)
23256
- return;
23257
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
23258
- pushToCache(['post', 'get', parentPost.postId], parentPost);
23259
- }
23260
- if (action === EnumPostActions.OnPostDeclined) {
23261
- collection.data = collection.data.filter(postId => postId !== post.postId);
23262
- }
23263
- if (action === EnumPostActions.OnPostCreated || action === EnumPostActions.OnPostApproved) {
23264
- if (this.query.dataTypes &&
23265
- this.query.dataTypes.length > 0 &&
23266
- !this.query.dataTypes.includes(post.dataType)) {
23267
- return;
23268
- }
23269
- collection.data = [...new Set([post.postId, ...collection.data])];
23270
- }
23271
- pushToCache(this.cacheKey, collection);
23272
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
23273
- };
23274
- }
23275
- subscribeRTE(createSubscriber) {
23276
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
23277
- }
23278
- }
23179
+ var index$a = /*#__PURE__*/Object.freeze({
23180
+ __proto__: null,
23181
+ queryGlobalFeed: queryGlobalFeed,
23182
+ getCustomRankingGlobalFeed: getCustomRankingGlobalFeed
23183
+ });
23279
23184
 
23280
23185
  /* begin_public_function
23281
- id: comment.get_by_ids
23186
+ id: post.get_by_ids
23282
23187
  */
23283
23188
  /**
23284
23189
  * ```js
23285
- * import { CommentRepository } from '@amityco/ts-sdk'
23286
- * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
23190
+ * import { getPostByIds } from '@amityco/ts-sdk'
23191
+ * const { data: posts } = await getPostByIds(['foo', 'bar'])
23287
23192
  * ```
23288
23193
  *
23289
- * Fetches a collection of {@link Amity.Comment} objects
23194
+ * Fetches a collection of {@link Amity.Post} objects
23290
23195
  *
23291
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
23292
- * @returns the associated collection of {@link Amity.Comment} objects
23196
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
23197
+ * @returns the associated collection of {@link Amity.Post} objects
23293
23198
  *
23294
- * @category Comment API
23199
+ * @category Post API
23295
23200
  * @async
23296
23201
  */
23297
- const getCommentByIds = async (commentIds) => {
23202
+ const getPostByIds = async (postIds) => {
23298
23203
  const client = getActiveClient();
23299
- client.log('comment/getCommentByIds', commentIds);
23300
- const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
23301
- let data;
23204
+ client.log('post/getPostByIds', postIds);
23205
+ const encodedPostIds = postIds.map(postId => encodeURIComponent(postId));
23206
+ let payload;
23302
23207
  try {
23303
23208
  // API-FIX: endpoint should not be /list, parameters should be querystring.
23304
- const response = await client.http.get(`/api/v3/comments/list`, {
23305
- params: { commentIds: encodedCommentIds },
23209
+ const response = await client.http.get(`/api/v3/posts/list`, {
23210
+ params: { postIds: encodedPostIds },
23306
23211
  });
23307
- data = response.data;
23212
+ payload = response.data;
23308
23213
  }
23309
23214
  catch (error) {
23310
- commentIds.forEach(commentId => {
23215
+ postIds.forEach(postId => {
23311
23216
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
23312
- pushToTombstone('comment', commentId);
23217
+ pushToTombstone('post', postId);
23313
23218
  }
23314
23219
  });
23315
23220
  throw error;
23316
23221
  }
23222
+ const data = prepareMembershipPayload(payload, 'communityUsers');
23317
23223
  const cachedAt = client.cache && Date.now();
23318
23224
  if (client.cache)
23319
23225
  ingestInCache(data, { cachedAt });
23320
23226
  return {
23321
- data: data.comments.map(comment => LinkedObject.comment(comment)),
23227
+ data: data.posts.map(LinkedObject.post),
23322
23228
  cachedAt,
23323
23229
  };
23324
23230
  };
23325
23231
  /* end_public_function */
23326
23232
  /**
23327
23233
  * ```js
23328
- * import { getCommentByIds } from '@amityco/ts-sdk'
23329
- * const comments = getCommentByIds.locally(['foo', 'bar'])
23234
+ * import { getPostByIds } from '@amityco/ts-sdk'
23235
+ * const { data: posts } = getPostByIds.locally(['foo', 'bar'])
23330
23236
  * ```
23331
23237
  *
23332
- * Fetches a collection of {@link Amity.Comment} objects from cache
23238
+ * Fetches a collection of {@link Amity.Post} objects from cache
23333
23239
  *
23334
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
23335
- * @returns the associated collection of {@link Amity.Comment} objects
23240
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
23241
+ * @returns the associated collection of {@link Amity.Post} objects
23336
23242
  *
23337
- * @category Comment API
23243
+ * @category Post API
23338
23244
  */
23339
- getCommentByIds.locally = (commentIds) => {
23245
+ getPostByIds.locally = (postIds) => {
23340
23246
  var _a;
23341
23247
  const client = getActiveClient();
23342
- client.log('comment/getCommentByIds.locally', commentIds);
23248
+ client.log('post/getPostByIds.locally', postIds);
23343
23249
  if (!client.cache)
23344
23250
  return;
23345
- const cached = commentIds
23346
- .map(commentId => pullFromCache(['comment', 'get', commentId]))
23251
+ const cached = postIds
23252
+ .map(postId => pullFromCache(['post', 'get', postId]))
23347
23253
  .filter(Boolean);
23348
- const comments = cached.map(({ data }) => data);
23254
+ const posts = cached.map(({ data }) => data);
23349
23255
  const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
23350
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < commentIds.length)
23256
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < postIds.length)
23351
23257
  return;
23352
23258
  return {
23353
- data: comments.map(comment => LinkedObject.comment(comment)),
23259
+ data: posts.map(LinkedObject.post),
23354
23260
  cachedAt: oldest.cachedAt,
23355
23261
  };
23356
23262
  };
23357
23263
 
23358
23264
  /* begin_public_function
23359
- id: comment.create
23265
+ 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
23360
23266
  */
23361
23267
  /**
23362
23268
  * ```js
23363
- * import { CommentRepository } from '@amityco/ts-sdk'
23364
- * const newComment = await CommentRepository.createComment(bundle)
23269
+ * import { PostRepository } from '@amityco/ts-sdk'
23270
+ * const created = await PostRepository.createPost({
23271
+ * targetType: 'user',
23272
+ * targetId: 'foobar',
23273
+ * data: { text: 'hello world' }
23274
+ * }))
23365
23275
  * ```
23366
23276
  *
23367
- * Creates an {@link Amity.Comment}
23277
+ * Creates an {@link Amity.Post}
23368
23278
  *
23369
- * @param bundle The data necessary to create a new {@link Amity.Comment}
23370
- * @returns The newly created {@link Amity.Comment}
23279
+ * @param bundle The data necessary to create a new {@link Amity.Post}
23280
+ * @returns The newly created {@link Amity.Post}
23371
23281
  *
23372
- * @category Comment API
23282
+ * @category Post API
23373
23283
  * @async
23374
23284
  */
23375
- const createComment = async (bundle) => {
23376
- var _a;
23285
+ const createPost = async (bundle) => {
23377
23286
  const client = getActiveClient();
23378
- client.log('comment/createComment', bundle);
23379
- const { data } = await client.http.post('/api/v3/comments', bundle);
23380
- const { comments } = data;
23381
- // BE always returns an array of comments If it got record 0 from BE it might have a problem on creation logic
23382
- if (comments.length === 0)
23383
- throw new Error('Comment not created');
23287
+ client.log('post/createPost', bundle);
23288
+ if (!bundle.dataType || ['text', 'image', 'file', 'video'].includes(bundle.dataType)) {
23289
+ // eslint-disable-next-line no-param-reassign
23290
+ delete bundle.dataType;
23291
+ }
23292
+ const { data: payload } = await client.http.post('/api/v4/posts', bundle);
23293
+ fireEvent('post.created', payload);
23294
+ const data = preparePostPayload(payload);
23384
23295
  const cachedAt = client.cache && Date.now();
23385
23296
  if (client.cache)
23386
23297
  ingestInCache(data, { cachedAt });
23387
- if (['post', 'content'].includes(bundle.referenceType)) {
23388
- const post = (_a = pullFromCache(['post', 'get', bundle.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
23389
- if (post) {
23390
- post.commentsCount += 1;
23391
- fireEvent('local.post.updated', {
23392
- posts: [post],
23393
- categories: [],
23394
- comments: [],
23395
- communities: [],
23396
- communityUsers: data.communityUsers,
23397
- feeds: [],
23398
- files: data.files,
23399
- postChildren: [],
23400
- users: data.users,
23401
- videoStreamings: [],
23402
- });
23403
- }
23404
- }
23405
- else if (bundle.referenceType === 'story') {
23406
- const storyIndex = pullFromCache([
23407
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
23408
- bundle.referenceId,
23409
- ]);
23410
- if (storyIndex === null || storyIndex === void 0 ? void 0 : storyIndex.data) {
23411
- const cacheStory = pullFromCache([
23412
- "story" /* STORY_KEY_CACHE.STORY */,
23413
- 'get',
23414
- storyIndex.data,
23415
- ]);
23416
- if (cacheStory === null || cacheStory === void 0 ? void 0 : cacheStory.data) {
23417
- fireEvent('story.updated', {
23418
- stories: [
23419
- Object.assign(Object.assign({}, cacheStory.data), { commentsCount: cacheStory.data.commentsCount + 1, comments: [...new Set([...cacheStory.data.comments, comments[0].commentId])] }),
23420
- ],
23421
- categories: [],
23422
- comments,
23423
- communities: [],
23424
- communityUsers: data.communityUsers,
23425
- files: data.files,
23426
- users: data.users,
23427
- });
23428
- }
23429
- }
23430
- }
23431
- fireEvent('local.comment.created', data);
23298
+ const { posts } = data;
23432
23299
  return {
23433
- data: LinkedObject.comment(comments[0]),
23300
+ data: LinkedObject.post(posts[0]),
23434
23301
  cachedAt,
23435
23302
  };
23436
23303
  };
23437
23304
  /* end_public_function */
23438
23305
 
23439
23306
  /* begin_public_function
23440
- id: comment.update_comment
23307
+ id: post.edit, post.edit.custom_post
23441
23308
  */
23442
23309
  /**
23443
23310
  * ```js
23444
- * import { CommentRepository } from '@amityco/ts-sdk'
23445
- * const updated = await CommentRepository.updateComment(commentId, {
23311
+ * import { PostRepository } from '@amityco/ts-sdk'
23312
+ * const updated = await PostRepository.editPost(postId, {
23446
23313
  * data: { text: 'hello world' }
23447
23314
  * })
23448
23315
  * ```
23449
23316
  *
23450
- * Updates an {@link Amity.Comment}
23317
+ * Updates an {@link Amity.Post}
23451
23318
  *
23452
- * @param commentId The ID of the {@link Amity.Comment} to edit
23319
+ * @param postId The ID of the {@link Amity.Post} to edit
23453
23320
  * @param patch The patch data to apply
23454
- * @returns the updated {@link Amity.Comment} object
23321
+ * @returns the updated {@link Amity.Post} object
23455
23322
  *
23456
- * @category Comment API
23323
+ * @category Post API
23457
23324
  * @async
23458
23325
  */
23459
- const updateComment = async (commentId, patch) => {
23326
+ const editPost = async (postId, patch) => {
23460
23327
  const client = getActiveClient();
23461
- client.log('user/updateComment', patch);
23462
- const { data } = await client.http.put(`/api/v3/comments/${encodeURIComponent(commentId)}`, patch);
23463
- const cachedAt = client.cache && Date.now();
23464
- if (client.cache)
23465
- ingestInCache(data, { cachedAt });
23466
- fireEvent('comment.updated', data);
23467
- const { comments } = data;
23468
- return {
23469
- data: LinkedObject.comment(comments.find(comment => comment.commentId === commentId)),
23470
- cachedAt,
23471
- };
23472
- };
23473
- /* end_public_function */
23474
-
23475
- // Due to we have optimistic logic, we will use referenceId as a id in SDK instead of storyId
23476
- const applyMissingField = (rawData, isCreated = false) => {
23477
- const { storyId, referenceId } = rawData;
23478
- if (!isCreated) {
23479
- if (referenceId)
23480
- return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */ });
23481
- }
23482
- return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */, referenceId: storyId });
23483
- };
23484
- const convertRawStoryToInternal = (data, isCreated = false) => {
23485
- const { stories } = data;
23486
- const storiesData = stories.map(story => applyMissingField(story, isCreated));
23487
- return Object.assign(Object.assign({}, data), { stories: storiesData });
23488
- };
23489
-
23490
- const getStoryByStoryId$1 = async (storyId) => {
23491
- const client = getActiveClient();
23492
- client.log('story/getStoryByStoryId', storyId);
23493
- // Get story referenceId from cache
23494
- const cacheReferenceId = pullFromCache([
23495
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
23496
- storyId,
23497
- ]);
23498
- if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
23499
- const { data: referenceId } = cacheReferenceId;
23500
- isInTombstone('story', referenceId);
23501
- }
23502
- let data;
23503
- try {
23504
- const response = await client.http.get(`/api/v4/stories/${storyId}`);
23505
- data = convertRawStoryToInternal(response.data);
23506
- }
23507
- catch (error) {
23508
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
23509
- pushToTombstone('story', storyId);
23510
- }
23511
- throw error;
23512
- }
23328
+ client.log('user/editPost', patch);
23329
+ const { data: payload } = await client.http.put(`/api/v4/posts/${encodeURIComponent(postId)}`, patch);
23330
+ const data = prepareMembershipPayload(payload, 'communityUsers');
23513
23331
  const cachedAt = client.cache && Date.now();
23514
- if (client.cache) {
23332
+ if (client.cache)
23515
23333
  ingestInCache(data, { cachedAt });
23516
- }
23517
- return {
23518
- data: data.stories[0],
23519
- cachedAt,
23520
- };
23521
- };
23522
- getStoryByStoryId$1.locally = (storyId) => {
23523
- const client = getActiveClient();
23524
- client.log('story/getStorybyStoryId', storyId);
23525
- // Get story referenceId from cache
23526
- const cacheReferenceId = pullFromCache([
23527
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
23528
- storyId,
23529
- ]);
23530
- if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
23531
- const { data: referenceId } = cacheReferenceId;
23532
- isInTombstone('story', referenceId);
23533
- }
23534
- const cachedAt = client.cache && Date.now();
23535
- const storyCache = pullFromCache(['story', 'get', storyId]);
23536
- if (!storyCache)
23537
- return;
23334
+ fireEvent('local.post.updated', data);
23335
+ const { posts } = data;
23538
23336
  return {
23539
- data: storyCache.data,
23337
+ data: LinkedObject.post(posts.find(post => post.postId === postId)),
23540
23338
  cachedAt,
23541
23339
  };
23542
23340
  };
23341
+ /* end_public_function */
23543
23342
 
23544
- /* begin_public_function
23545
- id: comment.soft_delete, comment.hard_delete
23546
- */
23547
23343
  /**
23548
23344
  * ```js
23549
- * import { CommentRepository } from '@amityco/ts-sdk'
23550
- * const success = await CommentRepository.deleteComment('foobar')
23345
+ * import { deletePost } from '@amityco/ts-sdk'
23346
+ * const success = await deletePost('foobar')
23551
23347
  * ```
23552
23348
  *
23553
- * Deletes a {@link Amity.Comment}
23349
+ * Deletes a {@link Amity.Post}
23554
23350
  *
23555
- * @param commentId The {@link Amity.Comment} ID to delete
23556
- * @return A success boolean if the {@link Amity.Comment} was deleted
23351
+ * @param postId The {@link Amity.Post} ID to delete
23352
+ * @return A success boolean if the {@link Amity.Post} was deleted
23557
23353
  *
23558
- * @category Comment API
23354
+ * @private
23559
23355
  * @async
23560
23356
  */
23561
- const deleteComment = async (commentId, permanent = false) => {
23357
+ const deletePost = async (postId, permanent = false) => {
23562
23358
  var _a;
23563
23359
  const client = getActiveClient();
23564
- const comment = await getComment$2(commentId);
23565
- // API-FIX: This endpoint has not been implemented yet.
23566
- await client.http.delete(`/api/v4/comments/${encodeURIComponent(commentId)}`, {
23360
+ const post = await getPost$2(postId);
23361
+ await client.http.delete(`/api/v4/posts/${encodeURIComponent(postId)}`, {
23567
23362
  params: {
23568
- commentId,
23363
+ postId,
23569
23364
  permanent,
23570
23365
  },
23571
23366
  });
23572
- // to support hard deletion
23573
- const deleted = Object.assign(Object.assign({}, comment.data), { isDeleted: true });
23574
- if (comment.data.referenceType === 'story') {
23575
- const story = await getStoryByStoryId$1(comment.data.referenceId);
23576
- fireEvent('local.story.updated', {
23577
- stories: [story.data],
23367
+ // there is currently a limitation which doesn't allow us to fire event to tell that community
23368
+ // has been updated. reason is that, when the object is deleted, we don't have its `communityId`
23369
+ // and so we cannot refetch the community or advertise on events. hopefully this should be solved
23370
+ // later when realtime events covers that for us.
23371
+ if (post.data.targetType === 'community') {
23372
+ const community = await getCommunity$1(post.data.targetId);
23373
+ const communityUsersCache = (_a = queryCache(['communityUsers', 'get'])) !== null && _a !== void 0 ? _a : [];
23374
+ const communityUsers = communityUsersCache
23375
+ .filter(({ key }) => {
23376
+ // cache key is ['communityUsers', 'get', `${communityId}#`${userId}`}]
23377
+ if (key[0] !== 'communityUsers')
23378
+ return false;
23379
+ if (key[1] !== 'get')
23380
+ return false;
23381
+ if (typeof key[2] === 'string')
23382
+ return key[2].includes(community.data.communityId);
23383
+ return false;
23384
+ })
23385
+ .map(({ data }) => data);
23386
+ fireEvent('community.updated', {
23387
+ communities: [community.data],
23578
23388
  categories: [],
23579
- comments: [],
23580
- communities: [],
23581
- communityUsers: [],
23389
+ communityUsers,
23390
+ feeds: [],
23582
23391
  files: [],
23583
23392
  users: [],
23584
23393
  });
23585
23394
  }
23395
+ // to support hard deletion
23396
+ const deleted = Object.assign(Object.assign({}, post.data), { isDeleted: true });
23397
+ if (permanent) {
23398
+ setTimeout(() => {
23399
+ pushToTombstone('post', postId);
23400
+ }, 0);
23401
+ }
23586
23402
  else {
23587
- const post = (_a = pullFromCache(['post', 'get', comment.data.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
23588
- if (post) {
23589
- let removeCount;
23590
- if (!deleted.parentId) {
23591
- // NOTE: delete the parent comment will remove all children comments
23592
- removeCount = deleted.childrenNumber + 1;
23593
- }
23594
- else
23595
- removeCount = 1;
23596
- post.commentsCount -= removeCount;
23597
- fireEvent('local.post.updated', {
23598
- posts: [post],
23599
- categories: [],
23600
- comments: [],
23601
- communities: [],
23602
- communityUsers: [],
23603
- feeds: [],
23604
- files: [],
23605
- postChildren: [],
23606
- users: [],
23607
- videoStreamings: [],
23608
- });
23609
- }
23403
+ upsertInCache(['post', 'get', postId], { isDeleted: true });
23610
23404
  }
23611
- fireEvent('local.comment.deleted', {
23612
- comments: [deleted],
23613
- commentChildren: [],
23405
+ fireEvent('local.post.deleted', {
23406
+ posts: [deleted],
23407
+ categories: [],
23408
+ comments: [],
23409
+ communities: [],
23410
+ communityUsers: [],
23411
+ feeds: [],
23614
23412
  files: [],
23413
+ postChildren: [],
23615
23414
  users: [],
23616
- communityUsers: [],
23415
+ videoStreamings: [],
23617
23416
  });
23618
- if (permanent) {
23619
- scheduleTask(() => pushToTombstone('comment', commentId));
23620
- }
23621
- else {
23622
- upsertInCache(['comment', 'get', commentId], { isDeleted: true });
23623
- }
23624
- return deleted;
23417
+ return LinkedObject.post(deleted);
23625
23418
  };
23626
- /* end_public_function */
23627
23419
 
23628
23420
  /* begin_public_function
23629
- id: comment.soft_delete
23421
+ id: post.soft_delete
23630
23422
  */
23631
23423
  /**
23632
23424
  * ```js
23633
- * import { CommentRepository } from '@amityco/ts-sdk'
23634
- * const success = await CommentRepository.softDeleteComment('foobar')
23425
+ * import { PostRepository } from '@amityco/ts-sdk'
23426
+ * const success = await PostRepository.softDeletePost('foobar')
23635
23427
  * ```
23636
23428
  *
23637
- * Deletes a {@link Amity.Comment}
23429
+ * Soft deletes a {@link Amity.Post}
23638
23430
  *
23639
- * @param commentId The {@link Amity.Comment} ID to delete
23640
- * @return A success boolean if the {@link Amity.Comment} was deleted
23431
+ * @param postId The {@link Amity.Post} ID to soft delete
23432
+ * @return A success boolean if the {@link Amity.Post} was deleted
23641
23433
  *
23642
- * @category Comment API
23434
+ * @category Post API
23643
23435
  * @async
23644
23436
  */
23645
- const softDeleteComment = async (commentId) => {
23437
+ const softDeletePost = async (postId) => {
23646
23438
  const client = getActiveClient();
23647
- client.log('comment/softDeleteComment', commentId);
23648
- const softDeleted = deleteComment(commentId);
23649
- return softDeleted;
23439
+ client.log('post/softDeletePost', postId);
23440
+ const softDeleted = await deletePost(postId, false);
23441
+ return LinkedObject.post(softDeleted);
23650
23442
  };
23651
23443
  /* end_public_function */
23652
23444
 
23653
23445
  /* begin_public_function
23654
- id: comment.hard_delete
23446
+ id: post.hard_delete
23655
23447
  */
23656
23448
  /**
23657
23449
  * ```js
23658
- * import { CommentRepository } from '@amityco/ts-sdk'
23659
- * const success = await CommentRepository.hardDeleteComment('foobar')
23450
+ * import { hardDeletePost } from '@amityco/ts-sdk'
23451
+ * const success = await hardDeletePost('foobar')
23660
23452
  * ```
23661
23453
  *
23662
- * Deletes a {@link Amity.Comment}
23454
+ * Hard deletes a {@link Amity.Post}
23663
23455
  *
23664
- * @param commentId The {@link Amity.Comment} ID to delete
23665
- * @return A success boolean if the {@link Amity.Comment} was deleted
23456
+ * @param postId The {@link Amity.Post} ID to be hard delete
23457
+ * @return A success boolean if the {@link Amity.Post} was deleted
23666
23458
  *
23667
- * @category Comment API
23459
+ * @category Post API
23668
23460
  * @async
23669
23461
  */
23670
- const hardDeleteComment = async (commentId) => {
23462
+ const hardDeletePost = async (postId) => {
23671
23463
  const client = getActiveClient();
23672
- client.log('comment/hardDeleteComment', commentId);
23673
- const hardDeleted = deleteComment(commentId, true);
23674
- return hardDeleted;
23464
+ client.log('post/hardDeletePost', postId);
23465
+ const hardDeleted = await deletePost(postId, true);
23466
+ return LinkedObject.post(hardDeleted);
23675
23467
  };
23676
23468
  /* end_public_function */
23677
23469
 
23678
23470
  /* begin_public_function
23679
- id: comment.flag
23471
+ id: post.approve
23680
23472
  */
23681
23473
  /**
23682
23474
  * ```js
23683
- * import { CommentRepository } from '@amityco/ts-sdk'
23684
- * const flagged = await CommentRepository.flagComment(commentId, reason)
23475
+ * import { approvePost } from '@amityco/ts-sdk'
23476
+ *
23477
+ * const { data: post } = await approvePost('postId')
23685
23478
  * ```
23686
23479
  *
23687
- * @param commentId The ID of the comment to flag
23688
- * @param reason the reason to flag the comment
23689
- * @returns the created report result
23480
+ * Approves a {@link Amity.Post}
23690
23481
  *
23691
- * @category Comment API
23482
+ * @param postId The {@link Amity.Post} ID to be approved
23483
+ * @return A {@link Amity.Post} that was approved
23484
+ *
23485
+ * @category Post API
23692
23486
  * @async
23693
- * */
23694
- const flagComment = async (commentId, reason) => {
23487
+ */
23488
+ const approvePost = async (postId) => {
23695
23489
  const client = getActiveClient();
23696
- client.log('comment/flagComment', commentId);
23697
- const isPredefinedReason = reason &&
23698
- Object.entries(exports.ContentFlagReasonEnum).some(([key, value]) => key !== exports.ContentFlagReasonEnum.Others && value === reason);
23490
+ client.log('post/approvePost', postId);
23491
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/approve`);
23492
+ fireEvent('post.approved', payload);
23493
+ // fire virtual event for community update
23494
+ if (payload.posts[0].targetType === 'community') {
23495
+ fireEvent('community.updated', payload);
23496
+ }
23497
+ const data = prepareMembershipPayload(payload, 'communityUsers');
23498
+ const cachedAt = client.cache && Date.now();
23499
+ if (client.cache)
23500
+ ingestInCache(data, { cachedAt });
23501
+ return {
23502
+ data: LinkedObject.post(data.posts.find(post => post.postId === postId)),
23503
+ cachedAt,
23504
+ };
23505
+ };
23506
+ /* end_public_function */
23507
+
23508
+ /* begin_public_function
23509
+ id: post.decline
23510
+ */
23511
+ /**
23512
+ * ```js
23513
+ * import { declinePost } from '@amityco/ts-sdk'
23514
+ *
23515
+ * const {data: post} = await declinePost('postId')
23516
+ * ```
23517
+ *
23518
+ * Declines a {@link Amity.Post}
23519
+ *
23520
+ * @param postId The {@link Amity.Post} ID to be declined
23521
+ * @return A {@link Amity.Post} that was declined
23522
+ *
23523
+ * @category Post API
23524
+ * @async
23525
+ */
23526
+ const declinePost = async (postId) => {
23527
+ const client = getActiveClient();
23528
+ client.log('post/declinePost', postId);
23529
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/decline`);
23530
+ // fire virtual event
23531
+ if (payload.posts[0].targetType === 'community') {
23532
+ fireEvent('community.updated', payload);
23533
+ }
23534
+ fireEvent('post.declined', payload);
23535
+ const data = prepareMembershipPayload(payload, 'communityUsers');
23536
+ const cachedAt = client.cache && Date.now();
23537
+ if (client.cache)
23538
+ ingestInCache(data, { cachedAt });
23539
+ return {
23540
+ data: LinkedObject.post(payload.posts.find(post => post.postId === postId)),
23541
+ cachedAt,
23542
+ };
23543
+ };
23544
+ /* end_public_function */
23545
+
23546
+ /* begin_public_function
23547
+ id: post.flag
23548
+ */
23549
+ /**
23550
+ * ```js
23551
+ * import { PostRepository } from '@amityco/ts-sdk'
23552
+ * const flagged = await PostRepository.flagPost(postId, reason)
23553
+ * ```
23554
+ *
23555
+ * @param postId of the post to flag
23556
+ * @param reason the reason to flag the post
23557
+ * @returns a boolean
23558
+ *
23559
+ * @category Post API
23560
+ * @async
23561
+ * */
23562
+ const flagPost = async (postId, reason) => {
23563
+ const client = getActiveClient();
23564
+ client.log('post/flagPost', postId);
23565
+ const isPredefinedReason = reason &&
23566
+ Object.entries(exports.ContentFlagReasonEnum).some(([key, value]) => key !== exports.ContentFlagReasonEnum.Others && value === reason);
23699
23567
  const body = {
23700
23568
  reason: reason && isPredefinedReason ? reason : exports.ContentFlagReasonEnum.Others,
23701
23569
  detail: reason && !isPredefinedReason ? reason : '',
23702
23570
  };
23703
- const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/flag`, body);
23571
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/flag`, body);
23704
23572
  if (client.cache) {
23705
- ingestInCache(payload);
23573
+ ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
23706
23574
  }
23707
- fireEvent('comment.flagged', payload);
23575
+ fireEvent('post.flagged', payload);
23708
23576
  return !!payload;
23709
23577
  };
23710
23578
  /* end_public_function */
23711
23579
 
23712
23580
  /* begin_public_function
23713
- id: comment.unflag
23581
+ id: post.unflag
23714
23582
  */
23715
23583
  /**
23716
23584
  * ```js
23717
- * import { CommentRepository } from '@amityco/ts-sdk'
23718
- * const unflagged = await CommentRepository.unflagComment('commentId')
23585
+ * import { PostRepository } from '@amityco/ts-sdk'
23586
+ * const unflagged = await PostRepository.unflagPost(postId)
23719
23587
  * ```
23720
23588
  *
23721
- * @param commentId The ID of comment to unflag
23722
- * @returns the unflagged result
23589
+ * @param postId of the post to unflag
23590
+ * @returns the unflag post result
23723
23591
  *
23724
- * @category Comment API
23592
+ * @category Post API
23725
23593
  * @async
23726
23594
  * */
23727
- const unflagComment = async (commentId) => {
23595
+ const unflagPost = async (postId) => {
23728
23596
  const client = getActiveClient();
23729
- client.log('comment/unflagComment', commentId);
23730
- const { data: payload } = await client.http.delete(`/api/v3/comments/${encodeURIComponent(commentId)}/unflag`);
23597
+ client.log('post/unflagPost', postId);
23598
+ const { data: payload } = await client.http.delete(`/api/v3/posts/${encodeURIComponent(postId)}/unflag`);
23731
23599
  if (client.cache) {
23732
- ingestInCache(payload);
23600
+ ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
23733
23601
  }
23734
- fireEvent('comment.unflagged', payload);
23602
+ fireEvent('post.unflagged', payload);
23735
23603
  return !!payload;
23736
23604
  };
23737
23605
  /* end_public_function */
23738
23606
 
23739
23607
  /* begin_public_function
23740
- id: comment.check_flag_by_me
23608
+ id: post.check_flag_by_me
23741
23609
  */
23742
23610
  /**
23743
23611
  * ```js
23744
- * import { CommentRepository } from '@amityco/ts-sdk'
23745
- * const isReported = await CommentRepository.isCommentFlaggedByMe('commentId')
23612
+ * import { PostRepository } from '@amityco/ts-sdk'
23613
+ * const isReported = await PostRepository.isPostFlaggedByMe('post', postId)
23746
23614
  * ```
23747
23615
  *
23748
- * @param commentId The ID of the comment to check if flagged by current user
23749
- * @returns `true` if the comment is flagged by me, `false` if doesn't.
23616
+ * @param postId of the post to check if flagged by current user
23617
+ * @returns `true` if the post is flagged by me, `false` if doesn't.
23750
23618
  *
23751
- * @category Comment API
23619
+ * @category Post API
23752
23620
  * @async
23753
23621
  * */
23754
- const isCommentFlaggedByMe = async (commentId) => {
23622
+ const isPostFlaggedByMe = async (postId) => {
23755
23623
  const client = getActiveClient();
23756
- client.log('comment/isCommentFlaggedByMe', commentId);
23757
- const { data: { result }, } = await client.http.get(`/api/v3/comments/${commentId}/isflagbyme`);
23624
+ client.log('post/isPostFlaggedByMe', postId);
23625
+ const { data: { result }, } = await client.http.get(`/api/v3/posts/${postId}/isflagbyme`);
23758
23626
  return result;
23759
23627
  };
23760
23628
  /* end_public_function */
23761
23629
 
23762
- const getComment$1 = async (commentId) => {
23630
+ /* begin_public_function
23631
+ id: post.create.clip_post
23632
+ */
23633
+ /**
23634
+ * ```js
23635
+ * import { PostRepository } from '@amityco/ts-sdk'
23636
+ * const created = await PostRepository.createClipPost({
23637
+ * targetType: 'user',
23638
+ * targetId: 'foobar',
23639
+ * dataType: 'clip',
23640
+ * data: { text: 'hello world' },
23641
+ * attachments: [{ type: 'clip', fileId: 'fileId123', displayMode: 'fill', isMuted: false }]
23642
+ * }))
23643
+ * ```
23644
+ *
23645
+ * Creates an {@link Amity.Post}
23646
+ *
23647
+ * @param bundle The data necessary to create a new {@link Amity.Post}
23648
+ * @returns The newly created {@link Amity.Post}
23649
+ *
23650
+ * @category Post API
23651
+ * @async
23652
+ */
23653
+ const createClipPost = async (bundle) => {
23763
23654
  const client = getActiveClient();
23764
- client.log('comment/getComment', commentId);
23765
- isInTombstone('comment', commentId);
23655
+ client.log('post/createPost', bundle);
23656
+ const { data: payload } = await client.http.post('/api/v4/posts', bundle);
23657
+ fireEvent('post.created', payload);
23658
+ const data = prepareMembershipPayload(payload, 'communityUsers');
23659
+ const cachedAt = client.cache && Date.now();
23660
+ if (client.cache)
23661
+ ingestInCache(data, { cachedAt });
23662
+ const { posts } = data;
23663
+ return {
23664
+ data: LinkedObject.post(posts[0]),
23665
+ cachedAt,
23666
+ };
23667
+ };
23668
+ /* end_public_function */
23669
+
23670
+ /* begin_public_function
23671
+ id: comment.get_by_ids
23672
+ */
23673
+ /**
23674
+ * ```js
23675
+ * import { CommentRepository } from '@amityco/ts-sdk'
23676
+ * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
23677
+ * ```
23678
+ *
23679
+ * Fetches a collection of {@link Amity.Comment} objects
23680
+ *
23681
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
23682
+ * @returns the associated collection of {@link Amity.Comment} objects
23683
+ *
23684
+ * @category Comment API
23685
+ * @async
23686
+ */
23687
+ const getCommentByIds = async (commentIds) => {
23688
+ const client = getActiveClient();
23689
+ client.log('comment/getCommentByIds', commentIds);
23690
+ const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
23766
23691
  let data;
23767
23692
  try {
23768
23693
  // API-FIX: endpoint should not be /list, parameters should be querystring.
23769
- const response = await client.http.get(`/api/v3/comments/${encodeURIComponent(commentId)}`);
23694
+ const response = await client.http.get(`/api/v3/comments/list`, {
23695
+ params: { commentIds: encodedCommentIds },
23696
+ });
23770
23697
  data = response.data;
23771
23698
  }
23772
23699
  catch (error) {
23773
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
23774
- pushToTombstone('comment', commentId);
23775
- }
23700
+ commentIds.forEach(commentId => {
23701
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
23702
+ pushToTombstone('comment', commentId);
23703
+ }
23704
+ });
23776
23705
  throw error;
23777
23706
  }
23778
23707
  const cachedAt = client.cache && Date.now();
23779
23708
  if (client.cache)
23780
23709
  ingestInCache(data, { cachedAt });
23781
- const { comments } = data;
23782
23710
  return {
23783
- data: comments.find(comment => comment.commentId === commentId),
23711
+ data: data.comments.map(comment => LinkedObject.comment(comment)),
23784
23712
  cachedAt,
23785
23713
  };
23786
23714
  };
23787
- getComment$1.locally = (commentId) => {
23715
+ /* end_public_function */
23716
+ /**
23717
+ * ```js
23718
+ * import { getCommentByIds } from '@amityco/ts-sdk'
23719
+ * const comments = getCommentByIds.locally(['foo', 'bar'])
23720
+ * ```
23721
+ *
23722
+ * Fetches a collection of {@link Amity.Comment} objects from cache
23723
+ *
23724
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
23725
+ * @returns the associated collection of {@link Amity.Comment} objects
23726
+ *
23727
+ * @category Comment API
23728
+ */
23729
+ getCommentByIds.locally = (commentIds) => {
23730
+ var _a;
23788
23731
  const client = getActiveClient();
23789
- client.log('comment/getComment.locally', commentId);
23732
+ client.log('comment/getCommentByIds.locally', commentIds);
23790
23733
  if (!client.cache)
23791
23734
  return;
23792
- const cached = pullFromCache(['comment', 'get', commentId]);
23793
- if (!cached)
23735
+ const cached = commentIds
23736
+ .map(commentId => pullFromCache(['comment', 'get', commentId]))
23737
+ .filter(Boolean);
23738
+ const comments = cached.map(({ data }) => data);
23739
+ const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
23740
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < commentIds.length)
23794
23741
  return;
23795
23742
  return {
23796
- data: cached.data,
23797
- cachedAt: cached.cachedAt,
23743
+ data: comments.map(comment => LinkedObject.comment(comment)),
23744
+ cachedAt: oldest.cachedAt,
23798
23745
  };
23799
23746
  };
23800
23747
 
23748
+ /* begin_public_function
23749
+ id: comment.create
23750
+ */
23801
23751
  /**
23802
23752
  * ```js
23803
- * import { onCommentDeleteLocal } from '@amityco/ts-sdk'
23804
- * const dispose = onCommentDeleteLocal(comment => {
23805
- * // ...
23806
- * })
23753
+ * import { CommentRepository } from '@amityco/ts-sdk'
23754
+ * const newComment = await CommentRepository.createComment(bundle)
23807
23755
  * ```
23808
23756
  *
23809
- * Fired when a {@link Amity.InternalComment} has been deleted
23757
+ * Creates an {@link Amity.Comment}
23810
23758
  *
23811
- * @param callback The function to call when the event was fired
23812
- * @returns an {@link Amity.Unsubscriber} function to stop listening
23759
+ * @param bundle The data necessary to create a new {@link Amity.Comment}
23760
+ * @returns The newly created {@link Amity.Comment}
23813
23761
  *
23814
- * @category Comment Events
23762
+ * @category Comment API
23763
+ * @async
23815
23764
  */
23816
- const onCommentDeleteLocal = (callback) => createLocalCommentEventSubscriber('local.comment.deleted', callback);
23817
-
23818
- /**
23819
- * ```js
23820
- * import { onLocalCommentReactionAdded } from '@amityco/ts-sdk'
23821
- * const dispose = onLocalCommentReactionAdded(comment => {
23822
- * // ...
23823
- * })
23824
- * ```
23825
- *
23826
- * Fired when a {@link Amity.InternalComment} has been reacted
23827
- *
23828
- * @param callback The function to call when the event was fired
23829
- * @returns an {@link Amity.Unsubscriber} function to stop listening
23830
- *
23831
- * @category Comment Events
23832
- */
23833
- const onLocalCommentReactionAdded = (callback) => {
23765
+ const createComment = async (bundle) => {
23766
+ var _a;
23834
23767
  const client = getActiveClient();
23835
- const filter = ({ comment }) => {
23836
- if (!client.cache) {
23837
- callback(comment);
23768
+ client.log('comment/createComment', bundle);
23769
+ const { data } = await client.http.post('/api/v3/comments', bundle);
23770
+ const { comments } = data;
23771
+ // BE always returns an array of comments If it got record 0 from BE it might have a problem on creation logic
23772
+ if (comments.length === 0)
23773
+ throw new Error('Comment not created');
23774
+ const cachedAt = client.cache && Date.now();
23775
+ if (client.cache)
23776
+ ingestInCache(data, { cachedAt });
23777
+ if (['post', 'content'].includes(bundle.referenceType)) {
23778
+ const post = (_a = pullFromCache(['post', 'get', bundle.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
23779
+ if (post) {
23780
+ post.commentsCount += 1;
23781
+ fireEvent('local.post.updated', {
23782
+ posts: [post],
23783
+ categories: [],
23784
+ comments: [],
23785
+ communities: [],
23786
+ communityUsers: data.communityUsers,
23787
+ feeds: [],
23788
+ files: data.files,
23789
+ postChildren: [],
23790
+ users: data.users,
23791
+ videoStreamings: [],
23792
+ });
23838
23793
  }
23839
- else {
23840
- upsertInCache(['comment', 'get', comment.commentId], comment);
23841
- callback(commentLinkedObject(comment));
23794
+ }
23795
+ else if (bundle.referenceType === 'story') {
23796
+ const storyIndex = pullFromCache([
23797
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
23798
+ bundle.referenceId,
23799
+ ]);
23800
+ if (storyIndex === null || storyIndex === void 0 ? void 0 : storyIndex.data) {
23801
+ const cacheStory = pullFromCache([
23802
+ "story" /* STORY_KEY_CACHE.STORY */,
23803
+ 'get',
23804
+ storyIndex.data,
23805
+ ]);
23806
+ if (cacheStory === null || cacheStory === void 0 ? void 0 : cacheStory.data) {
23807
+ fireEvent('story.updated', {
23808
+ stories: [
23809
+ Object.assign(Object.assign({}, cacheStory.data), { commentsCount: cacheStory.data.commentsCount + 1, comments: [...new Set([...cacheStory.data.comments, comments[0].commentId])] }),
23810
+ ],
23811
+ categories: [],
23812
+ comments,
23813
+ communities: [],
23814
+ communityUsers: data.communityUsers,
23815
+ files: data.files,
23816
+ users: data.users,
23817
+ });
23818
+ }
23842
23819
  }
23820
+ }
23821
+ fireEvent('local.comment.created', data);
23822
+ return {
23823
+ data: LinkedObject.comment(comments[0]),
23824
+ cachedAt,
23843
23825
  };
23844
- return createEventSubscriber(client, 'local.comment.addReaction', 'local.comment.addReaction', filter);
23845
23826
  };
23827
+ /* end_public_function */
23846
23828
 
23829
+ /* begin_public_function
23830
+ id: comment.update_comment
23831
+ */
23847
23832
  /**
23848
23833
  * ```js
23849
- * import { onLocalCommentReactionRemoved } from '@amityco/ts-sdk'
23850
- * const dispose = onLocalCommentReactionRemoved(comment => {
23851
- * // ...
23834
+ * import { CommentRepository } from '@amityco/ts-sdk'
23835
+ * const updated = await CommentRepository.updateComment(commentId, {
23836
+ * data: { text: 'hello world' }
23852
23837
  * })
23853
23838
  * ```
23854
23839
  *
23855
- * Fired when a {@link Amity.InternalComment} has been reacted
23840
+ * Updates an {@link Amity.Comment}
23856
23841
  *
23857
- * @param callback The function to call when the event was fired
23858
- * @returns an {@link Amity.Unsubscriber} function to stop listening
23842
+ * @param commentId The ID of the {@link Amity.Comment} to edit
23843
+ * @param patch The patch data to apply
23844
+ * @returns the updated {@link Amity.Comment} object
23859
23845
  *
23860
- * @category Comment Events
23846
+ * @category Comment API
23847
+ * @async
23861
23848
  */
23862
- const onLocalCommentReactionRemoved = (callback) => {
23849
+ const updateComment = async (commentId, patch) => {
23863
23850
  const client = getActiveClient();
23864
- const filter = ({ comment }) => {
23865
- if (!client.cache) {
23866
- callback(comment);
23867
- }
23868
- else {
23869
- upsertInCache(['comment', 'get', comment.commentId], comment);
23870
- callback(commentLinkedObject(comment));
23851
+ client.log('user/updateComment', patch);
23852
+ const { data } = await client.http.put(`/api/v3/comments/${encodeURIComponent(commentId)}`, patch);
23853
+ const cachedAt = client.cache && Date.now();
23854
+ if (client.cache)
23855
+ ingestInCache(data, { cachedAt });
23856
+ fireEvent('comment.updated', data);
23857
+ const { comments } = data;
23858
+ return {
23859
+ data: LinkedObject.comment(comments.find(comment => comment.commentId === commentId)),
23860
+ cachedAt,
23861
+ };
23862
+ };
23863
+ /* end_public_function */
23864
+
23865
+ // Due to we have optimistic logic, we will use referenceId as a id in SDK instead of storyId
23866
+ const applyMissingField = (rawData, isCreated = false) => {
23867
+ const { storyId, referenceId } = rawData;
23868
+ if (!isCreated) {
23869
+ if (referenceId)
23870
+ return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */ });
23871
+ }
23872
+ return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */, referenceId: storyId });
23873
+ };
23874
+ const convertRawStoryToInternal = (data, isCreated = false) => {
23875
+ const { stories } = data;
23876
+ const storiesData = stories.map(story => applyMissingField(story, isCreated));
23877
+ return Object.assign(Object.assign({}, data), { stories: storiesData });
23878
+ };
23879
+
23880
+ const getStoryByStoryId$1 = async (storyId) => {
23881
+ const client = getActiveClient();
23882
+ client.log('story/getStoryByStoryId', storyId);
23883
+ // Get story referenceId from cache
23884
+ const cacheReferenceId = pullFromCache([
23885
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
23886
+ storyId,
23887
+ ]);
23888
+ if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
23889
+ const { data: referenceId } = cacheReferenceId;
23890
+ isInTombstone('story', referenceId);
23891
+ }
23892
+ let data;
23893
+ try {
23894
+ const response = await client.http.get(`/api/v4/stories/${storyId}`);
23895
+ data = convertRawStoryToInternal(response.data);
23896
+ }
23897
+ catch (error) {
23898
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
23899
+ pushToTombstone('story', storyId);
23871
23900
  }
23901
+ throw error;
23902
+ }
23903
+ const cachedAt = client.cache && Date.now();
23904
+ if (client.cache) {
23905
+ ingestInCache(data, { cachedAt });
23906
+ }
23907
+ return {
23908
+ data: data.stories[0],
23909
+ cachedAt,
23910
+ };
23911
+ };
23912
+ getStoryByStoryId$1.locally = (storyId) => {
23913
+ const client = getActiveClient();
23914
+ client.log('story/getStorybyStoryId', storyId);
23915
+ // Get story referenceId from cache
23916
+ const cacheReferenceId = pullFromCache([
23917
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
23918
+ storyId,
23919
+ ]);
23920
+ if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
23921
+ const { data: referenceId } = cacheReferenceId;
23922
+ isInTombstone('story', referenceId);
23923
+ }
23924
+ const cachedAt = client.cache && Date.now();
23925
+ const storyCache = pullFromCache(['story', 'get', storyId]);
23926
+ if (!storyCache)
23927
+ return;
23928
+ return {
23929
+ data: storyCache.data,
23930
+ cachedAt,
23872
23931
  };
23873
- return createEventSubscriber(client, 'local.comment.removeReaction', 'local.comment.removeReaction', filter);
23874
23932
  };
23875
23933
 
23876
23934
  /* begin_public_function
23877
- id: comment.get
23935
+ id: comment.soft_delete, comment.hard_delete
23878
23936
  */
23879
23937
  /**
23880
23938
  * ```js
23881
- * import { CommentRepository } from '@amityco/ts-sdk';
23882
- *
23883
- * let comment;
23884
- *
23885
- * const unsub = CommentRepository.getComment(commentId, response => {
23886
- * comment = response.data;
23887
- * });
23939
+ * import { CommentRepository } from '@amityco/ts-sdk'
23940
+ * const success = await CommentRepository.deleteComment('foobar')
23888
23941
  * ```
23889
23942
  *
23890
- * Observe all mutation on a given {@link Amity.Comment}
23943
+ * Deletes a {@link Amity.Comment}
23891
23944
  *
23892
- * @param commentId the ID of the comment to observe
23893
- * @param callback the function to call when new data are available
23894
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
23945
+ * @param commentId The {@link Amity.Comment} ID to delete
23946
+ * @return A success boolean if the {@link Amity.Comment} was deleted
23895
23947
  *
23896
- * @category Comment Live Object
23948
+ * @category Comment API
23949
+ * @async
23897
23950
  */
23898
- const getComment = (commentId, callback) => {
23899
- return liveObject(commentId, callback, 'commentId', getComment$1, [
23900
- onCommentDeleteLocal,
23901
- onCommentDeleted,
23902
- onCommentFlagged,
23903
- onCommentReactionAdded,
23904
- onCommentReactionRemoved,
23905
- onCommentUnflagged,
23906
- onCommentUpdated,
23907
- onLocalCommentReactionAdded,
23908
- onLocalCommentReactionRemoved,
23909
- ]);
23910
- };
23911
- /* end_public_function */
23912
-
23913
- class CommentPaginationController extends PaginationController {
23914
- async getRequest(queryParams, token) {
23915
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
23916
- const baseOptions = {
23917
- type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
23918
- };
23919
- const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
23920
- const { data: queryResponse } = await this.http.get(`/api/v3/comments`, {
23921
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
23951
+ const deleteComment = async (commentId, permanent = false) => {
23952
+ var _a;
23953
+ const client = getActiveClient();
23954
+ const comment = await getComment$2(commentId);
23955
+ // API-FIX: This endpoint has not been implemented yet.
23956
+ await client.http.delete(`/api/v4/comments/${encodeURIComponent(commentId)}`, {
23957
+ params: {
23958
+ commentId,
23959
+ permanent,
23960
+ },
23961
+ });
23962
+ // to support hard deletion
23963
+ const deleted = Object.assign(Object.assign({}, comment.data), { isDeleted: true });
23964
+ if (comment.data.referenceType === 'story') {
23965
+ const story = await getStoryByStoryId$1(comment.data.referenceId);
23966
+ fireEvent('local.story.updated', {
23967
+ stories: [story.data],
23968
+ categories: [],
23969
+ comments: [],
23970
+ communities: [],
23971
+ communityUsers: [],
23972
+ files: [],
23973
+ users: [],
23922
23974
  });
23923
- return queryResponse;
23924
23975
  }
23925
- }
23926
-
23927
- var EnumCommentActions;
23928
- (function (EnumCommentActions) {
23929
- EnumCommentActions["OnCommentCreated"] = "onCommentCreated";
23930
- EnumCommentActions["OnCommentUpdated"] = "onCommentUpdated";
23931
- EnumCommentActions["OnCommentDeleted"] = "onCommentDeleted";
23932
- EnumCommentActions["OnCommentFlagged"] = "onCommentFlagged";
23933
- EnumCommentActions["OnCommentUnflagged"] = "onCommentUnflagged";
23934
- EnumCommentActions["OnCommentReactionAdded"] = "onCommentReactionAdded";
23935
- EnumCommentActions["OnCommentReactionRemoved"] = "onCommentReactionRemoved";
23936
- })(EnumCommentActions || (EnumCommentActions = {}));
23937
-
23938
- class CommentQueryStreamController extends QueryStreamController {
23939
- constructor(query, cacheKey, notifyChange, preparePayload) {
23940
- super(query, cacheKey);
23941
- this.notifyChange = notifyChange;
23942
- this.preparePayload = preparePayload;
23943
- }
23944
- async saveToMainDB(response) {
23945
- const processedPayload = await this.preparePayload(response);
23946
- const client = getActiveClient();
23947
- const cachedAt = client.cache && Date.now();
23948
- if (client.cache) {
23949
- ingestInCache(processedPayload, { cachedAt });
23950
- }
23951
- }
23952
- appendToQueryStream(response, direction, refresh = false) {
23953
- var _a, _b;
23954
- if (refresh) {
23955
- pushToCache(this.cacheKey, {
23956
- data: response.comments.map(getResolver('comment')),
23976
+ else {
23977
+ const post = (_a = pullFromCache(['post', 'get', comment.data.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
23978
+ if (post) {
23979
+ let removeCount;
23980
+ if (!deleted.parentId) {
23981
+ // NOTE: delete the parent comment will remove all children comments
23982
+ removeCount = deleted.childrenNumber + 1;
23983
+ }
23984
+ else
23985
+ removeCount = 1;
23986
+ post.commentsCount -= removeCount;
23987
+ fireEvent('local.post.updated', {
23988
+ posts: [post],
23989
+ categories: [],
23990
+ comments: [],
23991
+ communities: [],
23992
+ communityUsers: [],
23993
+ feeds: [],
23994
+ files: [],
23995
+ postChildren: [],
23996
+ users: [],
23997
+ videoStreamings: [],
23957
23998
  });
23958
23999
  }
23959
- else {
23960
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23961
- const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
23962
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...response.comments.map(getResolver('comment'))])] }));
23963
- }
23964
24000
  }
23965
- reactor(action) {
23966
- return (comment) => {
23967
- var _a;
23968
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
23969
- if (this.query.referenceId !== comment.referenceId ||
23970
- this.query.referenceType !== comment.referenceType ||
23971
- !collection) {
23972
- return;
23973
- }
23974
- if (this.query.parentId && this.query.parentId !== comment.parentId) {
23975
- return;
23976
- }
23977
- if (!this.query.parentId && comment.parentId) {
23978
- return;
23979
- }
23980
- if (action === EnumCommentActions.OnCommentCreated) {
23981
- collection.data = [...new Set([comment.commentId, ...collection.data])];
23982
- }
23983
- pushToCache(this.cacheKey, collection);
23984
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
23985
- };
24001
+ fireEvent('local.comment.deleted', {
24002
+ comments: [deleted],
24003
+ commentChildren: [],
24004
+ files: [],
24005
+ users: [],
24006
+ communityUsers: [],
24007
+ });
24008
+ if (permanent) {
24009
+ scheduleTask(() => pushToTombstone('comment', commentId));
23986
24010
  }
23987
- subscribeRTE(createSubscriber) {
23988
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
24011
+ else {
24012
+ upsertInCache(['comment', 'get', commentId], { isDeleted: true });
23989
24013
  }
23990
- }
24014
+ return deleted;
24015
+ };
24016
+ /* end_public_function */
23991
24017
 
24018
+ /* begin_public_function
24019
+ id: comment.soft_delete
24020
+ */
23992
24021
  /**
23993
24022
  * ```js
23994
- * import { onCommentCreated } from '@amityco/ts-sdk'
23995
- * const dispose = onCommentCreated(comment => {
23996
- * // ...
23997
- * })
24023
+ * import { CommentRepository } from '@amityco/ts-sdk'
24024
+ * const success = await CommentRepository.softDeleteComment('foobar')
23998
24025
  * ```
23999
24026
  *
24000
- * Fired when a {@link Amity.InternalComment} has been created
24027
+ * Deletes a {@link Amity.Comment}
24001
24028
  *
24002
- * @param callback The function to call when the event was fired
24003
- * @returns an {@link Amity.Unsubscriber} function to stop listening
24029
+ * @param commentId The {@link Amity.Comment} ID to delete
24030
+ * @return A success boolean if the {@link Amity.Comment} was deleted
24004
24031
  *
24005
- * @category Comment Events
24032
+ * @category Comment API
24033
+ * @async
24006
24034
  */
24007
- const onCommentCreatedLocal = (callback) => {
24008
- return createLocalCommentEventSubscriber('local.comment.created', callback);
24035
+ const softDeleteComment = async (commentId) => {
24036
+ const client = getActiveClient();
24037
+ client.log('comment/softDeleteComment', commentId);
24038
+ const softDeleted = deleteComment(commentId);
24039
+ return softDeleted;
24009
24040
  };
24010
-
24011
- class CommentLiveCollectionController extends LiveCollectionController {
24012
- constructor(query, callback) {
24013
- const queryStreamId = hash__default["default"](query);
24014
- const cacheKey = ['comments', 'collection', queryStreamId];
24015
- const paginationController = new CommentPaginationController(query);
24016
- super(paginationController, queryStreamId, cacheKey, callback);
24017
- this.query = query;
24018
- this.queryStreamController = new CommentQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommentPayload);
24019
- this.callback = callback.bind(this);
24020
- this.loadPage({ initial: true });
24021
- }
24022
- setup() {
24023
- var _a;
24024
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24025
- if (!collection) {
24026
- pushToCache(this.cacheKey, {
24027
- data: [],
24028
- params: {},
24029
- });
24030
- }
24031
- }
24032
- async persistModel(queryPayload) {
24033
- await this.queryStreamController.saveToMainDB(queryPayload);
24034
- }
24035
- persistQueryStream({ response, direction, refresh, }) {
24036
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
24037
- }
24038
- startSubscription() {
24039
- return this.queryStreamController.subscribeRTE([
24040
- { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
24041
- { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
24042
- { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
24043
- { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
24044
- { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
24045
- { fn: onCommentFlagged, action: EnumCommentActions.OnCommentFlagged },
24046
- { fn: onCommentUnflagged, action: EnumCommentActions.OnCommentUnflagged },
24047
- { fn: onCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
24048
- { fn: onCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
24049
- { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
24050
- { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
24051
- ]);
24052
- }
24053
- notifyChange({ origin, loading, error }) {
24054
- var _a, _b;
24055
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24056
- if (!collection)
24057
- return;
24058
- const data = this.applyFilter((_b = collection.data
24059
- .map(id => pullFromCache(['comment', 'get', id]))
24060
- .filter(isNonNullable)
24061
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.comment);
24062
- if (!this.shouldNotify(data) && origin === 'event')
24063
- return;
24064
- this.callback({
24065
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
24066
- data,
24067
- hasNextPage: !!this.paginationController.getNextToken(),
24068
- loading,
24069
- error,
24070
- });
24071
- }
24072
- applyFilter(data) {
24073
- let comments = data;
24074
- if (!this.query.includeDeleted) {
24075
- comments = filterByPropEquality(comments, 'isDeleted', false);
24076
- }
24077
- if (this.query.parentId) {
24078
- comments = comments.filter(comment => comment.parentId === this.query.parentId);
24079
- }
24080
- if (typeof this.query.hasFlag === 'boolean') {
24081
- if (this.query.hasFlag) {
24082
- comments = comments.filter(comment => comment.hashFlag != null);
24083
- }
24084
- else {
24085
- comments = comments.filter(comment => comment.hashFlag == null);
24086
- }
24087
- }
24088
- if (this.query.dataTypes) {
24089
- if (this.query.dataTypes.matchType === 'exact') {
24090
- comments = comments.filter(comment => {
24091
- var _a, _b;
24092
- const sortedDataTypesQueryValue = ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.sort()) || [];
24093
- const sortedDataTypesCommentValue = ((_b = comment.dataTypes) === null || _b === void 0 ? void 0 : _b.sort()) || [];
24094
- if (sortedDataTypesCommentValue.length !== sortedDataTypesQueryValue.length) {
24095
- return false;
24096
- }
24097
- return sortedDataTypesQueryValue.every((value, index) => value === sortedDataTypesCommentValue[index]);
24098
- });
24099
- }
24100
- if (this.query.dataTypes.matchType === 'any') {
24101
- 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); }); });
24102
- }
24103
- }
24104
- switch (this.query.sortBy) {
24105
- case 'firstCreated':
24106
- comments = comments.sort(sortByFirstCreated);
24107
- break;
24108
- case 'lastCreated':
24109
- default:
24110
- comments = comments.sort(sortByLastCreated);
24111
- break;
24112
- }
24113
- return comments;
24114
- }
24115
- }
24041
+ /* end_public_function */
24116
24042
 
24117
24043
  /* begin_public_function
24118
- id: comment.query
24044
+ id: comment.hard_delete
24119
24045
  */
24120
24046
  /**
24121
24047
  * ```js
24122
- * import { getComments } from '@amityco/ts-sdk'
24123
- *
24124
- * let comments = []
24125
- * const unsub = getComments({
24126
- * referenceType: Amity.InternalComment['referenceType'];
24127
- * referenceId: Amity.InternalComment['referenceId'];
24128
- * }, response => merge(comments, response.data))
24048
+ * import { CommentRepository } from '@amityco/ts-sdk'
24049
+ * const success = await CommentRepository.hardDeleteComment('foobar')
24129
24050
  * ```
24130
24051
  *
24131
- * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
24052
+ * Deletes a {@link Amity.Comment}
24132
24053
  *
24133
- * @param referenceType the type of the target
24134
- * @param referenceId the ID of the target
24135
- * @param callback the function to call when new data are available
24136
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
24054
+ * @param commentId The {@link Amity.Comment} ID to delete
24055
+ * @return A success boolean if the {@link Amity.Comment} was deleted
24137
24056
  *
24138
- * @category Comments Live Collection
24057
+ * @category Comment API
24058
+ * @async
24139
24059
  */
24140
- const getComments = (params, callback, config) => {
24141
- const { log, cache } = getActiveClient();
24142
- if (!cache) {
24143
- console.log('For using Live Collection feature you need to enable Cache!');
24144
- }
24145
- const timestamp = Date.now();
24146
- log(`getComments(tmpid: ${timestamp}) > listen`);
24147
- const commentsLiveCollection = new CommentLiveCollectionController(params, callback);
24148
- const disposers = commentsLiveCollection.startSubscription();
24149
- const cacheKey = commentsLiveCollection.getCacheKey();
24150
- disposers.push(() => dropFromCache(cacheKey));
24151
- return () => {
24152
- log(`getComments(tmpid: ${timestamp}) > dispose`);
24153
- disposers.forEach(fn => fn());
24060
+ const hardDeleteComment = async (commentId) => {
24061
+ const client = getActiveClient();
24062
+ client.log('comment/hardDeleteComment', commentId);
24063
+ const hardDeleted = deleteComment(commentId, true);
24064
+ return hardDeleted;
24065
+ };
24066
+ /* end_public_function */
24067
+
24068
+ /* begin_public_function
24069
+ id: comment.flag
24070
+ */
24071
+ /**
24072
+ * ```js
24073
+ * import { CommentRepository } from '@amityco/ts-sdk'
24074
+ * const flagged = await CommentRepository.flagComment(commentId, reason)
24075
+ * ```
24076
+ *
24077
+ * @param commentId The ID of the comment to flag
24078
+ * @param reason the reason to flag the comment
24079
+ * @returns the created report result
24080
+ *
24081
+ * @category Comment API
24082
+ * @async
24083
+ * */
24084
+ const flagComment = async (commentId, reason) => {
24085
+ const client = getActiveClient();
24086
+ client.log('comment/flagComment', commentId);
24087
+ const isPredefinedReason = reason &&
24088
+ Object.entries(exports.ContentFlagReasonEnum).some(([key, value]) => key !== exports.ContentFlagReasonEnum.Others && value === reason);
24089
+ const body = {
24090
+ reason: reason && isPredefinedReason ? reason : exports.ContentFlagReasonEnum.Others,
24091
+ detail: reason && !isPredefinedReason ? reason : '',
24154
24092
  };
24093
+ const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/flag`, body);
24094
+ if (client.cache) {
24095
+ ingestInCache(payload);
24096
+ }
24097
+ fireEvent('comment.flagged', payload);
24098
+ return !!payload;
24155
24099
  };
24156
24100
  /* end_public_function */
24157
24101
 
24158
- var index$a = /*#__PURE__*/Object.freeze({
24159
- __proto__: null,
24160
- getCommentByIds: getCommentByIds,
24161
- createComment: createComment,
24162
- updateComment: updateComment,
24163
- deleteComment: deleteComment,
24164
- softDeleteComment: softDeleteComment,
24165
- hardDeleteComment: hardDeleteComment,
24166
- flagComment: flagComment,
24167
- unflagComment: unflagComment,
24168
- isCommentFlaggedByMe: isCommentFlaggedByMe,
24169
- onCommentCreated: onCommentCreated,
24170
- onCommentUpdated: onCommentUpdated,
24171
- onCommentDeleted: onCommentDeleted,
24172
- onCommentFlagged: onCommentFlagged,
24173
- onCommentUnflagged: onCommentUnflagged,
24174
- onCommentReactionAdded: onCommentReactionAdded,
24175
- onCommentReactionRemoved: onCommentReactionRemoved,
24176
- getComment: getComment,
24177
- getComments: getComments
24178
- });
24102
+ /* begin_public_function
24103
+ id: comment.unflag
24104
+ */
24105
+ /**
24106
+ * ```js
24107
+ * import { CommentRepository } from '@amityco/ts-sdk'
24108
+ * const unflagged = await CommentRepository.unflagComment('commentId')
24109
+ * ```
24110
+ *
24111
+ * @param commentId The ID of comment to unflag
24112
+ * @returns the unflagged result
24113
+ *
24114
+ * @category Comment API
24115
+ * @async
24116
+ * */
24117
+ const unflagComment = async (commentId) => {
24118
+ const client = getActiveClient();
24119
+ client.log('comment/unflagComment', commentId);
24120
+ const { data: payload } = await client.http.delete(`/api/v3/comments/${encodeURIComponent(commentId)}/unflag`);
24121
+ if (client.cache) {
24122
+ ingestInCache(payload);
24123
+ }
24124
+ fireEvent('comment.unflagged', payload);
24125
+ return !!payload;
24126
+ };
24127
+ /* end_public_function */
24128
+
24129
+ /* begin_public_function
24130
+ id: comment.check_flag_by_me
24131
+ */
24132
+ /**
24133
+ * ```js
24134
+ * import { CommentRepository } from '@amityco/ts-sdk'
24135
+ * const isReported = await CommentRepository.isCommentFlaggedByMe('commentId')
24136
+ * ```
24137
+ *
24138
+ * @param commentId The ID of the comment to check if flagged by current user
24139
+ * @returns `true` if the comment is flagged by me, `false` if doesn't.
24140
+ *
24141
+ * @category Comment API
24142
+ * @async
24143
+ * */
24144
+ const isCommentFlaggedByMe = async (commentId) => {
24145
+ const client = getActiveClient();
24146
+ client.log('comment/isCommentFlaggedByMe', commentId);
24147
+ const { data: { result }, } = await client.http.get(`/api/v3/comments/${commentId}/isflagbyme`);
24148
+ return result;
24149
+ };
24150
+ /* end_public_function */
24179
24151
 
24180
- const getPost$1 = async (postId) => {
24152
+ const getComment$1 = async (commentId) => {
24181
24153
  const client = getActiveClient();
24182
- client.log('post/getPost', postId);
24183
- isInTombstone('post', postId);
24184
- let payload;
24154
+ client.log('comment/getComment', commentId);
24155
+ isInTombstone('comment', commentId);
24156
+ let data;
24185
24157
  try {
24186
24158
  // API-FIX: endpoint should not be /list, parameters should be querystring.
24187
- const response = await client.http.get(`/api/v3/posts/${encodeURIComponent(postId)}`);
24188
- payload = response.data;
24159
+ const response = await client.http.get(`/api/v3/comments/${encodeURIComponent(commentId)}`);
24160
+ data = response.data;
24189
24161
  }
24190
24162
  catch (error) {
24191
24163
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
24192
- pushToTombstone('post', postId);
24164
+ pushToTombstone('comment', commentId);
24193
24165
  }
24194
24166
  throw error;
24195
24167
  }
24196
- const data = prepareMembershipPayload(payload, 'communityUsers');
24197
24168
  const cachedAt = client.cache && Date.now();
24198
24169
  if (client.cache)
24199
24170
  ingestInCache(data, { cachedAt });
24200
- const { posts } = data;
24201
- const result = posts.find(post => post.postId === postId);
24171
+ const { comments } = data;
24202
24172
  return {
24203
- data: result,
24173
+ data: comments.find(comment => comment.commentId === commentId),
24204
24174
  cachedAt,
24205
24175
  };
24206
24176
  };
24207
- getPost$1.locally = (postId) => {
24177
+ getComment$1.locally = (commentId) => {
24208
24178
  const client = getActiveClient();
24209
- client.log('post/getPost.locally', postId);
24179
+ client.log('comment/getComment.locally', commentId);
24210
24180
  if (!client.cache)
24211
24181
  return;
24212
- const cached = pullFromCache(['post', 'get', postId]);
24182
+ const cached = pullFromCache(['comment', 'get', commentId]);
24213
24183
  if (!cached)
24214
24184
  return;
24215
24185
  return {
@@ -24220,164 +24190,254 @@ getPost$1.locally = (postId) => {
24220
24190
 
24221
24191
  /**
24222
24192
  * ```js
24223
- * import { onPostUpdatedLocal } from '@amityco/ts-sdk'
24224
- * const dispose = onPostUpdatedLocal(post => {
24193
+ * import { onCommentDeleteLocal } from '@amityco/ts-sdk'
24194
+ * const dispose = onCommentDeleteLocal(comment => {
24225
24195
  * // ...
24226
24196
  * })
24227
24197
  * ```
24228
24198
  *
24229
- * Fired when a {@link Amity.InternalPost} has been updated
24199
+ * Fired when a {@link Amity.InternalComment} has been deleted
24230
24200
  *
24231
24201
  * @param callback The function to call when the event was fired
24232
24202
  * @returns an {@link Amity.Unsubscriber} function to stop listening
24233
24203
  *
24234
- * @category Post Events
24204
+ * @category Comment Events
24235
24205
  */
24236
- const onPostUpdatedLocal = (callback) => createLocalPostEventSubscriber('local.post.updated', callback);
24206
+ const onCommentDeleteLocal = (callback) => createLocalCommentEventSubscriber('local.comment.deleted', callback);
24237
24207
 
24238
24208
  /**
24239
24209
  * ```js
24240
- * import { onLocalPostReactionAdded } from '@amityco/ts-sdk'
24241
- * const dispose = onPostReactionAdded(post => {
24210
+ * import { onLocalCommentReactionAdded } from '@amityco/ts-sdk'
24211
+ * const dispose = onLocalCommentReactionAdded(comment => {
24242
24212
  * // ...
24243
24213
  * })
24244
24214
  * ```
24245
24215
  *
24246
- * Fired when a {@link Amity.InternalPost} has been reacted
24216
+ * Fired when a {@link Amity.InternalComment} has been reacted
24247
24217
  *
24248
24218
  * @param callback The function to call when the event was fired
24249
24219
  * @returns an {@link Amity.Unsubscriber} function to stop listening
24250
24220
  *
24251
- * @category Post Events
24221
+ * @category Comment Events
24252
24222
  */
24253
- const onLocalPostReactionAdded = (callback) => {
24223
+ const onLocalCommentReactionAdded = (callback) => {
24254
24224
  const client = getActiveClient();
24255
- const filter = ({ post }) => {
24225
+ const filter = ({ comment }) => {
24256
24226
  if (!client.cache) {
24257
- callback(post);
24227
+ callback(comment);
24258
24228
  }
24259
24229
  else {
24260
- upsertInCache(['post', 'get', post.postId], post);
24261
- callback(post);
24230
+ upsertInCache(['comment', 'get', comment.commentId], comment);
24231
+ callback(commentLinkedObject(comment));
24262
24232
  }
24263
24233
  };
24264
- return createEventSubscriber(client, 'local.post.addReaction', 'local.post.addReaction', filter);
24234
+ return createEventSubscriber(client, 'local.comment.addReaction', 'local.comment.addReaction', filter);
24265
24235
  };
24266
24236
 
24267
24237
  /**
24268
24238
  * ```js
24269
- * import { onLocalPostReactionRemoved } from '@amityco/ts-sdk'
24270
- * const dispose = onPostReactionRemoved(post => {
24239
+ * import { onLocalCommentReactionRemoved } from '@amityco/ts-sdk'
24240
+ * const dispose = onLocalCommentReactionRemoved(comment => {
24271
24241
  * // ...
24272
24242
  * })
24273
24243
  * ```
24274
24244
  *
24275
- * Fired when a {@link Amity.InternalPost} has been reacted
24245
+ * Fired when a {@link Amity.InternalComment} has been reacted
24276
24246
  *
24277
24247
  * @param callback The function to call when the event was fired
24278
24248
  * @returns an {@link Amity.Unsubscriber} function to stop listening
24279
24249
  *
24280
- * @category Post Events
24250
+ * @category Comment Events
24281
24251
  */
24282
- const onLocalPostReactionRemoved = (callback) => {
24252
+ const onLocalCommentReactionRemoved = (callback) => {
24283
24253
  const client = getActiveClient();
24284
- const filter = ({ post }) => {
24254
+ const filter = ({ comment }) => {
24285
24255
  if (!client.cache) {
24286
- callback(post);
24256
+ callback(comment);
24287
24257
  }
24288
24258
  else {
24289
- upsertInCache(['post', 'get', post.postId], post);
24290
- callback(post);
24259
+ upsertInCache(['comment', 'get', comment.commentId], comment);
24260
+ callback(commentLinkedObject(comment));
24291
24261
  }
24292
24262
  };
24293
- return createEventSubscriber(client, 'local.post.removeReaction', 'local.post.removeReaction', filter);
24263
+ return createEventSubscriber(client, 'local.comment.removeReaction', 'local.comment.removeReaction', filter);
24294
24264
  };
24295
24265
 
24266
+ /* begin_public_function
24267
+ id: comment.get
24268
+ */
24296
24269
  /**
24297
24270
  * ```js
24298
- * import { onLocalPostDeleted } from '@amityco/ts-sdk'
24299
- * const dispose = onLocalPostDeleted(post => {
24300
- * // ...
24301
- * })
24271
+ * import { CommentRepository } from '@amityco/ts-sdk';
24272
+ *
24273
+ * let comment;
24274
+ *
24275
+ * const unsub = CommentRepository.getComment(commentId, response => {
24276
+ * comment = response.data;
24277
+ * });
24302
24278
  * ```
24303
24279
  *
24304
- * Fired when a {@link Amity.InternalPost} has been deleted
24280
+ * Observe all mutation on a given {@link Amity.Comment}
24305
24281
  *
24306
- * @param callback The function to call when the event was fired
24307
- * @returns an {@link Amity.Unsubscriber} function to stop listening
24282
+ * @param commentId the ID of the comment to observe
24283
+ * @param callback the function to call when new data are available
24284
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
24308
24285
  *
24309
- * @category Post Events
24286
+ * @category Comment Live Object
24310
24287
  */
24311
- const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.post.deleted', callback);
24288
+ const getComment = (commentId, callback) => {
24289
+ return liveObject(commentId, callback, 'commentId', getComment$1, [
24290
+ onCommentDeleteLocal,
24291
+ onCommentDeleted,
24292
+ onCommentFlagged,
24293
+ onCommentReactionAdded,
24294
+ onCommentReactionRemoved,
24295
+ onCommentUnflagged,
24296
+ onCommentUpdated,
24297
+ onLocalCommentReactionAdded,
24298
+ onLocalCommentReactionRemoved,
24299
+ ]);
24300
+ };
24301
+ /* end_public_function */
24312
24302
 
24313
- class UserFeedLiveCollectionController extends LiveCollectionController {
24314
- constructor(query, callback) {
24315
- const queryStreamId = hash__default["default"](query);
24316
- const cacheKey = ['userFeed', 'collection', queryStreamId];
24317
- const paginationController = new UserFeedPaginationController(query);
24318
- super(paginationController, queryStreamId, cacheKey, callback);
24319
- this.query = query;
24320
- this.queryStreamController = new UserFeedQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), preparePostPayload);
24321
- this.callback = callback.bind(this);
24322
- this.loadPage({ initial: true });
24323
- }
24324
- setup() {
24325
- var _a;
24326
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24327
- if (!collection) {
24328
- pushToCache(this.cacheKey, {
24329
- data: [],
24330
- params: {},
24331
- });
24332
- }
24303
+ class CommentPaginationController extends PaginationController {
24304
+ async getRequest(queryParams, token) {
24305
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
24306
+ const baseOptions = {
24307
+ type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
24308
+ };
24309
+ const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
24310
+ const { data: queryResponse } = await this.http.get(`/api/v3/comments`, {
24311
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
24312
+ });
24313
+ return queryResponse;
24333
24314
  }
24334
- async persistModel(queryPayload) {
24335
- await this.queryStreamController.saveToMainDB(queryPayload);
24315
+ }
24316
+
24317
+ var EnumCommentActions;
24318
+ (function (EnumCommentActions) {
24319
+ EnumCommentActions["OnCommentCreated"] = "onCommentCreated";
24320
+ EnumCommentActions["OnCommentUpdated"] = "onCommentUpdated";
24321
+ EnumCommentActions["OnCommentDeleted"] = "onCommentDeleted";
24322
+ EnumCommentActions["OnCommentFlagged"] = "onCommentFlagged";
24323
+ EnumCommentActions["OnCommentUnflagged"] = "onCommentUnflagged";
24324
+ EnumCommentActions["OnCommentReactionAdded"] = "onCommentReactionAdded";
24325
+ EnumCommentActions["OnCommentReactionRemoved"] = "onCommentReactionRemoved";
24326
+ })(EnumCommentActions || (EnumCommentActions = {}));
24327
+
24328
+ class CommentQueryStreamController extends QueryStreamController {
24329
+ constructor(query, cacheKey, notifyChange, preparePayload) {
24330
+ super(query, cacheKey);
24331
+ this.notifyChange = notifyChange;
24332
+ this.preparePayload = preparePayload;
24333
+ }
24334
+ async saveToMainDB(response) {
24335
+ const processedPayload = await this.preparePayload(response);
24336
+ const client = getActiveClient();
24337
+ const cachedAt = client.cache && Date.now();
24338
+ if (client.cache) {
24339
+ ingestInCache(processedPayload, { cachedAt });
24340
+ }
24341
+ }
24342
+ appendToQueryStream(response, direction, refresh = false) {
24343
+ var _a, _b;
24344
+ if (refresh) {
24345
+ pushToCache(this.cacheKey, {
24346
+ data: response.comments.map(getResolver('comment')),
24347
+ });
24348
+ }
24349
+ else {
24350
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24351
+ const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
24352
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...response.comments.map(getResolver('comment'))])] }));
24353
+ }
24354
+ }
24355
+ reactor(action) {
24356
+ return (comment) => {
24357
+ var _a;
24358
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24359
+ if (this.query.referenceId !== comment.referenceId ||
24360
+ this.query.referenceType !== comment.referenceType ||
24361
+ !collection) {
24362
+ return;
24363
+ }
24364
+ if (this.query.parentId && this.query.parentId !== comment.parentId) {
24365
+ return;
24366
+ }
24367
+ if (!this.query.parentId && comment.parentId) {
24368
+ return;
24369
+ }
24370
+ if (action === EnumCommentActions.OnCommentCreated) {
24371
+ collection.data = [...new Set([comment.commentId, ...collection.data])];
24372
+ }
24373
+ pushToCache(this.cacheKey, collection);
24374
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
24375
+ };
24376
+ }
24377
+ subscribeRTE(createSubscriber) {
24378
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
24379
+ }
24380
+ }
24381
+
24382
+ /**
24383
+ * ```js
24384
+ * import { onCommentCreated } from '@amityco/ts-sdk'
24385
+ * const dispose = onCommentCreated(comment => {
24386
+ * // ...
24387
+ * })
24388
+ * ```
24389
+ *
24390
+ * Fired when a {@link Amity.InternalComment} has been created
24391
+ *
24392
+ * @param callback The function to call when the event was fired
24393
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
24394
+ *
24395
+ * @category Comment Events
24396
+ */
24397
+ const onCommentCreatedLocal = (callback) => {
24398
+ return createLocalCommentEventSubscriber('local.comment.created', callback);
24399
+ };
24400
+
24401
+ class CommentLiveCollectionController extends LiveCollectionController {
24402
+ constructor(query, callback) {
24403
+ const queryStreamId = hash__default["default"](query);
24404
+ const cacheKey = ['comments', 'collection', queryStreamId];
24405
+ const paginationController = new CommentPaginationController(query);
24406
+ super(paginationController, queryStreamId, cacheKey, callback);
24407
+ this.query = query;
24408
+ this.queryStreamController = new CommentQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommentPayload);
24409
+ this.callback = callback.bind(this);
24410
+ this.loadPage({ initial: true });
24411
+ }
24412
+ setup() {
24413
+ var _a;
24414
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24415
+ if (!collection) {
24416
+ pushToCache(this.cacheKey, {
24417
+ data: [],
24418
+ params: {},
24419
+ });
24420
+ }
24421
+ }
24422
+ async persistModel(queryPayload) {
24423
+ await this.queryStreamController.saveToMainDB(queryPayload);
24336
24424
  }
24337
24425
  persistQueryStream({ response, direction, refresh, }) {
24338
24426
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
24339
24427
  }
24340
24428
  startSubscription() {
24341
24429
  return this.queryStreamController.subscribeRTE([
24342
- { fn: onPostCreated, action: EnumPostActions.OnPostCreated },
24343
- { fn: onPostUpdated, action: EnumPostActions.OnPostUpdated },
24344
- { fn: onPostUpdatedLocal, action: EnumPostActions.OnPostUpdated },
24345
- { fn: onPostDeleted, action: EnumPostActions.OnPostDeleted },
24346
- { fn: onPostFlagged, action: EnumPostActions.OnPostFlagged },
24347
- { fn: onPostUnflagged, action: EnumPostActions.OnPostUnflagged },
24348
- { fn: onPostApproved, action: EnumPostActions.OnPostApproved },
24349
- { fn: onPostDeclined, action: EnumPostActions.OnPostDeclined },
24350
- { fn: onPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
24351
- { fn: onPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
24352
- { fn: onLocalPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
24353
- { fn: onLocalPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
24354
- { fn: onLocalPostDeleted, action: EnumPostActions.OnPostDeleted },
24355
- {
24356
- fn: convertEventPayload((callback) => {
24357
- return onCommentCreated(async (comment) => {
24358
- var _a;
24359
- const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24360
- if (!currentCollection || currentCollection.data.includes(comment.referenceId))
24361
- return;
24362
- await getPost$1(comment.referenceId);
24363
- callback(comment);
24364
- });
24365
- }, 'referenceId', 'post'),
24366
- action: EnumPostActions.OnPostUpdated,
24367
- },
24368
- {
24369
- fn: convertEventPayload((callback) => {
24370
- return onCommentDeleted(async (comment) => {
24371
- var _a;
24372
- const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
24373
- if (!currentCollection || currentCollection.data.includes(comment.referenceId))
24374
- return;
24375
- await getPost$1(comment.referenceId);
24376
- callback(comment);
24377
- });
24378
- }, 'referenceId', 'post'),
24379
- action: EnumPostActions.OnPostUpdated,
24380
- },
24430
+ { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
24431
+ { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
24432
+ { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
24433
+ { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
24434
+ { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
24435
+ { fn: onCommentFlagged, action: EnumCommentActions.OnCommentFlagged },
24436
+ { fn: onCommentUnflagged, action: EnumCommentActions.OnCommentUnflagged },
24437
+ { fn: onCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
24438
+ { fn: onCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
24439
+ { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
24440
+ { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
24381
24441
  ]);
24382
24442
  }
24383
24443
  notifyChange({ origin, loading, error }) {
@@ -24386,9 +24446,9 @@ class UserFeedLiveCollectionController extends LiveCollectionController {
24386
24446
  if (!collection)
24387
24447
  return;
24388
24448
  const data = this.applyFilter((_b = collection.data
24389
- .map(id => pullFromCache(['post', 'get', id]))
24449
+ .map(id => pullFromCache(['comment', 'get', id]))
24390
24450
  .filter(isNonNullable)
24391
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.post);
24451
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.comment);
24392
24452
  if (!this.shouldNotify(data) && origin === 'event')
24393
24453
  return;
24394
24454
  this.callback({
@@ -24400,560 +24460,204 @@ class UserFeedLiveCollectionController extends LiveCollectionController {
24400
24460
  });
24401
24461
  }
24402
24462
  applyFilter(data) {
24403
- var _a;
24404
- let posts = data;
24463
+ let comments = data;
24405
24464
  if (!this.query.includeDeleted) {
24406
- posts = filterByPropEquality(posts, 'isDeleted', false);
24465
+ comments = filterByPropEquality(comments, 'isDeleted', false);
24407
24466
  }
24408
- if ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.length) {
24409
- posts = filterByPostDataTypes(posts, this.query.dataTypes);
24467
+ if (this.query.parentId) {
24468
+ comments = comments.filter(comment => comment.parentId === this.query.parentId);
24469
+ }
24470
+ if (typeof this.query.hasFlag === 'boolean') {
24471
+ if (this.query.hasFlag) {
24472
+ comments = comments.filter(comment => comment.hashFlag != null);
24473
+ }
24474
+ else {
24475
+ comments = comments.filter(comment => comment.hashFlag == null);
24476
+ }
24477
+ }
24478
+ if (this.query.dataTypes) {
24479
+ if (this.query.dataTypes.matchType === 'exact') {
24480
+ comments = comments.filter(comment => {
24481
+ var _a, _b;
24482
+ const sortedDataTypesQueryValue = ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.sort()) || [];
24483
+ const sortedDataTypesCommentValue = ((_b = comment.dataTypes) === null || _b === void 0 ? void 0 : _b.sort()) || [];
24484
+ if (sortedDataTypesCommentValue.length !== sortedDataTypesQueryValue.length) {
24485
+ return false;
24486
+ }
24487
+ return sortedDataTypesQueryValue.every((value, index) => value === sortedDataTypesCommentValue[index]);
24488
+ });
24489
+ }
24490
+ if (this.query.dataTypes.matchType === 'any') {
24491
+ 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); }); });
24492
+ }
24410
24493
  }
24411
24494
  switch (this.query.sortBy) {
24412
24495
  case 'firstCreated':
24413
- posts = posts.sort(sortByFirstCreated);
24496
+ comments = comments.sort(sortByFirstCreated);
24414
24497
  break;
24415
24498
  case 'lastCreated':
24416
24499
  default:
24417
- posts = posts.sort(sortByLastCreated);
24500
+ comments = comments.sort(sortByLastCreated);
24418
24501
  break;
24419
24502
  }
24420
- return posts;
24503
+ return comments;
24421
24504
  }
24422
24505
  }
24423
24506
 
24424
24507
  /* begin_public_function
24425
- id: feed.query.user_feed
24508
+ id: comment.query
24426
24509
  */
24427
24510
  /**
24428
24511
  * ```js
24429
- * import { FeedRepository } from '@amityco/ts-sdk'
24512
+ * import { getComments } from '@amityco/ts-sdk'
24430
24513
  *
24431
- * let posts = []
24432
- * const unsubscribe = FeedRepository.getUserFeed({
24433
- * userId: string,
24434
- * feedSources: ['user', 'community'],
24435
- * }, response => response => processResponse(response))
24514
+ * let comments = []
24515
+ * const unsub = getComments({
24516
+ * referenceType: Amity.InternalComment['referenceType'];
24517
+ * referenceId: Amity.InternalComment['referenceId'];
24518
+ * }, response => merge(comments, response.data))
24436
24519
  * ```
24437
24520
  *
24438
- * Observe all mutations on a list of {@link Amity.Post} for a given user and feedSources
24521
+ * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
24439
24522
  *
24440
- * @param params.userId the ID of the user
24441
- * @param params.feedSources the sources of the feed
24523
+ * @param referenceType the type of the target
24524
+ * @param referenceId the ID of the target
24442
24525
  * @param callback the function to call when new data are available
24443
- * @param config
24444
24526
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
24445
- *
24446
- * @category Posts Live Collection
24447
- */
24448
- const getUserFeed = (params, callback, config) => {
24449
- const { log, cache } = getActiveClient();
24450
- if (!cache) {
24451
- console.log(ENABLE_CACHE_MESSAGE);
24452
- }
24453
- const timestamp = Date.now();
24454
- log(`getUserFeed(tmpid: ${timestamp}) > listen`);
24455
- const userFeedLiveCollection = new UserFeedLiveCollectionController(params, callback);
24456
- const disposers = userFeedLiveCollection.startSubscription();
24457
- const cacheKey = userFeedLiveCollection.getCacheKey();
24458
- disposers.push(() => dropFromCache(cacheKey));
24459
- return () => {
24460
- log(`getUserFeed(tmpid: ${timestamp}) > dispose`);
24461
- disposers.forEach(fn => fn());
24462
- };
24463
- };
24464
- /* end_public_function */
24465
-
24466
- var index$9 = /*#__PURE__*/Object.freeze({
24467
- __proto__: null,
24468
- queryGlobalFeed: queryGlobalFeed,
24469
- getCustomRankingGlobalFeed: getCustomRankingGlobalFeed,
24470
- getUserFeed: getUserFeed
24471
- });
24472
-
24473
- /* begin_public_function
24474
- id: post.get_by_ids
24475
- */
24476
- /**
24477
- * ```js
24478
- * import { getPostByIds } from '@amityco/ts-sdk'
24479
- * const { data: posts } = await getPostByIds(['foo', 'bar'])
24480
- * ```
24481
- *
24482
- * Fetches a collection of {@link Amity.Post} objects
24483
- *
24484
- * @param postIds the IDs of the {@link Amity.Post} to fetch
24485
- * @returns the associated collection of {@link Amity.Post} objects
24486
- *
24487
- * @category Post API
24488
- * @async
24489
- */
24490
- const getPostByIds = async (postIds) => {
24491
- const client = getActiveClient();
24492
- client.log('post/getPostByIds', postIds);
24493
- const encodedPostIds = postIds.map(postId => encodeURIComponent(postId));
24494
- let payload;
24495
- try {
24496
- // API-FIX: endpoint should not be /list, parameters should be querystring.
24497
- const response = await client.http.get(`/api/v3/posts/list`, {
24498
- params: { postIds: encodedPostIds },
24499
- });
24500
- payload = response.data;
24501
- }
24502
- catch (error) {
24503
- postIds.forEach(postId => {
24504
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
24505
- pushToTombstone('post', postId);
24506
- }
24507
- });
24508
- throw error;
24509
- }
24510
- const data = prepareMembershipPayload(payload, 'communityUsers');
24511
- const cachedAt = client.cache && Date.now();
24512
- if (client.cache)
24513
- ingestInCache(data, { cachedAt });
24514
- return {
24515
- data: data.posts.map(LinkedObject.post),
24516
- cachedAt,
24517
- };
24518
- };
24519
- /* end_public_function */
24520
- /**
24521
- * ```js
24522
- * import { getPostByIds } from '@amityco/ts-sdk'
24523
- * const { data: posts } = getPostByIds.locally(['foo', 'bar'])
24524
- * ```
24525
- *
24526
- * Fetches a collection of {@link Amity.Post} objects from cache
24527
- *
24528
- * @param postIds the IDs of the {@link Amity.Post} to fetch
24529
- * @returns the associated collection of {@link Amity.Post} objects
24530
- *
24531
- * @category Post API
24532
- */
24533
- getPostByIds.locally = (postIds) => {
24534
- var _a;
24535
- const client = getActiveClient();
24536
- client.log('post/getPostByIds.locally', postIds);
24537
- if (!client.cache)
24538
- return;
24539
- const cached = postIds
24540
- .map(postId => pullFromCache(['post', 'get', postId]))
24541
- .filter(Boolean);
24542
- const posts = cached.map(({ data }) => data);
24543
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
24544
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < postIds.length)
24545
- return;
24546
- return {
24547
- data: posts.map(LinkedObject.post),
24548
- cachedAt: oldest.cachedAt,
24549
- };
24550
- };
24551
-
24552
- /* begin_public_function
24553
- 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
24554
- */
24555
- /**
24556
- * ```js
24557
- * import { PostRepository } from '@amityco/ts-sdk'
24558
- * const created = await PostRepository.createPost({
24559
- * targetType: 'user',
24560
- * targetId: 'foobar',
24561
- * data: { text: 'hello world' }
24562
- * }))
24563
- * ```
24564
- *
24565
- * Creates an {@link Amity.Post}
24566
- *
24567
- * @param bundle The data necessary to create a new {@link Amity.Post}
24568
- * @returns The newly created {@link Amity.Post}
24569
- *
24570
- * @category Post API
24571
- * @async
24572
- */
24573
- const createPost = async (bundle) => {
24574
- const client = getActiveClient();
24575
- client.log('post/createPost', bundle);
24576
- if (!bundle.dataType || ['text', 'image', 'file', 'video'].includes(bundle.dataType)) {
24577
- // eslint-disable-next-line no-param-reassign
24578
- delete bundle.dataType;
24579
- }
24580
- const { data: payload } = await client.http.post('/api/v4/posts', bundle);
24581
- fireEvent('post.created', payload);
24582
- const data = preparePostPayload(payload);
24583
- const cachedAt = client.cache && Date.now();
24584
- if (client.cache)
24585
- ingestInCache(data, { cachedAt });
24586
- const { posts } = data;
24587
- return {
24588
- data: LinkedObject.post(posts[0]),
24589
- cachedAt,
24590
- };
24591
- };
24592
- /* end_public_function */
24593
-
24594
- /* begin_public_function
24595
- id: post.edit, post.edit.custom_post
24596
- */
24597
- /**
24598
- * ```js
24599
- * import { PostRepository } from '@amityco/ts-sdk'
24600
- * const updated = await PostRepository.editPost(postId, {
24601
- * data: { text: 'hello world' }
24602
- * })
24603
- * ```
24604
- *
24605
- * Updates an {@link Amity.Post}
24606
- *
24607
- * @param postId The ID of the {@link Amity.Post} to edit
24608
- * @param patch The patch data to apply
24609
- * @returns the updated {@link Amity.Post} object
24610
- *
24611
- * @category Post API
24612
- * @async
24613
- */
24614
- const editPost = async (postId, patch) => {
24615
- const client = getActiveClient();
24616
- client.log('user/editPost', patch);
24617
- const { data: payload } = await client.http.put(`/api/v4/posts/${encodeURIComponent(postId)}`, patch);
24618
- const data = prepareMembershipPayload(payload, 'communityUsers');
24619
- const cachedAt = client.cache && Date.now();
24620
- if (client.cache)
24621
- ingestInCache(data, { cachedAt });
24622
- fireEvent('local.post.updated', data);
24623
- const { posts } = data;
24624
- return {
24625
- data: LinkedObject.post(posts.find(post => post.postId === postId)),
24626
- cachedAt,
24627
- };
24628
- };
24629
- /* end_public_function */
24630
-
24631
- /**
24632
- * ```js
24633
- * import { deletePost } from '@amityco/ts-sdk'
24634
- * const success = await deletePost('foobar')
24635
- * ```
24636
- *
24637
- * Deletes a {@link Amity.Post}
24638
- *
24639
- * @param postId The {@link Amity.Post} ID to delete
24640
- * @return A success boolean if the {@link Amity.Post} was deleted
24641
- *
24642
- * @private
24643
- * @async
24644
- */
24645
- const deletePost = async (postId, permanent = false) => {
24646
- var _a;
24647
- const client = getActiveClient();
24648
- const post = await getPost$2(postId);
24649
- await client.http.delete(`/api/v4/posts/${encodeURIComponent(postId)}`, {
24650
- params: {
24651
- postId,
24652
- permanent,
24653
- },
24654
- });
24655
- // there is currently a limitation which doesn't allow us to fire event to tell that community
24656
- // has been updated. reason is that, when the object is deleted, we don't have its `communityId`
24657
- // and so we cannot refetch the community or advertise on events. hopefully this should be solved
24658
- // later when realtime events covers that for us.
24659
- if (post.data.targetType === 'community') {
24660
- const community = await getCommunity$1(post.data.targetId);
24661
- const communityUsersCache = (_a = queryCache(['communityUsers', 'get'])) !== null && _a !== void 0 ? _a : [];
24662
- const communityUsers = communityUsersCache
24663
- .filter(({ key }) => {
24664
- // cache key is ['communityUsers', 'get', `${communityId}#`${userId}`}]
24665
- if (key[0] !== 'communityUsers')
24666
- return false;
24667
- if (key[1] !== 'get')
24668
- return false;
24669
- if (typeof key[2] === 'string')
24670
- return key[2].includes(community.data.communityId);
24671
- return false;
24672
- })
24673
- .map(({ data }) => data);
24674
- fireEvent('community.updated', {
24675
- communities: [community.data],
24676
- categories: [],
24677
- communityUsers,
24678
- feeds: [],
24679
- files: [],
24680
- users: [],
24681
- });
24682
- }
24683
- // to support hard deletion
24684
- const deleted = Object.assign(Object.assign({}, post.data), { isDeleted: true });
24685
- if (permanent) {
24686
- setTimeout(() => {
24687
- pushToTombstone('post', postId);
24688
- }, 0);
24689
- }
24690
- else {
24691
- upsertInCache(['post', 'get', postId], { isDeleted: true });
24692
- }
24693
- fireEvent('local.post.deleted', {
24694
- posts: [deleted],
24695
- categories: [],
24696
- comments: [],
24697
- communities: [],
24698
- communityUsers: [],
24699
- feeds: [],
24700
- files: [],
24701
- postChildren: [],
24702
- users: [],
24703
- videoStreamings: [],
24704
- });
24705
- return LinkedObject.post(deleted);
24706
- };
24707
-
24708
- /* begin_public_function
24709
- id: post.soft_delete
24710
- */
24711
- /**
24712
- * ```js
24713
- * import { PostRepository } from '@amityco/ts-sdk'
24714
- * const success = await PostRepository.softDeletePost('foobar')
24715
- * ```
24716
- *
24717
- * Soft deletes a {@link Amity.Post}
24718
- *
24719
- * @param postId The {@link Amity.Post} ID to soft delete
24720
- * @return A success boolean if the {@link Amity.Post} was deleted
24721
- *
24722
- * @category Post API
24723
- * @async
24724
- */
24725
- const softDeletePost = async (postId) => {
24726
- const client = getActiveClient();
24727
- client.log('post/softDeletePost', postId);
24728
- const softDeleted = await deletePost(postId, false);
24729
- return LinkedObject.post(softDeleted);
24730
- };
24731
- /* end_public_function */
24732
-
24733
- /* begin_public_function
24734
- id: post.hard_delete
24735
- */
24736
- /**
24737
- * ```js
24738
- * import { hardDeletePost } from '@amityco/ts-sdk'
24739
- * const success = await hardDeletePost('foobar')
24740
- * ```
24741
- *
24742
- * Hard deletes a {@link Amity.Post}
24743
- *
24744
- * @param postId The {@link Amity.Post} ID to be hard delete
24745
- * @return A success boolean if the {@link Amity.Post} was deleted
24746
- *
24747
- * @category Post API
24748
- * @async
24749
- */
24750
- const hardDeletePost = async (postId) => {
24751
- const client = getActiveClient();
24752
- client.log('post/hardDeletePost', postId);
24753
- const hardDeleted = await deletePost(postId, true);
24754
- return LinkedObject.post(hardDeleted);
24755
- };
24756
- /* end_public_function */
24757
-
24758
- /* begin_public_function
24759
- id: post.approve
24760
- */
24761
- /**
24762
- * ```js
24763
- * import { approvePost } from '@amityco/ts-sdk'
24764
- *
24765
- * const { data: post } = await approvePost('postId')
24766
- * ```
24767
- *
24768
- * Approves a {@link Amity.Post}
24769
- *
24770
- * @param postId The {@link Amity.Post} ID to be approved
24771
- * @return A {@link Amity.Post} that was approved
24772
- *
24773
- * @category Post API
24774
- * @async
24775
- */
24776
- const approvePost = async (postId) => {
24777
- const client = getActiveClient();
24778
- client.log('post/approvePost', postId);
24779
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/approve`);
24780
- fireEvent('post.approved', payload);
24781
- // fire virtual event for community update
24782
- if (payload.posts[0].targetType === 'community') {
24783
- fireEvent('community.updated', payload);
24784
- }
24785
- const data = prepareMembershipPayload(payload, 'communityUsers');
24786
- const cachedAt = client.cache && Date.now();
24787
- if (client.cache)
24788
- ingestInCache(data, { cachedAt });
24789
- return {
24790
- data: LinkedObject.post(data.posts.find(post => post.postId === postId)),
24791
- cachedAt,
24792
- };
24793
- };
24794
- /* end_public_function */
24795
-
24796
- /* begin_public_function
24797
- id: post.decline
24798
- */
24799
- /**
24800
- * ```js
24801
- * import { declinePost } from '@amityco/ts-sdk'
24802
- *
24803
- * const {data: post} = await declinePost('postId')
24804
- * ```
24805
- *
24806
- * Declines a {@link Amity.Post}
24807
- *
24808
- * @param postId The {@link Amity.Post} ID to be declined
24809
- * @return A {@link Amity.Post} that was declined
24810
- *
24811
- * @category Post API
24812
- * @async
24813
- */
24814
- const declinePost = async (postId) => {
24815
- const client = getActiveClient();
24816
- client.log('post/declinePost', postId);
24817
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/decline`);
24818
- // fire virtual event
24819
- if (payload.posts[0].targetType === 'community') {
24820
- fireEvent('community.updated', payload);
24527
+ *
24528
+ * @category Comments Live Collection
24529
+ */
24530
+ const getComments = (params, callback, config) => {
24531
+ const { log, cache } = getActiveClient();
24532
+ if (!cache) {
24533
+ console.log('For using Live Collection feature you need to enable Cache!');
24821
24534
  }
24822
- fireEvent('post.declined', payload);
24823
- const data = prepareMembershipPayload(payload, 'communityUsers');
24824
- const cachedAt = client.cache && Date.now();
24825
- if (client.cache)
24826
- ingestInCache(data, { cachedAt });
24827
- return {
24828
- data: LinkedObject.post(payload.posts.find(post => post.postId === postId)),
24829
- cachedAt,
24535
+ const timestamp = Date.now();
24536
+ log(`getComments(tmpid: ${timestamp}) > listen`);
24537
+ const commentsLiveCollection = new CommentLiveCollectionController(params, callback);
24538
+ const disposers = commentsLiveCollection.startSubscription();
24539
+ const cacheKey = commentsLiveCollection.getCacheKey();
24540
+ disposers.push(() => dropFromCache(cacheKey));
24541
+ return () => {
24542
+ log(`getComments(tmpid: ${timestamp}) > dispose`);
24543
+ disposers.forEach(fn => fn());
24830
24544
  };
24831
24545
  };
24832
24546
  /* end_public_function */
24833
24547
 
24834
- /* begin_public_function
24835
- id: post.flag
24836
- */
24548
+ var index$9 = /*#__PURE__*/Object.freeze({
24549
+ __proto__: null,
24550
+ getCommentByIds: getCommentByIds,
24551
+ createComment: createComment,
24552
+ updateComment: updateComment,
24553
+ deleteComment: deleteComment,
24554
+ softDeleteComment: softDeleteComment,
24555
+ hardDeleteComment: hardDeleteComment,
24556
+ flagComment: flagComment,
24557
+ unflagComment: unflagComment,
24558
+ isCommentFlaggedByMe: isCommentFlaggedByMe,
24559
+ onCommentCreated: onCommentCreated,
24560
+ onCommentUpdated: onCommentUpdated,
24561
+ onCommentDeleted: onCommentDeleted,
24562
+ onCommentFlagged: onCommentFlagged,
24563
+ onCommentUnflagged: onCommentUnflagged,
24564
+ onCommentReactionAdded: onCommentReactionAdded,
24565
+ onCommentReactionRemoved: onCommentReactionRemoved,
24566
+ getComment: getComment,
24567
+ getComments: getComments
24568
+ });
24569
+
24837
24570
  /**
24838
24571
  * ```js
24839
- * import { PostRepository } from '@amityco/ts-sdk'
24840
- * const flagged = await PostRepository.flagPost(postId, reason)
24572
+ * import { onPostUpdatedLocal } from '@amityco/ts-sdk'
24573
+ * const dispose = onPostUpdatedLocal(post => {
24574
+ * // ...
24575
+ * })
24841
24576
  * ```
24842
24577
  *
24843
- * @param postId of the post to flag
24844
- * @param reason the reason to flag the post
24845
- * @returns a boolean
24578
+ * Fired when a {@link Amity.InternalPost} has been updated
24846
24579
  *
24847
- * @category Post API
24848
- * @async
24849
- * */
24850
- const flagPost = async (postId, reason) => {
24851
- const client = getActiveClient();
24852
- client.log('post/flagPost', postId);
24853
- const isPredefinedReason = reason &&
24854
- Object.entries(exports.ContentFlagReasonEnum).some(([key, value]) => key !== exports.ContentFlagReasonEnum.Others && value === reason);
24855
- const body = {
24856
- reason: reason && isPredefinedReason ? reason : exports.ContentFlagReasonEnum.Others,
24857
- detail: reason && !isPredefinedReason ? reason : '',
24858
- };
24859
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/flag`, body);
24860
- if (client.cache) {
24861
- ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
24862
- }
24863
- fireEvent('post.flagged', payload);
24864
- return !!payload;
24865
- };
24866
- /* end_public_function */
24580
+ * @param callback The function to call when the event was fired
24581
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
24582
+ *
24583
+ * @category Post Events
24584
+ */
24585
+ const onPostUpdatedLocal = (callback) => createLocalPostEventSubscriber('local.post.updated', callback);
24867
24586
 
24868
- /* begin_public_function
24869
- id: post.unflag
24870
- */
24871
24587
  /**
24872
24588
  * ```js
24873
- * import { PostRepository } from '@amityco/ts-sdk'
24874
- * const unflagged = await PostRepository.unflagPost(postId)
24589
+ * import { onLocalPostReactionAdded } from '@amityco/ts-sdk'
24590
+ * const dispose = onPostReactionAdded(post => {
24591
+ * // ...
24592
+ * })
24875
24593
  * ```
24876
24594
  *
24877
- * @param postId of the post to unflag
24878
- * @returns the unflag post result
24595
+ * Fired when a {@link Amity.InternalPost} has been reacted
24879
24596
  *
24880
- * @category Post API
24881
- * @async
24882
- * */
24883
- const unflagPost = async (postId) => {
24597
+ * @param callback The function to call when the event was fired
24598
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
24599
+ *
24600
+ * @category Post Events
24601
+ */
24602
+ const onLocalPostReactionAdded = (callback) => {
24884
24603
  const client = getActiveClient();
24885
- client.log('post/unflagPost', postId);
24886
- const { data: payload } = await client.http.delete(`/api/v3/posts/${encodeURIComponent(postId)}/unflag`);
24887
- if (client.cache) {
24888
- ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
24889
- }
24890
- fireEvent('post.unflagged', payload);
24891
- return !!payload;
24604
+ const filter = ({ post }) => {
24605
+ if (!client.cache) {
24606
+ callback(post);
24607
+ }
24608
+ else {
24609
+ upsertInCache(['post', 'get', post.postId], post);
24610
+ callback(post);
24611
+ }
24612
+ };
24613
+ return createEventSubscriber(client, 'local.post.addReaction', 'local.post.addReaction', filter);
24892
24614
  };
24893
- /* end_public_function */
24894
24615
 
24895
- /* begin_public_function
24896
- id: post.check_flag_by_me
24897
- */
24898
24616
  /**
24899
24617
  * ```js
24900
- * import { PostRepository } from '@amityco/ts-sdk'
24901
- * const isReported = await PostRepository.isPostFlaggedByMe('post', postId)
24618
+ * import { onLocalPostReactionRemoved } from '@amityco/ts-sdk'
24619
+ * const dispose = onPostReactionRemoved(post => {
24620
+ * // ...
24621
+ * })
24902
24622
  * ```
24903
24623
  *
24904
- * @param postId of the post to check if flagged by current user
24905
- * @returns `true` if the post is flagged by me, `false` if doesn't.
24624
+ * Fired when a {@link Amity.InternalPost} has been reacted
24906
24625
  *
24907
- * @category Post API
24908
- * @async
24909
- * */
24910
- const isPostFlaggedByMe = async (postId) => {
24626
+ * @param callback The function to call when the event was fired
24627
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
24628
+ *
24629
+ * @category Post Events
24630
+ */
24631
+ const onLocalPostReactionRemoved = (callback) => {
24911
24632
  const client = getActiveClient();
24912
- client.log('post/isPostFlaggedByMe', postId);
24913
- const { data: { result }, } = await client.http.get(`/api/v3/posts/${postId}/isflagbyme`);
24914
- return result;
24633
+ const filter = ({ post }) => {
24634
+ if (!client.cache) {
24635
+ callback(post);
24636
+ }
24637
+ else {
24638
+ upsertInCache(['post', 'get', post.postId], post);
24639
+ callback(post);
24640
+ }
24641
+ };
24642
+ return createEventSubscriber(client, 'local.post.removeReaction', 'local.post.removeReaction', filter);
24915
24643
  };
24916
- /* end_public_function */
24917
24644
 
24918
- /* begin_public_function
24919
- id: post.create.clip_post
24920
- */
24921
24645
  /**
24922
24646
  * ```js
24923
- * import { PostRepository } from '@amityco/ts-sdk'
24924
- * const created = await PostRepository.createClipPost({
24925
- * targetType: 'user',
24926
- * targetId: 'foobar',
24927
- * dataType: 'clip',
24928
- * data: { text: 'hello world' },
24929
- * attachments: [{ type: 'clip', fileId: 'fileId123', displayMode: 'fill', isMuted: false }]
24930
- * }))
24647
+ * import { onLocalPostDeleted } from '@amityco/ts-sdk'
24648
+ * const dispose = onLocalPostDeleted(post => {
24649
+ * // ...
24650
+ * })
24931
24651
  * ```
24932
24652
  *
24933
- * Creates an {@link Amity.Post}
24653
+ * Fired when a {@link Amity.InternalPost} has been deleted
24934
24654
  *
24935
- * @param bundle The data necessary to create a new {@link Amity.Post}
24936
- * @returns The newly created {@link Amity.Post}
24655
+ * @param callback The function to call when the event was fired
24656
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
24937
24657
  *
24938
- * @category Post API
24939
- * @async
24658
+ * @category Post Events
24940
24659
  */
24941
- const createClipPost = async (bundle) => {
24942
- const client = getActiveClient();
24943
- client.log('post/createPost', bundle);
24944
- const { data: payload } = await client.http.post('/api/v4/posts', bundle);
24945
- fireEvent('post.created', payload);
24946
- const data = prepareMembershipPayload(payload, 'communityUsers');
24947
- const cachedAt = client.cache && Date.now();
24948
- if (client.cache)
24949
- ingestInCache(data, { cachedAt });
24950
- const { posts } = data;
24951
- return {
24952
- data: LinkedObject.post(posts[0]),
24953
- cachedAt,
24954
- };
24955
- };
24956
- /* end_public_function */
24660
+ const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.post.deleted', callback);
24957
24661
 
24958
24662
  /* begin_public_function
24959
24663
  id: post.get
@@ -24977,7 +24681,7 @@ const createClipPost = async (bundle) => {
24977
24681
  *
24978
24682
  * @category Post Live Object
24979
24683
  */
24980
- const getPost = (postId, callback) => {
24684
+ const getPost$1 = (postId, callback) => {
24981
24685
  const responder = (snapshot) => {
24982
24686
  const { data } = snapshot;
24983
24687
  callback(Object.assign(Object.assign({}, snapshot), { data: data ? LinkedObject.post(snapshot.data) : data }));
@@ -25066,6 +24770,19 @@ class PostPaginationController extends PaginationController {
25066
24770
  }
25067
24771
  }
25068
24772
 
24773
+ var EnumPostActions;
24774
+ (function (EnumPostActions) {
24775
+ EnumPostActions["OnPostCreated"] = "onPostCreated";
24776
+ EnumPostActions["OnPostUpdated"] = "onPostUpdated";
24777
+ EnumPostActions["OnPostDeleted"] = "onPostDeleted";
24778
+ EnumPostActions["OnPostFlagged"] = "onPostFlagged";
24779
+ EnumPostActions["OnPostUnflagged"] = "onPostUnflagged";
24780
+ EnumPostActions["OnPostReactionAdded"] = "onPostReactionAdded";
24781
+ EnumPostActions["OnPostReactionRemoved"] = "onPostReactionRemoved";
24782
+ EnumPostActions["OnPostApproved"] = "onPostApproved";
24783
+ EnumPostActions["OnPostDeclined"] = "onPostDeclined";
24784
+ })(EnumPostActions || (EnumPostActions = {}));
24785
+
25069
24786
  class PostQueryStreamController extends QueryStreamController {
25070
24787
  constructor(query, cacheKey, notifyChange, preparePayload) {
25071
24788
  super(query, cacheKey);
@@ -25131,6 +24848,47 @@ class PostQueryStreamController extends QueryStreamController {
25131
24848
  }
25132
24849
  }
25133
24850
 
24851
+ const getPost = async (postId) => {
24852
+ const client = getActiveClient();
24853
+ client.log('post/getPost', postId);
24854
+ isInTombstone('post', postId);
24855
+ let payload;
24856
+ try {
24857
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
24858
+ const response = await client.http.get(`/api/v3/posts/${encodeURIComponent(postId)}`);
24859
+ payload = response.data;
24860
+ }
24861
+ catch (error) {
24862
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
24863
+ pushToTombstone('post', postId);
24864
+ }
24865
+ throw error;
24866
+ }
24867
+ const data = prepareMembershipPayload(payload, 'communityUsers');
24868
+ const cachedAt = client.cache && Date.now();
24869
+ if (client.cache)
24870
+ ingestInCache(data, { cachedAt });
24871
+ const { posts } = data;
24872
+ const result = posts.find(post => post.postId === postId);
24873
+ return {
24874
+ data: result,
24875
+ cachedAt,
24876
+ };
24877
+ };
24878
+ getPost.locally = (postId) => {
24879
+ const client = getActiveClient();
24880
+ client.log('post/getPost.locally', postId);
24881
+ if (!client.cache)
24882
+ return;
24883
+ const cached = pullFromCache(['post', 'get', postId]);
24884
+ if (!cached)
24885
+ return;
24886
+ return {
24887
+ data: cached.data,
24888
+ cachedAt: cached.cachedAt,
24889
+ };
24890
+ };
24891
+
25134
24892
  class PostLiveCollectionController extends LiveCollectionController {
25135
24893
  constructor(query, callback) {
25136
24894
  const queryStreamId = hash__default["default"](query);
@@ -25180,7 +24938,7 @@ class PostLiveCollectionController extends LiveCollectionController {
25180
24938
  const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25181
24939
  if (!currentCollection || currentCollection.data.includes(comment.referenceId))
25182
24940
  return;
25183
- await getPost$1(comment.referenceId);
24941
+ await getPost(comment.referenceId);
25184
24942
  callback(comment);
25185
24943
  });
25186
24944
  }, 'referenceId', 'post'),
@@ -25193,7 +24951,7 @@ class PostLiveCollectionController extends LiveCollectionController {
25193
24951
  const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
25194
24952
  if (!currentCollection || currentCollection.data.includes(comment.referenceId))
25195
24953
  return;
25196
- await getPost$1(comment.referenceId);
24954
+ await getPost(comment.referenceId);
25197
24955
  callback(comment);
25198
24956
  });
25199
24957
  }, 'referenceId', 'post'),
@@ -25819,7 +25577,7 @@ var index$8 = /*#__PURE__*/Object.freeze({
25819
25577
  onPostUnflagged: onPostUnflagged,
25820
25578
  onPostReactionAdded: onPostReactionAdded,
25821
25579
  onPostReactionRemoved: onPostReactionRemoved,
25822
- getPost: getPost,
25580
+ getPost: getPost$1,
25823
25581
  getPosts: getPosts,
25824
25582
  getPinnedPosts: getPinnedPosts,
25825
25583
  getGlobalPinnedPosts: getGlobalPinnedPosts,
@@ -26188,12 +25946,9 @@ const onStreamViewerUnbanned = (callback) => {
26188
25946
  const filter = async (payloads) => {
26189
25947
  var _a;
26190
25948
  // Get new stream object to restore stream watcherUrl in cache
26191
- await Promise.all(payloads.map(({ streamId }) => getStream(streamId)));
26192
- const stream = (_a = pullFromCache([
26193
- 'stream',
26194
- 'get',
26195
- payloads[0].streamId,
26196
- ])) === null || _a === void 0 ? void 0 : _a.data;
25949
+ const { list } = payloads;
25950
+ await Promise.all(list.map(({ streamId }) => getStream(streamId)));
25951
+ const stream = (_a = pullFromCache(['stream', 'get', list[0].streamId])) === null || _a === void 0 ? void 0 : _a.data;
26197
25952
  if (!stream)
26198
25953
  return;
26199
25954
  callback(stream);
@@ -29025,13 +28780,13 @@ exports.AdRepository = index$3;
29025
28780
  exports.CategoryRepository = index$b;
29026
28781
  exports.ChannelRepository = index$f;
29027
28782
  exports.Client = index$o;
29028
- exports.CommentRepository = index$a;
28783
+ exports.CommentRepository = index$9;
29029
28784
  exports.CommunityPostSettingMaps = CommunityPostSettingMaps;
29030
28785
  exports.CommunityPostSettings = CommunityPostSettings;
29031
28786
  exports.CommunityRepository = index$c;
29032
28787
  exports.ContentFeedType = ContentFeedType;
29033
28788
  exports.DefaultCommunityPostSetting = DefaultCommunityPostSetting;
29034
- exports.FeedRepository = index$9;
28789
+ exports.FeedRepository = index$a;
29035
28790
  exports.FileRepository = index$l;
29036
28791
  exports.FileType = FileType;
29037
28792
  exports.InvitationRepository = index$1;