@amityco/ts-sdk 7.7.1-1cf499d.0 → 7.7.1-47be9e51.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 (55) hide show
  1. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/domains/feed.d.ts +31 -0
  2. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/domains/feed.d.ts.map +1 -1
  3. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/domains/feed.js +21 -1
  4. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/@types/domains/feed.js.map +1 -1
  5. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/index.d.ts +1 -0
  6. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/index.d.ts.map +1 -1
  7. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/index.js +1 -0
  8. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/index.js.map +1 -1
  9. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/LiveCollectionController.d.ts +14 -0
  10. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/LiveCollectionController.d.ts.map +1 -0
  11. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/LiveCollectionController.js +129 -0
  12. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/LiveCollectionController.js.map +1 -0
  13. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/PaginationController.d.ts +5 -0
  14. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/PaginationController.d.ts.map +1 -0
  15. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/PaginationController.js +15 -0
  16. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/PaginationController.js.map +1 -0
  17. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/QueryStreamController.d.ts +15 -0
  18. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/QueryStreamController.d.ts.map +1 -0
  19. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/QueryStreamController.js +78 -0
  20. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed/QueryStreamController.js.map +1 -0
  21. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed.d.ts +23 -0
  22. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed.d.ts.map +1 -0
  23. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed.js +46 -0
  24. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/getUserFeed.js.map +1 -0
  25. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/index.d.ts +2 -0
  26. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/index.d.ts.map +1 -0
  27. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/index.js +2 -0
  28. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/dist/feedRepository/observers/index.js.map +1 -0
  29. package/.rollup.cache/home/runner/work/AmityTypescriptSDK/AmityTypescriptSDK/packages/sdk/tsconfig.tsbuildinfo +1 -1
  30. package/dist/@types/domains/feed.d.ts +31 -0
  31. package/dist/@types/domains/feed.d.ts.map +1 -1
  32. package/dist/feedRepository/index.d.ts +1 -0
  33. package/dist/feedRepository/index.d.ts.map +1 -1
  34. package/dist/feedRepository/observers/getUserFeed/LiveCollectionController.d.ts +14 -0
  35. package/dist/feedRepository/observers/getUserFeed/LiveCollectionController.d.ts.map +1 -0
  36. package/dist/feedRepository/observers/getUserFeed/PaginationController.d.ts +5 -0
  37. package/dist/feedRepository/observers/getUserFeed/PaginationController.d.ts.map +1 -0
  38. package/dist/feedRepository/observers/getUserFeed/QueryStreamController.d.ts +15 -0
  39. package/dist/feedRepository/observers/getUserFeed/QueryStreamController.d.ts.map +1 -0
  40. package/dist/feedRepository/observers/getUserFeed.d.ts +23 -0
  41. package/dist/feedRepository/observers/getUserFeed.d.ts.map +1 -0
  42. package/dist/feedRepository/observers/index.d.ts +2 -0
  43. package/dist/feedRepository/observers/index.d.ts.map +1 -0
  44. package/dist/index.cjs.js +1296 -1059
  45. package/dist/index.esm.js +1295 -1058
  46. package/dist/index.umd.js +1 -1
  47. package/package.json +1 -1
  48. package/src/@types/domains/feed.ts +43 -0
  49. package/src/feedRepository/index.ts +1 -0
  50. package/src/feedRepository/observers/getUserFeed/LiveCollectionController.ts +192 -0
  51. package/src/feedRepository/observers/getUserFeed/PaginationController.ts +37 -0
  52. package/src/feedRepository/observers/getUserFeed/QueryStreamController.ts +119 -0
  53. package/src/feedRepository/observers/getUserFeed.ts +56 -0
  54. package/src/feedRepository/observers/index.ts +1 -0
  55. package/tsconfig.tsbuildinfo +1 -1
package/dist/index.esm.js CHANGED
@@ -39272,1010 +39272,1035 @@ getCustomRankingGlobalFeed.locally = (query) => {
39272
39272
  : undefined;
39273
39273
  };
39274
39274
 
39275
- var index$a = /*#__PURE__*/Object.freeze({
39276
- __proto__: null,
39277
- queryGlobalFeed: queryGlobalFeed,
39278
- getCustomRankingGlobalFeed: getCustomRankingGlobalFeed
39279
- });
39275
+ class UserFeedPaginationController extends PaginationController {
39276
+ async getRequest(queryParams, token) {
39277
+ const { userId, feedSources, dataTypes, includeDeleted, matchingOnlyParentPost, limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["userId", "feedSources", "dataTypes", "includeDeleted", "matchingOnlyParentPost", "limit"]);
39278
+ const options = token ? { token } : { limit };
39279
+ const { data: queryResponse } = await this.http.get(`/api/v4/user-feeds/${userId}`, {
39280
+ 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) }),
39281
+ });
39282
+ return queryResponse;
39283
+ }
39284
+ }
39285
+
39286
+ var EnumPostActions;
39287
+ (function (EnumPostActions) {
39288
+ EnumPostActions["OnPostCreated"] = "onPostCreated";
39289
+ EnumPostActions["OnPostUpdated"] = "onPostUpdated";
39290
+ EnumPostActions["OnPostDeleted"] = "onPostDeleted";
39291
+ EnumPostActions["OnPostFlagged"] = "onPostFlagged";
39292
+ EnumPostActions["OnPostUnflagged"] = "onPostUnflagged";
39293
+ EnumPostActions["OnPostReactionAdded"] = "onPostReactionAdded";
39294
+ EnumPostActions["OnPostReactionRemoved"] = "onPostReactionRemoved";
39295
+ EnumPostActions["OnPostApproved"] = "onPostApproved";
39296
+ EnumPostActions["OnPostDeclined"] = "onPostDeclined";
39297
+ })(EnumPostActions || (EnumPostActions = {}));
39298
+
39299
+ class UserFeedQueryStreamController extends QueryStreamController {
39300
+ constructor(query, cacheKey, notifyChange, preparePayload) {
39301
+ super(query, cacheKey);
39302
+ this.notifyChange = notifyChange;
39303
+ this.preparePayload = preparePayload;
39304
+ }
39305
+ async saveToMainDB(response) {
39306
+ const processedPayload = await this.preparePayload(response);
39307
+ const client = getActiveClient();
39308
+ const cachedAt = client.cache && Date.now();
39309
+ if (client.cache) {
39310
+ ingestInCache(processedPayload, { cachedAt });
39311
+ }
39312
+ }
39313
+ appendToQueryStream(response, direction, refresh = false) {
39314
+ var _a, _b;
39315
+ if (refresh) {
39316
+ pushToCache(this.cacheKey, {
39317
+ data: response.posts.map(getResolver('post')),
39318
+ });
39319
+ }
39320
+ else {
39321
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39322
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
39323
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...posts, ...response.posts.map(getResolver('post'))])] }));
39324
+ }
39325
+ }
39326
+ reactor(action) {
39327
+ return (post) => {
39328
+ var _a, _b;
39329
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39330
+ if (!collection)
39331
+ return;
39332
+ // if the collection is parent post collection and
39333
+ // post is not included in the collection or post is child post
39334
+ if ((!this.query.dataTypes || this.query.dataTypes.length === 0) &&
39335
+ !collection.data.includes(post.parentPostId ? post.parentPostId : post.postId))
39336
+ return;
39337
+ if (action === EnumPostActions.OnPostDeleted) {
39338
+ collection.data = collection.data.filter(postId => postId !== post.postId);
39339
+ }
39340
+ if (post.parentPostId && post.isDeleted) {
39341
+ const parentPost = (_b = pullFromCache([
39342
+ 'post',
39343
+ 'get',
39344
+ post.parentPostId,
39345
+ ])) === null || _b === void 0 ? void 0 : _b.data;
39346
+ if (!parentPost)
39347
+ return;
39348
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
39349
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
39350
+ }
39351
+ if (action === EnumPostActions.OnPostDeclined) {
39352
+ collection.data = collection.data.filter(postId => postId !== post.postId);
39353
+ }
39354
+ if (action === EnumPostActions.OnPostCreated || action === EnumPostActions.OnPostApproved) {
39355
+ if (this.query.dataTypes &&
39356
+ this.query.dataTypes.length > 0 &&
39357
+ !this.query.dataTypes.includes(post.dataType)) {
39358
+ return;
39359
+ }
39360
+ collection.data = [...new Set([post.postId, ...collection.data])];
39361
+ }
39362
+ pushToCache(this.cacheKey, collection);
39363
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
39364
+ };
39365
+ }
39366
+ subscribeRTE(createSubscriber) {
39367
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
39368
+ }
39369
+ }
39280
39370
 
39281
39371
  /* begin_public_function
39282
- id: post.get_by_ids
39372
+ id: comment.get_by_ids
39283
39373
  */
39284
39374
  /**
39285
39375
  * ```js
39286
- * import { getPostByIds } from '@amityco/ts-sdk'
39287
- * const { data: posts } = await getPostByIds(['foo', 'bar'])
39376
+ * import { CommentRepository } from '@amityco/ts-sdk'
39377
+ * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
39288
39378
  * ```
39289
39379
  *
39290
- * Fetches a collection of {@link Amity.Post} objects
39380
+ * Fetches a collection of {@link Amity.Comment} objects
39291
39381
  *
39292
- * @param postIds the IDs of the {@link Amity.Post} to fetch
39293
- * @returns the associated collection of {@link Amity.Post} objects
39382
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
39383
+ * @returns the associated collection of {@link Amity.Comment} objects
39294
39384
  *
39295
- * @category Post API
39385
+ * @category Comment API
39296
39386
  * @async
39297
39387
  */
39298
- const getPostByIds = async (postIds) => {
39388
+ const getCommentByIds = async (commentIds) => {
39299
39389
  const client = getActiveClient();
39300
- client.log('post/getPostByIds', postIds);
39301
- const encodedPostIds = postIds.map(postId => encodeURIComponent(postId));
39302
- let payload;
39390
+ client.log('comment/getCommentByIds', commentIds);
39391
+ const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
39392
+ let data;
39303
39393
  try {
39304
39394
  // API-FIX: endpoint should not be /list, parameters should be querystring.
39305
- const response = await client.http.get(`/api/v3/posts/list`, {
39306
- params: { postIds: encodedPostIds },
39395
+ const response = await client.http.get(`/api/v3/comments/list`, {
39396
+ params: { commentIds: encodedCommentIds },
39307
39397
  });
39308
- payload = response.data;
39398
+ data = response.data;
39309
39399
  }
39310
39400
  catch (error) {
39311
- postIds.forEach(postId => {
39401
+ commentIds.forEach(commentId => {
39312
39402
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39313
- pushToTombstone('post', postId);
39403
+ pushToTombstone('comment', commentId);
39314
39404
  }
39315
39405
  });
39316
39406
  throw error;
39317
39407
  }
39318
- const data = prepareMembershipPayload(payload, 'communityUsers');
39319
39408
  const cachedAt = client.cache && Date.now();
39320
39409
  if (client.cache)
39321
39410
  ingestInCache(data, { cachedAt });
39322
39411
  return {
39323
- data: data.posts.map(LinkedObject.post),
39412
+ data: data.comments.map(comment => LinkedObject.comment(comment)),
39324
39413
  cachedAt,
39325
39414
  };
39326
39415
  };
39327
39416
  /* end_public_function */
39328
39417
  /**
39329
39418
  * ```js
39330
- * import { getPostByIds } from '@amityco/ts-sdk'
39331
- * const { data: posts } = getPostByIds.locally(['foo', 'bar'])
39419
+ * import { getCommentByIds } from '@amityco/ts-sdk'
39420
+ * const comments = getCommentByIds.locally(['foo', 'bar'])
39332
39421
  * ```
39333
39422
  *
39334
- * Fetches a collection of {@link Amity.Post} objects from cache
39423
+ * Fetches a collection of {@link Amity.Comment} objects from cache
39335
39424
  *
39336
- * @param postIds the IDs of the {@link Amity.Post} to fetch
39337
- * @returns the associated collection of {@link Amity.Post} objects
39425
+ * @param commentIds the IDs of the {@link Amity.Comment} to fetch
39426
+ * @returns the associated collection of {@link Amity.Comment} objects
39338
39427
  *
39339
- * @category Post API
39428
+ * @category Comment API
39340
39429
  */
39341
- getPostByIds.locally = (postIds) => {
39430
+ getCommentByIds.locally = (commentIds) => {
39342
39431
  var _a;
39343
39432
  const client = getActiveClient();
39344
- client.log('post/getPostByIds.locally', postIds);
39433
+ client.log('comment/getCommentByIds.locally', commentIds);
39345
39434
  if (!client.cache)
39346
39435
  return;
39347
- const cached = postIds
39348
- .map(postId => pullFromCache(['post', 'get', postId]))
39436
+ const cached = commentIds
39437
+ .map(commentId => pullFromCache(['comment', 'get', commentId]))
39349
39438
  .filter(Boolean);
39350
- const posts = cached.map(({ data }) => data);
39439
+ const comments = cached.map(({ data }) => data);
39351
39440
  const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
39352
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < postIds.length)
39441
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < commentIds.length)
39353
39442
  return;
39354
39443
  return {
39355
- data: posts.map(LinkedObject.post),
39444
+ data: comments.map(comment => LinkedObject.comment(comment)),
39356
39445
  cachedAt: oldest.cachedAt,
39357
39446
  };
39358
39447
  };
39359
39448
 
39360
39449
  /* begin_public_function
39361
- 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
39450
+ id: comment.create
39362
39451
  */
39363
39452
  /**
39364
39453
  * ```js
39365
- * import { PostRepository } from '@amityco/ts-sdk'
39366
- * const created = await PostRepository.createPost({
39367
- * targetType: 'user',
39368
- * targetId: 'foobar',
39369
- * data: { text: 'hello world' }
39370
- * }))
39454
+ * import { CommentRepository } from '@amityco/ts-sdk'
39455
+ * const newComment = await CommentRepository.createComment(bundle)
39371
39456
  * ```
39372
39457
  *
39373
- * Creates an {@link Amity.Post}
39458
+ * Creates an {@link Amity.Comment}
39374
39459
  *
39375
- * @param bundle The data necessary to create a new {@link Amity.Post}
39376
- * @returns The newly created {@link Amity.Post}
39460
+ * @param bundle The data necessary to create a new {@link Amity.Comment}
39461
+ * @returns The newly created {@link Amity.Comment}
39377
39462
  *
39378
- * @category Post API
39463
+ * @category Comment API
39379
39464
  * @async
39380
39465
  */
39381
- const createPost = async (bundle) => {
39466
+ const createComment = async (bundle) => {
39467
+ var _a;
39382
39468
  const client = getActiveClient();
39383
- client.log('post/createPost', bundle);
39384
- if (!bundle.dataType || ['text', 'image', 'file', 'video'].includes(bundle.dataType)) {
39385
- // eslint-disable-next-line no-param-reassign
39386
- delete bundle.dataType;
39387
- }
39388
- const { data: payload } = await client.http.post('/api/v4/posts', bundle);
39389
- fireEvent('post.created', payload);
39390
- const data = preparePostPayload(payload);
39469
+ client.log('comment/createComment', bundle);
39470
+ const { data } = await client.http.post('/api/v3/comments', bundle);
39471
+ const { comments } = data;
39472
+ // BE always returns an array of comments If it got record 0 from BE it might have a problem on creation logic
39473
+ if (comments.length === 0)
39474
+ throw new Error('Comment not created');
39391
39475
  const cachedAt = client.cache && Date.now();
39392
39476
  if (client.cache)
39393
39477
  ingestInCache(data, { cachedAt });
39394
- const { posts } = data;
39478
+ if (['post', 'content'].includes(bundle.referenceType)) {
39479
+ const post = (_a = pullFromCache(['post', 'get', bundle.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
39480
+ if (post) {
39481
+ post.commentsCount += 1;
39482
+ fireEvent('local.post.updated', {
39483
+ posts: [post],
39484
+ categories: [],
39485
+ comments: [],
39486
+ communities: [],
39487
+ communityUsers: data.communityUsers,
39488
+ feeds: [],
39489
+ files: data.files,
39490
+ postChildren: [],
39491
+ users: data.users,
39492
+ videoStreamings: [],
39493
+ });
39494
+ }
39495
+ }
39496
+ else if (bundle.referenceType === 'story') {
39497
+ const storyIndex = pullFromCache([
39498
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39499
+ bundle.referenceId,
39500
+ ]);
39501
+ if (storyIndex === null || storyIndex === void 0 ? void 0 : storyIndex.data) {
39502
+ const cacheStory = pullFromCache([
39503
+ "story" /* STORY_KEY_CACHE.STORY */,
39504
+ 'get',
39505
+ storyIndex.data,
39506
+ ]);
39507
+ if (cacheStory === null || cacheStory === void 0 ? void 0 : cacheStory.data) {
39508
+ fireEvent('story.updated', {
39509
+ stories: [
39510
+ Object.assign(Object.assign({}, cacheStory.data), { commentsCount: cacheStory.data.commentsCount + 1, comments: [...new Set([...cacheStory.data.comments, comments[0].commentId])] }),
39511
+ ],
39512
+ categories: [],
39513
+ comments,
39514
+ communities: [],
39515
+ communityUsers: data.communityUsers,
39516
+ files: data.files,
39517
+ users: data.users,
39518
+ });
39519
+ }
39520
+ }
39521
+ }
39522
+ fireEvent('local.comment.created', data);
39395
39523
  return {
39396
- data: LinkedObject.post(posts[0]),
39524
+ data: LinkedObject.comment(comments[0]),
39397
39525
  cachedAt,
39398
39526
  };
39399
39527
  };
39400
39528
  /* end_public_function */
39401
39529
 
39402
39530
  /* begin_public_function
39403
- id: post.edit, post.edit.custom_post
39531
+ id: comment.update_comment
39404
39532
  */
39405
39533
  /**
39406
39534
  * ```js
39407
- * import { PostRepository } from '@amityco/ts-sdk'
39408
- * const updated = await PostRepository.editPost(postId, {
39535
+ * import { CommentRepository } from '@amityco/ts-sdk'
39536
+ * const updated = await CommentRepository.updateComment(commentId, {
39409
39537
  * data: { text: 'hello world' }
39410
39538
  * })
39411
39539
  * ```
39412
39540
  *
39413
- * Updates an {@link Amity.Post}
39541
+ * Updates an {@link Amity.Comment}
39414
39542
  *
39415
- * @param postId The ID of the {@link Amity.Post} to edit
39543
+ * @param commentId The ID of the {@link Amity.Comment} to edit
39416
39544
  * @param patch The patch data to apply
39417
- * @returns the updated {@link Amity.Post} object
39545
+ * @returns the updated {@link Amity.Comment} object
39418
39546
  *
39419
- * @category Post API
39547
+ * @category Comment API
39420
39548
  * @async
39421
39549
  */
39422
- const editPost = async (postId, patch) => {
39550
+ const updateComment = async (commentId, patch) => {
39423
39551
  const client = getActiveClient();
39424
- client.log('user/editPost', patch);
39425
- const { data: payload } = await client.http.put(`/api/v4/posts/${encodeURIComponent(postId)}`, patch);
39426
- const data = prepareMembershipPayload(payload, 'communityUsers');
39552
+ client.log('user/updateComment', patch);
39553
+ const { data } = await client.http.put(`/api/v3/comments/${encodeURIComponent(commentId)}`, patch);
39427
39554
  const cachedAt = client.cache && Date.now();
39428
39555
  if (client.cache)
39429
39556
  ingestInCache(data, { cachedAt });
39430
- fireEvent('local.post.updated', data);
39431
- const { posts } = data;
39557
+ fireEvent('comment.updated', data);
39558
+ const { comments } = data;
39432
39559
  return {
39433
- data: LinkedObject.post(posts.find(post => post.postId === postId)),
39560
+ data: LinkedObject.comment(comments.find(comment => comment.commentId === commentId)),
39434
39561
  cachedAt,
39435
39562
  };
39436
39563
  };
39437
39564
  /* end_public_function */
39438
39565
 
39566
+ // Due to we have optimistic logic, we will use referenceId as a id in SDK instead of storyId
39567
+ const applyMissingField = (rawData, isCreated = false) => {
39568
+ const { storyId, referenceId } = rawData;
39569
+ if (!isCreated) {
39570
+ if (referenceId)
39571
+ return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */ });
39572
+ }
39573
+ return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */, referenceId: storyId });
39574
+ };
39575
+ const convertRawStoryToInternal = (data, isCreated = false) => {
39576
+ const { stories } = data;
39577
+ const storiesData = stories.map(story => applyMissingField(story, isCreated));
39578
+ return Object.assign(Object.assign({}, data), { stories: storiesData });
39579
+ };
39580
+
39581
+ const getStoryByStoryId$1 = async (storyId) => {
39582
+ const client = getActiveClient();
39583
+ client.log('story/getStoryByStoryId', storyId);
39584
+ // Get story referenceId from cache
39585
+ const cacheReferenceId = pullFromCache([
39586
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39587
+ storyId,
39588
+ ]);
39589
+ if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
39590
+ const { data: referenceId } = cacheReferenceId;
39591
+ isInTombstone('story', referenceId);
39592
+ }
39593
+ let data;
39594
+ try {
39595
+ const response = await client.http.get(`/api/v4/stories/${storyId}`);
39596
+ data = convertRawStoryToInternal(response.data);
39597
+ }
39598
+ catch (error) {
39599
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39600
+ pushToTombstone('story', storyId);
39601
+ }
39602
+ throw error;
39603
+ }
39604
+ const cachedAt = client.cache && Date.now();
39605
+ if (client.cache) {
39606
+ ingestInCache(data, { cachedAt });
39607
+ }
39608
+ return {
39609
+ data: data.stories[0],
39610
+ cachedAt,
39611
+ };
39612
+ };
39613
+ getStoryByStoryId$1.locally = (storyId) => {
39614
+ const client = getActiveClient();
39615
+ client.log('story/getStorybyStoryId', storyId);
39616
+ // Get story referenceId from cache
39617
+ const cacheReferenceId = pullFromCache([
39618
+ "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39619
+ storyId,
39620
+ ]);
39621
+ if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
39622
+ const { data: referenceId } = cacheReferenceId;
39623
+ isInTombstone('story', referenceId);
39624
+ }
39625
+ const cachedAt = client.cache && Date.now();
39626
+ const storyCache = pullFromCache(['story', 'get', storyId]);
39627
+ if (!storyCache)
39628
+ return;
39629
+ return {
39630
+ data: storyCache.data,
39631
+ cachedAt,
39632
+ };
39633
+ };
39634
+
39635
+ /* begin_public_function
39636
+ id: comment.soft_delete, comment.hard_delete
39637
+ */
39439
39638
  /**
39440
39639
  * ```js
39441
- * import { deletePost } from '@amityco/ts-sdk'
39442
- * const success = await deletePost('foobar')
39640
+ * import { CommentRepository } from '@amityco/ts-sdk'
39641
+ * const success = await CommentRepository.deleteComment('foobar')
39443
39642
  * ```
39444
39643
  *
39445
- * Deletes a {@link Amity.Post}
39644
+ * Deletes a {@link Amity.Comment}
39446
39645
  *
39447
- * @param postId The {@link Amity.Post} ID to delete
39448
- * @return A success boolean if the {@link Amity.Post} was deleted
39646
+ * @param commentId The {@link Amity.Comment} ID to delete
39647
+ * @return A success boolean if the {@link Amity.Comment} was deleted
39449
39648
  *
39450
- * @private
39649
+ * @category Comment API
39451
39650
  * @async
39452
39651
  */
39453
- const deletePost = async (postId, permanent = false) => {
39652
+ const deleteComment = async (commentId, permanent = false) => {
39454
39653
  var _a;
39455
39654
  const client = getActiveClient();
39456
- const post = await getPost$2(postId);
39457
- await client.http.delete(`/api/v4/posts/${encodeURIComponent(postId)}`, {
39655
+ const comment = await getComment$2(commentId);
39656
+ // API-FIX: This endpoint has not been implemented yet.
39657
+ await client.http.delete(`/api/v4/comments/${encodeURIComponent(commentId)}`, {
39458
39658
  params: {
39459
- postId,
39659
+ commentId,
39460
39660
  permanent,
39461
39661
  },
39462
39662
  });
39463
- // there is currently a limitation which doesn't allow us to fire event to tell that community
39464
- // has been updated. reason is that, when the object is deleted, we don't have its `communityId`
39465
- // and so we cannot refetch the community or advertise on events. hopefully this should be solved
39466
- // later when realtime events covers that for us.
39467
- if (post.data.targetType === 'community') {
39468
- const community = await getCommunity$1(post.data.targetId);
39469
- const communityUsersCache = (_a = queryCache(['communityUsers', 'get'])) !== null && _a !== void 0 ? _a : [];
39470
- const communityUsers = communityUsersCache
39471
- .filter(({ key }) => {
39472
- // cache key is ['communityUsers', 'get', `${communityId}#`${userId}`}]
39473
- if (key[0] !== 'communityUsers')
39474
- return false;
39475
- if (key[1] !== 'get')
39476
- return false;
39477
- if (typeof key[2] === 'string')
39478
- return key[2].includes(community.data.communityId);
39479
- return false;
39480
- })
39481
- .map(({ data }) => data);
39482
- fireEvent('community.updated', {
39483
- communities: [community.data],
39663
+ // to support hard deletion
39664
+ const deleted = Object.assign(Object.assign({}, comment.data), { isDeleted: true });
39665
+ if (comment.data.referenceType === 'story') {
39666
+ const story = await getStoryByStoryId$1(comment.data.referenceId);
39667
+ fireEvent('local.story.updated', {
39668
+ stories: [story.data],
39484
39669
  categories: [],
39485
- communityUsers,
39486
- feeds: [],
39670
+ comments: [],
39671
+ communities: [],
39672
+ communityUsers: [],
39487
39673
  files: [],
39488
39674
  users: [],
39489
39675
  });
39490
39676
  }
39491
- // to support hard deletion
39492
- const deleted = Object.assign(Object.assign({}, post.data), { isDeleted: true });
39493
- if (permanent) {
39494
- setTimeout(() => {
39495
- pushToTombstone('post', postId);
39496
- }, 0);
39497
- }
39498
39677
  else {
39499
- upsertInCache(['post', 'get', postId], { isDeleted: true });
39678
+ const post = (_a = pullFromCache(['post', 'get', comment.data.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
39679
+ if (post) {
39680
+ let removeCount;
39681
+ if (!deleted.parentId) {
39682
+ // NOTE: delete the parent comment will remove all children comments
39683
+ removeCount = deleted.childrenNumber + 1;
39684
+ }
39685
+ else
39686
+ removeCount = 1;
39687
+ post.commentsCount -= removeCount;
39688
+ fireEvent('local.post.updated', {
39689
+ posts: [post],
39690
+ categories: [],
39691
+ comments: [],
39692
+ communities: [],
39693
+ communityUsers: [],
39694
+ feeds: [],
39695
+ files: [],
39696
+ postChildren: [],
39697
+ users: [],
39698
+ videoStreamings: [],
39699
+ });
39700
+ }
39500
39701
  }
39501
- fireEvent('local.post.deleted', {
39502
- posts: [deleted],
39503
- categories: [],
39504
- comments: [],
39505
- communities: [],
39506
- communityUsers: [],
39507
- feeds: [],
39702
+ fireEvent('local.comment.deleted', {
39703
+ comments: [deleted],
39704
+ commentChildren: [],
39508
39705
  files: [],
39509
- postChildren: [],
39510
39706
  users: [],
39511
- videoStreamings: [],
39707
+ communityUsers: [],
39512
39708
  });
39513
- return LinkedObject.post(deleted);
39709
+ if (permanent) {
39710
+ scheduleTask(() => pushToTombstone('comment', commentId));
39711
+ }
39712
+ else {
39713
+ upsertInCache(['comment', 'get', commentId], { isDeleted: true });
39714
+ }
39715
+ return deleted;
39514
39716
  };
39717
+ /* end_public_function */
39515
39718
 
39516
39719
  /* begin_public_function
39517
- id: post.soft_delete
39720
+ id: comment.soft_delete
39518
39721
  */
39519
39722
  /**
39520
39723
  * ```js
39521
- * import { PostRepository } from '@amityco/ts-sdk'
39522
- * const success = await PostRepository.softDeletePost('foobar')
39724
+ * import { CommentRepository } from '@amityco/ts-sdk'
39725
+ * const success = await CommentRepository.softDeleteComment('foobar')
39523
39726
  * ```
39524
39727
  *
39525
- * Soft deletes a {@link Amity.Post}
39728
+ * Deletes a {@link Amity.Comment}
39526
39729
  *
39527
- * @param postId The {@link Amity.Post} ID to soft delete
39528
- * @return A success boolean if the {@link Amity.Post} was deleted
39730
+ * @param commentId The {@link Amity.Comment} ID to delete
39731
+ * @return A success boolean if the {@link Amity.Comment} was deleted
39529
39732
  *
39530
- * @category Post API
39733
+ * @category Comment API
39531
39734
  * @async
39532
39735
  */
39533
- const softDeletePost = async (postId) => {
39736
+ const softDeleteComment = async (commentId) => {
39534
39737
  const client = getActiveClient();
39535
- client.log('post/softDeletePost', postId);
39536
- const softDeleted = await deletePost(postId, false);
39537
- return LinkedObject.post(softDeleted);
39738
+ client.log('comment/softDeleteComment', commentId);
39739
+ const softDeleted = deleteComment(commentId);
39740
+ return softDeleted;
39538
39741
  };
39539
39742
  /* end_public_function */
39540
39743
 
39541
39744
  /* begin_public_function
39542
- id: post.hard_delete
39745
+ id: comment.hard_delete
39543
39746
  */
39544
39747
  /**
39545
39748
  * ```js
39546
- * import { hardDeletePost } from '@amityco/ts-sdk'
39547
- * const success = await hardDeletePost('foobar')
39749
+ * import { CommentRepository } from '@amityco/ts-sdk'
39750
+ * const success = await CommentRepository.hardDeleteComment('foobar')
39548
39751
  * ```
39549
39752
  *
39550
- * Hard deletes a {@link Amity.Post}
39753
+ * Deletes a {@link Amity.Comment}
39551
39754
  *
39552
- * @param postId The {@link Amity.Post} ID to be hard delete
39553
- * @return A success boolean if the {@link Amity.Post} was deleted
39755
+ * @param commentId The {@link Amity.Comment} ID to delete
39756
+ * @return A success boolean if the {@link Amity.Comment} was deleted
39554
39757
  *
39555
- * @category Post API
39758
+ * @category Comment API
39556
39759
  * @async
39557
39760
  */
39558
- const hardDeletePost = async (postId) => {
39761
+ const hardDeleteComment = async (commentId) => {
39559
39762
  const client = getActiveClient();
39560
- client.log('post/hardDeletePost', postId);
39561
- const hardDeleted = await deletePost(postId, true);
39562
- return LinkedObject.post(hardDeleted);
39763
+ client.log('comment/hardDeleteComment', commentId);
39764
+ const hardDeleted = deleteComment(commentId, true);
39765
+ return hardDeleted;
39563
39766
  };
39564
39767
  /* end_public_function */
39565
39768
 
39566
39769
  /* begin_public_function
39567
- id: post.approve
39770
+ id: comment.flag
39568
39771
  */
39569
39772
  /**
39570
39773
  * ```js
39571
- * import { approvePost } from '@amityco/ts-sdk'
39572
- *
39573
- * const { data: post } = await approvePost('postId')
39774
+ * import { CommentRepository } from '@amityco/ts-sdk'
39775
+ * const flagged = await CommentRepository.flagComment(commentId, reason)
39574
39776
  * ```
39575
39777
  *
39576
- * Approves a {@link Amity.Post}
39577
- *
39578
- * @param postId The {@link Amity.Post} ID to be approved
39579
- * @return A {@link Amity.Post} that was approved
39778
+ * @param commentId The ID of the comment to flag
39779
+ * @param reason the reason to flag the comment
39780
+ * @returns the created report result
39580
39781
  *
39581
- * @category Post API
39782
+ * @category Comment API
39582
39783
  * @async
39583
- */
39584
- const approvePost = async (postId) => {
39784
+ * */
39785
+ const flagComment = async (commentId, reason) => {
39585
39786
  const client = getActiveClient();
39586
- client.log('post/approvePost', postId);
39587
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/approve`);
39588
- fireEvent('post.approved', payload);
39589
- // fire virtual event for community update
39590
- if (payload.posts[0].targetType === 'community') {
39591
- fireEvent('community.updated', payload);
39592
- }
39593
- const data = prepareMembershipPayload(payload, 'communityUsers');
39594
- const cachedAt = client.cache && Date.now();
39595
- if (client.cache)
39596
- ingestInCache(data, { cachedAt });
39597
- return {
39598
- data: LinkedObject.post(data.posts.find(post => post.postId === postId)),
39599
- cachedAt,
39600
- };
39601
- };
39602
- /* end_public_function */
39603
-
39604
- /* begin_public_function
39605
- id: post.decline
39606
- */
39607
- /**
39608
- * ```js
39609
- * import { declinePost } from '@amityco/ts-sdk'
39610
- *
39611
- * const {data: post} = await declinePost('postId')
39612
- * ```
39613
- *
39614
- * Declines a {@link Amity.Post}
39615
- *
39616
- * @param postId The {@link Amity.Post} ID to be declined
39617
- * @return A {@link Amity.Post} that was declined
39618
- *
39619
- * @category Post API
39620
- * @async
39621
- */
39622
- const declinePost = async (postId) => {
39623
- const client = getActiveClient();
39624
- client.log('post/declinePost', postId);
39625
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/decline`);
39626
- // fire virtual event
39627
- if (payload.posts[0].targetType === 'community') {
39628
- fireEvent('community.updated', payload);
39629
- }
39630
- fireEvent('post.declined', payload);
39631
- const data = prepareMembershipPayload(payload, 'communityUsers');
39632
- const cachedAt = client.cache && Date.now();
39633
- if (client.cache)
39634
- ingestInCache(data, { cachedAt });
39635
- return {
39636
- data: LinkedObject.post(payload.posts.find(post => post.postId === postId)),
39637
- cachedAt,
39638
- };
39639
- };
39640
- /* end_public_function */
39641
-
39642
- /* begin_public_function
39643
- id: post.flag
39644
- */
39645
- /**
39646
- * ```js
39647
- * import { PostRepository } from '@amityco/ts-sdk'
39648
- * const flagged = await PostRepository.flagPost(postId, reason)
39649
- * ```
39650
- *
39651
- * @param postId of the post to flag
39652
- * @param reason the reason to flag the post
39653
- * @returns a boolean
39654
- *
39655
- * @category Post API
39656
- * @async
39657
- * */
39658
- const flagPost = async (postId, reason) => {
39659
- const client = getActiveClient();
39660
- client.log('post/flagPost', postId);
39787
+ client.log('comment/flagComment', commentId);
39661
39788
  const isPredefinedReason = reason &&
39662
39789
  Object.entries(ContentFlagReasonEnum).some(([key, value]) => key !== ContentFlagReasonEnum.Others && value === reason);
39663
39790
  const body = {
39664
39791
  reason: reason && isPredefinedReason ? reason : ContentFlagReasonEnum.Others,
39665
39792
  detail: reason && !isPredefinedReason ? reason : '',
39666
39793
  };
39667
- const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/flag`, body);
39794
+ const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/flag`, body);
39668
39795
  if (client.cache) {
39669
- ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
39796
+ ingestInCache(payload);
39670
39797
  }
39671
- fireEvent('post.flagged', payload);
39798
+ fireEvent('comment.flagged', payload);
39672
39799
  return !!payload;
39673
39800
  };
39674
39801
  /* end_public_function */
39675
39802
 
39676
39803
  /* begin_public_function
39677
- id: post.unflag
39804
+ id: comment.unflag
39678
39805
  */
39679
39806
  /**
39680
39807
  * ```js
39681
- * import { PostRepository } from '@amityco/ts-sdk'
39682
- * const unflagged = await PostRepository.unflagPost(postId)
39808
+ * import { CommentRepository } from '@amityco/ts-sdk'
39809
+ * const unflagged = await CommentRepository.unflagComment('commentId')
39683
39810
  * ```
39684
39811
  *
39685
- * @param postId of the post to unflag
39686
- * @returns the unflag post result
39812
+ * @param commentId The ID of comment to unflag
39813
+ * @returns the unflagged result
39687
39814
  *
39688
- * @category Post API
39815
+ * @category Comment API
39689
39816
  * @async
39690
39817
  * */
39691
- const unflagPost = async (postId) => {
39818
+ const unflagComment = async (commentId) => {
39692
39819
  const client = getActiveClient();
39693
- client.log('post/unflagPost', postId);
39694
- const { data: payload } = await client.http.delete(`/api/v3/posts/${encodeURIComponent(postId)}/unflag`);
39820
+ client.log('comment/unflagComment', commentId);
39821
+ const { data: payload } = await client.http.delete(`/api/v3/comments/${encodeURIComponent(commentId)}/unflag`);
39695
39822
  if (client.cache) {
39696
- ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
39823
+ ingestInCache(payload);
39697
39824
  }
39698
- fireEvent('post.unflagged', payload);
39825
+ fireEvent('comment.unflagged', payload);
39699
39826
  return !!payload;
39700
39827
  };
39701
39828
  /* end_public_function */
39702
39829
 
39703
39830
  /* begin_public_function
39704
- id: post.check_flag_by_me
39831
+ id: comment.check_flag_by_me
39705
39832
  */
39706
39833
  /**
39707
39834
  * ```js
39708
- * import { PostRepository } from '@amityco/ts-sdk'
39709
- * const isReported = await PostRepository.isPostFlaggedByMe('post', postId)
39835
+ * import { CommentRepository } from '@amityco/ts-sdk'
39836
+ * const isReported = await CommentRepository.isCommentFlaggedByMe('commentId')
39710
39837
  * ```
39711
39838
  *
39712
- * @param postId of the post to check if flagged by current user
39713
- * @returns `true` if the post is flagged by me, `false` if doesn't.
39839
+ * @param commentId The ID of the comment to check if flagged by current user
39840
+ * @returns `true` if the comment is flagged by me, `false` if doesn't.
39714
39841
  *
39715
- * @category Post API
39842
+ * @category Comment API
39716
39843
  * @async
39717
39844
  * */
39718
- const isPostFlaggedByMe = async (postId) => {
39845
+ const isCommentFlaggedByMe = async (commentId) => {
39719
39846
  const client = getActiveClient();
39720
- client.log('post/isPostFlaggedByMe', postId);
39721
- const { data: { result }, } = await client.http.get(`/api/v3/posts/${postId}/isflagbyme`);
39847
+ client.log('comment/isCommentFlaggedByMe', commentId);
39848
+ const { data: { result }, } = await client.http.get(`/api/v3/comments/${commentId}/isflagbyme`);
39722
39849
  return result;
39723
39850
  };
39724
39851
  /* end_public_function */
39725
39852
 
39726
- /* begin_public_function
39727
- id: post.create.clip_post
39728
- */
39729
- /**
39730
- * ```js
39731
- * import { PostRepository } from '@amityco/ts-sdk'
39732
- * const created = await PostRepository.createClipPost({
39733
- * targetType: 'user',
39734
- * targetId: 'foobar',
39735
- * dataType: 'clip',
39736
- * data: { text: 'hello world' },
39737
- * attachments: [{ type: 'clip', fileId: 'fileId123', displayMode: 'fill', isMuted: false }]
39738
- * }))
39739
- * ```
39740
- *
39741
- * Creates an {@link Amity.Post}
39742
- *
39743
- * @param bundle The data necessary to create a new {@link Amity.Post}
39744
- * @returns The newly created {@link Amity.Post}
39745
- *
39746
- * @category Post API
39747
- * @async
39748
- */
39749
- const createClipPost = async (bundle) => {
39750
- const client = getActiveClient();
39751
- client.log('post/createPost', bundle);
39752
- const { data: payload } = await client.http.post('/api/v4/posts', bundle);
39753
- fireEvent('post.created', payload);
39754
- const data = prepareMembershipPayload(payload, 'communityUsers');
39755
- const cachedAt = client.cache && Date.now();
39756
- if (client.cache)
39757
- ingestInCache(data, { cachedAt });
39758
- const { posts } = data;
39759
- return {
39760
- data: LinkedObject.post(posts[0]),
39761
- cachedAt,
39762
- };
39763
- };
39764
- /* end_public_function */
39765
-
39766
- /* begin_public_function
39767
- id: comment.get_by_ids
39768
- */
39769
- /**
39770
- * ```js
39771
- * import { CommentRepository } from '@amityco/ts-sdk'
39772
- * const comments = await CommentRepository.getCommentByIds(['foo', 'bar'])
39773
- * ```
39774
- *
39775
- * Fetches a collection of {@link Amity.Comment} objects
39776
- *
39777
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
39778
- * @returns the associated collection of {@link Amity.Comment} objects
39779
- *
39780
- * @category Comment API
39781
- * @async
39782
- */
39783
- const getCommentByIds = async (commentIds) => {
39853
+ const getComment$1 = async (commentId) => {
39784
39854
  const client = getActiveClient();
39785
- client.log('comment/getCommentByIds', commentIds);
39786
- const encodedCommentIds = commentIds.map(commentId => encodeURIComponent(commentId));
39855
+ client.log('comment/getComment', commentId);
39856
+ isInTombstone('comment', commentId);
39787
39857
  let data;
39788
39858
  try {
39789
39859
  // API-FIX: endpoint should not be /list, parameters should be querystring.
39790
- const response = await client.http.get(`/api/v3/comments/list`, {
39791
- params: { commentIds: encodedCommentIds },
39792
- });
39860
+ const response = await client.http.get(`/api/v3/comments/${encodeURIComponent(commentId)}`);
39793
39861
  data = response.data;
39794
39862
  }
39795
39863
  catch (error) {
39796
- commentIds.forEach(commentId => {
39797
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39798
- pushToTombstone('comment', commentId);
39799
- }
39800
- });
39864
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39865
+ pushToTombstone('comment', commentId);
39866
+ }
39801
39867
  throw error;
39802
39868
  }
39803
39869
  const cachedAt = client.cache && Date.now();
39804
39870
  if (client.cache)
39805
39871
  ingestInCache(data, { cachedAt });
39872
+ const { comments } = data;
39806
39873
  return {
39807
- data: data.comments.map(comment => LinkedObject.comment(comment)),
39874
+ data: comments.find(comment => comment.commentId === commentId),
39808
39875
  cachedAt,
39809
39876
  };
39810
39877
  };
39811
- /* end_public_function */
39812
- /**
39813
- * ```js
39814
- * import { getCommentByIds } from '@amityco/ts-sdk'
39815
- * const comments = getCommentByIds.locally(['foo', 'bar'])
39816
- * ```
39817
- *
39818
- * Fetches a collection of {@link Amity.Comment} objects from cache
39819
- *
39820
- * @param commentIds the IDs of the {@link Amity.Comment} to fetch
39821
- * @returns the associated collection of {@link Amity.Comment} objects
39822
- *
39823
- * @category Comment API
39824
- */
39825
- getCommentByIds.locally = (commentIds) => {
39826
- var _a;
39878
+ getComment$1.locally = (commentId) => {
39827
39879
  const client = getActiveClient();
39828
- client.log('comment/getCommentByIds.locally', commentIds);
39880
+ client.log('comment/getComment.locally', commentId);
39829
39881
  if (!client.cache)
39830
39882
  return;
39831
- const cached = commentIds
39832
- .map(commentId => pullFromCache(['comment', 'get', commentId]))
39833
- .filter(Boolean);
39834
- const comments = cached.map(({ data }) => data);
39835
- const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
39836
- if ((cached === null || cached === void 0 ? void 0 : cached.length) < commentIds.length)
39883
+ const cached = pullFromCache(['comment', 'get', commentId]);
39884
+ if (!cached)
39837
39885
  return;
39838
39886
  return {
39839
- data: comments.map(comment => LinkedObject.comment(comment)),
39840
- cachedAt: oldest.cachedAt,
39887
+ data: cached.data,
39888
+ cachedAt: cached.cachedAt,
39841
39889
  };
39842
39890
  };
39843
39891
 
39844
- /* begin_public_function
39845
- id: comment.create
39846
- */
39847
39892
  /**
39848
39893
  * ```js
39849
- * import { CommentRepository } from '@amityco/ts-sdk'
39850
- * const newComment = await CommentRepository.createComment(bundle)
39894
+ * import { onCommentDeleteLocal } from '@amityco/ts-sdk'
39895
+ * const dispose = onCommentDeleteLocal(comment => {
39896
+ * // ...
39897
+ * })
39851
39898
  * ```
39852
39899
  *
39853
- * Creates an {@link Amity.Comment}
39900
+ * Fired when a {@link Amity.InternalComment} has been deleted
39854
39901
  *
39855
- * @param bundle The data necessary to create a new {@link Amity.Comment}
39856
- * @returns The newly created {@link Amity.Comment}
39902
+ * @param callback The function to call when the event was fired
39903
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39857
39904
  *
39858
- * @category Comment API
39859
- * @async
39905
+ * @category Comment Events
39860
39906
  */
39861
- const createComment = async (bundle) => {
39862
- var _a;
39907
+ const onCommentDeleteLocal = (callback) => createLocalCommentEventSubscriber('local.comment.deleted', callback);
39908
+
39909
+ /**
39910
+ * ```js
39911
+ * import { onLocalCommentReactionAdded } from '@amityco/ts-sdk'
39912
+ * const dispose = onLocalCommentReactionAdded(comment => {
39913
+ * // ...
39914
+ * })
39915
+ * ```
39916
+ *
39917
+ * Fired when a {@link Amity.InternalComment} has been reacted
39918
+ *
39919
+ * @param callback The function to call when the event was fired
39920
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39921
+ *
39922
+ * @category Comment Events
39923
+ */
39924
+ const onLocalCommentReactionAdded = (callback) => {
39863
39925
  const client = getActiveClient();
39864
- client.log('comment/createComment', bundle);
39865
- const { data } = await client.http.post('/api/v3/comments', bundle);
39866
- const { comments } = data;
39867
- // BE always returns an array of comments If it got record 0 from BE it might have a problem on creation logic
39868
- if (comments.length === 0)
39869
- throw new Error('Comment not created');
39870
- const cachedAt = client.cache && Date.now();
39871
- if (client.cache)
39872
- ingestInCache(data, { cachedAt });
39873
- if (['post', 'content'].includes(bundle.referenceType)) {
39874
- const post = (_a = pullFromCache(['post', 'get', bundle.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
39875
- if (post) {
39876
- post.commentsCount += 1;
39877
- fireEvent('local.post.updated', {
39878
- posts: [post],
39879
- categories: [],
39880
- comments: [],
39881
- communities: [],
39882
- communityUsers: data.communityUsers,
39883
- feeds: [],
39884
- files: data.files,
39885
- postChildren: [],
39886
- users: data.users,
39887
- videoStreamings: [],
39888
- });
39926
+ const filter = ({ comment }) => {
39927
+ if (!client.cache) {
39928
+ callback(comment);
39889
39929
  }
39890
- }
39891
- else if (bundle.referenceType === 'story') {
39892
- const storyIndex = pullFromCache([
39893
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39894
- bundle.referenceId,
39895
- ]);
39896
- if (storyIndex === null || storyIndex === void 0 ? void 0 : storyIndex.data) {
39897
- const cacheStory = pullFromCache([
39898
- "story" /* STORY_KEY_CACHE.STORY */,
39899
- 'get',
39900
- storyIndex.data,
39901
- ]);
39902
- if (cacheStory === null || cacheStory === void 0 ? void 0 : cacheStory.data) {
39903
- fireEvent('story.updated', {
39904
- stories: [
39905
- Object.assign(Object.assign({}, cacheStory.data), { commentsCount: cacheStory.data.commentsCount + 1, comments: [...new Set([...cacheStory.data.comments, comments[0].commentId])] }),
39906
- ],
39907
- categories: [],
39908
- comments,
39909
- communities: [],
39910
- communityUsers: data.communityUsers,
39911
- files: data.files,
39912
- users: data.users,
39913
- });
39914
- }
39930
+ else {
39931
+ upsertInCache(['comment', 'get', comment.commentId], comment);
39932
+ callback(commentLinkedObject(comment));
39915
39933
  }
39916
- }
39917
- fireEvent('local.comment.created', data);
39918
- return {
39919
- data: LinkedObject.comment(comments[0]),
39920
- cachedAt,
39921
39934
  };
39935
+ return createEventSubscriber(client, 'local.comment.addReaction', 'local.comment.addReaction', filter);
39922
39936
  };
39923
- /* end_public_function */
39924
39937
 
39925
- /* begin_public_function
39926
- id: comment.update_comment
39927
- */
39928
39938
  /**
39929
39939
  * ```js
39930
- * import { CommentRepository } from '@amityco/ts-sdk'
39931
- * const updated = await CommentRepository.updateComment(commentId, {
39932
- * data: { text: 'hello world' }
39940
+ * import { onLocalCommentReactionRemoved } from '@amityco/ts-sdk'
39941
+ * const dispose = onLocalCommentReactionRemoved(comment => {
39942
+ * // ...
39933
39943
  * })
39934
39944
  * ```
39935
39945
  *
39936
- * Updates an {@link Amity.Comment}
39946
+ * Fired when a {@link Amity.InternalComment} has been reacted
39937
39947
  *
39938
- * @param commentId The ID of the {@link Amity.Comment} to edit
39939
- * @param patch The patch data to apply
39940
- * @returns the updated {@link Amity.Comment} object
39948
+ * @param callback The function to call when the event was fired
39949
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
39941
39950
  *
39942
- * @category Comment API
39943
- * @async
39951
+ * @category Comment Events
39944
39952
  */
39945
- const updateComment = async (commentId, patch) => {
39946
- const client = getActiveClient();
39947
- client.log('user/updateComment', patch);
39948
- const { data } = await client.http.put(`/api/v3/comments/${encodeURIComponent(commentId)}`, patch);
39949
- const cachedAt = client.cache && Date.now();
39950
- if (client.cache)
39951
- ingestInCache(data, { cachedAt });
39952
- fireEvent('comment.updated', data);
39953
- const { comments } = data;
39954
- return {
39955
- data: LinkedObject.comment(comments.find(comment => comment.commentId === commentId)),
39956
- cachedAt,
39957
- };
39958
- };
39959
- /* end_public_function */
39960
-
39961
- // Due to we have optimistic logic, we will use referenceId as a id in SDK instead of storyId
39962
- const applyMissingField = (rawData, isCreated = false) => {
39963
- const { storyId, referenceId } = rawData;
39964
- if (!isCreated) {
39965
- if (referenceId)
39966
- return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */ });
39967
- }
39968
- return Object.assign(Object.assign({}, rawData), { syncState: "synced" /* Amity.SyncState.Synced */, referenceId: storyId });
39969
- };
39970
- const convertRawStoryToInternal = (data, isCreated = false) => {
39971
- const { stories } = data;
39972
- const storiesData = stories.map(story => applyMissingField(story, isCreated));
39973
- return Object.assign(Object.assign({}, data), { stories: storiesData });
39974
- };
39975
-
39976
- const getStoryByStoryId$1 = async (storyId) => {
39953
+ const onLocalCommentReactionRemoved = (callback) => {
39977
39954
  const client = getActiveClient();
39978
- client.log('story/getStoryByStoryId', storyId);
39979
- // Get story referenceId from cache
39980
- const cacheReferenceId = pullFromCache([
39981
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
39982
- storyId,
39983
- ]);
39984
- if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
39985
- const { data: referenceId } = cacheReferenceId;
39986
- isInTombstone('story', referenceId);
39987
- }
39988
- let data;
39989
- try {
39990
- const response = await client.http.get(`/api/v4/stories/${storyId}`);
39991
- data = convertRawStoryToInternal(response.data);
39992
- }
39993
- catch (error) {
39994
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
39995
- pushToTombstone('story', storyId);
39955
+ const filter = ({ comment }) => {
39956
+ if (!client.cache) {
39957
+ callback(comment);
39958
+ }
39959
+ else {
39960
+ upsertInCache(['comment', 'get', comment.commentId], comment);
39961
+ callback(commentLinkedObject(comment));
39996
39962
  }
39997
- throw error;
39998
- }
39999
- const cachedAt = client.cache && Date.now();
40000
- if (client.cache) {
40001
- ingestInCache(data, { cachedAt });
40002
- }
40003
- return {
40004
- data: data.stories[0],
40005
- cachedAt,
40006
- };
40007
- };
40008
- getStoryByStoryId$1.locally = (storyId) => {
40009
- const client = getActiveClient();
40010
- client.log('story/getStorybyStoryId', storyId);
40011
- // Get story referenceId from cache
40012
- const cacheReferenceId = pullFromCache([
40013
- "story-reference" /* STORY_KEY_CACHE.STORY_ID_TO_REFERENCE_ID */,
40014
- storyId,
40015
- ]);
40016
- if (cacheReferenceId === null || cacheReferenceId === void 0 ? void 0 : cacheReferenceId.data) {
40017
- const { data: referenceId } = cacheReferenceId;
40018
- isInTombstone('story', referenceId);
40019
- }
40020
- const cachedAt = client.cache && Date.now();
40021
- const storyCache = pullFromCache(['story', 'get', storyId]);
40022
- if (!storyCache)
40023
- return;
40024
- return {
40025
- data: storyCache.data,
40026
- cachedAt,
40027
39963
  };
39964
+ return createEventSubscriber(client, 'local.comment.removeReaction', 'local.comment.removeReaction', filter);
40028
39965
  };
40029
39966
 
40030
39967
  /* begin_public_function
40031
- id: comment.soft_delete, comment.hard_delete
39968
+ id: comment.get
40032
39969
  */
40033
39970
  /**
40034
39971
  * ```js
40035
- * import { CommentRepository } from '@amityco/ts-sdk'
40036
- * const success = await CommentRepository.deleteComment('foobar')
39972
+ * import { CommentRepository } from '@amityco/ts-sdk';
39973
+ *
39974
+ * let comment;
39975
+ *
39976
+ * const unsub = CommentRepository.getComment(commentId, response => {
39977
+ * comment = response.data;
39978
+ * });
40037
39979
  * ```
40038
39980
  *
40039
- * Deletes a {@link Amity.Comment}
39981
+ * Observe all mutation on a given {@link Amity.Comment}
40040
39982
  *
40041
- * @param commentId The {@link Amity.Comment} ID to delete
40042
- * @return A success boolean if the {@link Amity.Comment} was deleted
39983
+ * @param commentId the ID of the comment to observe
39984
+ * @param callback the function to call when new data are available
39985
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
40043
39986
  *
40044
- * @category Comment API
40045
- * @async
39987
+ * @category Comment Live Object
40046
39988
  */
40047
- const deleteComment = async (commentId, permanent = false) => {
40048
- var _a;
40049
- const client = getActiveClient();
40050
- const comment = await getComment$2(commentId);
40051
- // API-FIX: This endpoint has not been implemented yet.
40052
- await client.http.delete(`/api/v4/comments/${encodeURIComponent(commentId)}`, {
40053
- params: {
40054
- commentId,
40055
- permanent,
40056
- },
40057
- });
40058
- // to support hard deletion
40059
- const deleted = Object.assign(Object.assign({}, comment.data), { isDeleted: true });
40060
- if (comment.data.referenceType === 'story') {
40061
- const story = await getStoryByStoryId$1(comment.data.referenceId);
40062
- fireEvent('local.story.updated', {
40063
- stories: [story.data],
40064
- categories: [],
40065
- comments: [],
40066
- communities: [],
40067
- communityUsers: [],
40068
- files: [],
40069
- users: [],
39989
+ const getComment = (commentId, callback) => {
39990
+ return liveObject(commentId, callback, 'commentId', getComment$1, [
39991
+ onCommentDeleteLocal,
39992
+ onCommentDeleted,
39993
+ onCommentFlagged,
39994
+ onCommentReactionAdded,
39995
+ onCommentReactionRemoved,
39996
+ onCommentUnflagged,
39997
+ onCommentUpdated,
39998
+ onLocalCommentReactionAdded,
39999
+ onLocalCommentReactionRemoved,
40000
+ ]);
40001
+ };
40002
+ /* end_public_function */
40003
+
40004
+ class CommentPaginationController extends PaginationController {
40005
+ async getRequest(queryParams, token) {
40006
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
40007
+ const baseOptions = {
40008
+ type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
40009
+ };
40010
+ const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
40011
+ const { data: queryResponse } = await this.http.get(`/api/v3/comments`, {
40012
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
40070
40013
  });
40014
+ return queryResponse;
40071
40015
  }
40072
- else {
40073
- const post = (_a = pullFromCache(['post', 'get', comment.data.referenceId])) === null || _a === void 0 ? void 0 : _a.data;
40074
- if (post) {
40075
- let removeCount;
40076
- if (!deleted.parentId) {
40077
- // NOTE: delete the parent comment will remove all children comments
40078
- removeCount = deleted.childrenNumber + 1;
40079
- }
40080
- else
40081
- removeCount = 1;
40082
- post.commentsCount -= removeCount;
40083
- fireEvent('local.post.updated', {
40084
- posts: [post],
40085
- categories: [],
40086
- comments: [],
40087
- communities: [],
40088
- communityUsers: [],
40089
- feeds: [],
40090
- files: [],
40091
- postChildren: [],
40092
- users: [],
40093
- videoStreamings: [],
40016
+ }
40017
+
40018
+ var EnumCommentActions;
40019
+ (function (EnumCommentActions) {
40020
+ EnumCommentActions["OnCommentCreated"] = "onCommentCreated";
40021
+ EnumCommentActions["OnCommentUpdated"] = "onCommentUpdated";
40022
+ EnumCommentActions["OnCommentDeleted"] = "onCommentDeleted";
40023
+ EnumCommentActions["OnCommentFlagged"] = "onCommentFlagged";
40024
+ EnumCommentActions["OnCommentUnflagged"] = "onCommentUnflagged";
40025
+ EnumCommentActions["OnCommentReactionAdded"] = "onCommentReactionAdded";
40026
+ EnumCommentActions["OnCommentReactionRemoved"] = "onCommentReactionRemoved";
40027
+ })(EnumCommentActions || (EnumCommentActions = {}));
40028
+
40029
+ class CommentQueryStreamController extends QueryStreamController {
40030
+ constructor(query, cacheKey, notifyChange, preparePayload) {
40031
+ super(query, cacheKey);
40032
+ this.notifyChange = notifyChange;
40033
+ this.preparePayload = preparePayload;
40034
+ }
40035
+ async saveToMainDB(response) {
40036
+ const processedPayload = await this.preparePayload(response);
40037
+ const client = getActiveClient();
40038
+ const cachedAt = client.cache && Date.now();
40039
+ if (client.cache) {
40040
+ ingestInCache(processedPayload, { cachedAt });
40041
+ }
40042
+ }
40043
+ appendToQueryStream(response, direction, refresh = false) {
40044
+ var _a, _b;
40045
+ if (refresh) {
40046
+ pushToCache(this.cacheKey, {
40047
+ data: response.comments.map(getResolver('comment')),
40094
40048
  });
40095
40049
  }
40050
+ else {
40051
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40052
+ const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
40053
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...response.comments.map(getResolver('comment'))])] }));
40054
+ }
40096
40055
  }
40097
- fireEvent('local.comment.deleted', {
40098
- comments: [deleted],
40099
- commentChildren: [],
40100
- files: [],
40101
- users: [],
40102
- communityUsers: [],
40103
- });
40104
- if (permanent) {
40105
- scheduleTask(() => pushToTombstone('comment', commentId));
40056
+ reactor(action) {
40057
+ return (comment) => {
40058
+ var _a;
40059
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40060
+ if (this.query.referenceId !== comment.referenceId ||
40061
+ this.query.referenceType !== comment.referenceType ||
40062
+ !collection) {
40063
+ return;
40064
+ }
40065
+ if (this.query.parentId && this.query.parentId !== comment.parentId) {
40066
+ return;
40067
+ }
40068
+ if (!this.query.parentId && comment.parentId) {
40069
+ return;
40070
+ }
40071
+ if (action === EnumCommentActions.OnCommentCreated) {
40072
+ collection.data = [...new Set([comment.commentId, ...collection.data])];
40073
+ }
40074
+ pushToCache(this.cacheKey, collection);
40075
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
40076
+ };
40106
40077
  }
40107
- else {
40108
- upsertInCache(['comment', 'get', commentId], { isDeleted: true });
40078
+ subscribeRTE(createSubscriber) {
40079
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
40109
40080
  }
40110
- return deleted;
40111
- };
40112
- /* end_public_function */
40081
+ }
40113
40082
 
40114
- /* begin_public_function
40115
- id: comment.soft_delete
40116
- */
40117
40083
  /**
40118
40084
  * ```js
40119
- * import { CommentRepository } from '@amityco/ts-sdk'
40120
- * const success = await CommentRepository.softDeleteComment('foobar')
40085
+ * import { onCommentCreated } from '@amityco/ts-sdk'
40086
+ * const dispose = onCommentCreated(comment => {
40087
+ * // ...
40088
+ * })
40121
40089
  * ```
40122
40090
  *
40123
- * Deletes a {@link Amity.Comment}
40091
+ * Fired when a {@link Amity.InternalComment} has been created
40124
40092
  *
40125
- * @param commentId The {@link Amity.Comment} ID to delete
40126
- * @return A success boolean if the {@link Amity.Comment} was deleted
40093
+ * @param callback The function to call when the event was fired
40094
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
40127
40095
  *
40128
- * @category Comment API
40129
- * @async
40096
+ * @category Comment Events
40130
40097
  */
40131
- const softDeleteComment = async (commentId) => {
40132
- const client = getActiveClient();
40133
- client.log('comment/softDeleteComment', commentId);
40134
- const softDeleted = deleteComment(commentId);
40135
- return softDeleted;
40098
+ const onCommentCreatedLocal = (callback) => {
40099
+ return createLocalCommentEventSubscriber('local.comment.created', callback);
40136
40100
  };
40137
- /* end_public_function */
40101
+
40102
+ class CommentLiveCollectionController extends LiveCollectionController {
40103
+ constructor(query, callback) {
40104
+ const queryStreamId = hash(query);
40105
+ const cacheKey = ['comments', 'collection', queryStreamId];
40106
+ const paginationController = new CommentPaginationController(query);
40107
+ super(paginationController, queryStreamId, cacheKey, callback);
40108
+ this.query = query;
40109
+ this.queryStreamController = new CommentQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommentPayload);
40110
+ this.callback = callback.bind(this);
40111
+ this.loadPage({ initial: true });
40112
+ }
40113
+ setup() {
40114
+ var _a;
40115
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40116
+ if (!collection) {
40117
+ pushToCache(this.cacheKey, {
40118
+ data: [],
40119
+ params: {},
40120
+ });
40121
+ }
40122
+ }
40123
+ async persistModel(queryPayload) {
40124
+ await this.queryStreamController.saveToMainDB(queryPayload);
40125
+ }
40126
+ persistQueryStream({ response, direction, refresh, }) {
40127
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
40128
+ }
40129
+ startSubscription() {
40130
+ return this.queryStreamController.subscribeRTE([
40131
+ { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
40132
+ { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
40133
+ { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
40134
+ { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
40135
+ { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
40136
+ { fn: onCommentFlagged, action: EnumCommentActions.OnCommentFlagged },
40137
+ { fn: onCommentUnflagged, action: EnumCommentActions.OnCommentUnflagged },
40138
+ { fn: onCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
40139
+ { fn: onCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
40140
+ { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
40141
+ { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
40142
+ ]);
40143
+ }
40144
+ notifyChange({ origin, loading, error }) {
40145
+ var _a, _b;
40146
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40147
+ if (!collection)
40148
+ return;
40149
+ const data = this.applyFilter((_b = collection.data
40150
+ .map(id => pullFromCache(['comment', 'get', id]))
40151
+ .filter(isNonNullable)
40152
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.comment);
40153
+ if (!this.shouldNotify(data) && origin === 'event')
40154
+ return;
40155
+ this.callback({
40156
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
40157
+ data,
40158
+ hasNextPage: !!this.paginationController.getNextToken(),
40159
+ loading,
40160
+ error,
40161
+ });
40162
+ }
40163
+ applyFilter(data) {
40164
+ let comments = data;
40165
+ if (!this.query.includeDeleted) {
40166
+ comments = filterByPropEquality(comments, 'isDeleted', false);
40167
+ }
40168
+ if (this.query.parentId) {
40169
+ comments = comments.filter(comment => comment.parentId === this.query.parentId);
40170
+ }
40171
+ if (typeof this.query.hasFlag === 'boolean') {
40172
+ if (this.query.hasFlag) {
40173
+ comments = comments.filter(comment => comment.hashFlag != null);
40174
+ }
40175
+ else {
40176
+ comments = comments.filter(comment => comment.hashFlag == null);
40177
+ }
40178
+ }
40179
+ if (this.query.dataTypes) {
40180
+ if (this.query.dataTypes.matchType === 'exact') {
40181
+ comments = comments.filter(comment => {
40182
+ var _a, _b;
40183
+ const sortedDataTypesQueryValue = ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.sort()) || [];
40184
+ const sortedDataTypesCommentValue = ((_b = comment.dataTypes) === null || _b === void 0 ? void 0 : _b.sort()) || [];
40185
+ if (sortedDataTypesCommentValue.length !== sortedDataTypesQueryValue.length) {
40186
+ return false;
40187
+ }
40188
+ return sortedDataTypesQueryValue.every((value, index) => value === sortedDataTypesCommentValue[index]);
40189
+ });
40190
+ }
40191
+ if (this.query.dataTypes.matchType === 'any') {
40192
+ 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); }); });
40193
+ }
40194
+ }
40195
+ switch (this.query.sortBy) {
40196
+ case 'firstCreated':
40197
+ comments = comments.sort(sortByFirstCreated);
40198
+ break;
40199
+ case 'lastCreated':
40200
+ default:
40201
+ comments = comments.sort(sortByLastCreated);
40202
+ break;
40203
+ }
40204
+ return comments;
40205
+ }
40206
+ }
40138
40207
 
40139
40208
  /* begin_public_function
40140
- id: comment.hard_delete
40209
+ id: comment.query
40141
40210
  */
40142
40211
  /**
40143
40212
  * ```js
40144
- * import { CommentRepository } from '@amityco/ts-sdk'
40145
- * const success = await CommentRepository.hardDeleteComment('foobar')
40213
+ * import { getComments } from '@amityco/ts-sdk'
40214
+ *
40215
+ * let comments = []
40216
+ * const unsub = getComments({
40217
+ * referenceType: Amity.InternalComment['referenceType'];
40218
+ * referenceId: Amity.InternalComment['referenceId'];
40219
+ * }, response => merge(comments, response.data))
40146
40220
  * ```
40147
40221
  *
40148
- * Deletes a {@link Amity.Comment}
40222
+ * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
40149
40223
  *
40150
- * @param commentId The {@link Amity.Comment} ID to delete
40151
- * @return A success boolean if the {@link Amity.Comment} was deleted
40224
+ * @param referenceType the type of the target
40225
+ * @param referenceId the ID of the target
40226
+ * @param callback the function to call when new data are available
40227
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
40152
40228
  *
40153
- * @category Comment API
40154
- * @async
40229
+ * @category Comments Live Collection
40155
40230
  */
40156
- const hardDeleteComment = async (commentId) => {
40157
- const client = getActiveClient();
40158
- client.log('comment/hardDeleteComment', commentId);
40159
- const hardDeleted = deleteComment(commentId, true);
40160
- return hardDeleted;
40231
+ const getComments = (params, callback, config) => {
40232
+ const { log, cache } = getActiveClient();
40233
+ if (!cache) {
40234
+ console.log('For using Live Collection feature you need to enable Cache!');
40235
+ }
40236
+ const timestamp = Date.now();
40237
+ log(`getComments(tmpid: ${timestamp}) > listen`);
40238
+ const commentsLiveCollection = new CommentLiveCollectionController(params, callback);
40239
+ const disposers = commentsLiveCollection.startSubscription();
40240
+ const cacheKey = commentsLiveCollection.getCacheKey();
40241
+ disposers.push(() => dropFromCache(cacheKey));
40242
+ return () => {
40243
+ log(`getComments(tmpid: ${timestamp}) > dispose`);
40244
+ disposers.forEach(fn => fn());
40245
+ };
40161
40246
  };
40162
40247
  /* end_public_function */
40163
40248
 
40164
- /* begin_public_function
40165
- id: comment.flag
40166
- */
40167
- /**
40168
- * ```js
40169
- * import { CommentRepository } from '@amityco/ts-sdk'
40170
- * const flagged = await CommentRepository.flagComment(commentId, reason)
40171
- * ```
40172
- *
40173
- * @param commentId The ID of the comment to flag
40174
- * @param reason the reason to flag the comment
40175
- * @returns the created report result
40176
- *
40177
- * @category Comment API
40178
- * @async
40179
- * */
40180
- const flagComment = async (commentId, reason) => {
40181
- const client = getActiveClient();
40182
- client.log('comment/flagComment', commentId);
40183
- const isPredefinedReason = reason &&
40184
- Object.entries(ContentFlagReasonEnum).some(([key, value]) => key !== ContentFlagReasonEnum.Others && value === reason);
40185
- const body = {
40186
- reason: reason && isPredefinedReason ? reason : ContentFlagReasonEnum.Others,
40187
- detail: reason && !isPredefinedReason ? reason : '',
40188
- };
40189
- const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/flag`, body);
40190
- if (client.cache) {
40191
- ingestInCache(payload);
40192
- }
40193
- fireEvent('comment.flagged', payload);
40194
- return !!payload;
40195
- };
40196
- /* end_public_function */
40197
-
40198
- /* begin_public_function
40199
- id: comment.unflag
40200
- */
40201
- /**
40202
- * ```js
40203
- * import { CommentRepository } from '@amityco/ts-sdk'
40204
- * const unflagged = await CommentRepository.unflagComment('commentId')
40205
- * ```
40206
- *
40207
- * @param commentId The ID of comment to unflag
40208
- * @returns the unflagged result
40209
- *
40210
- * @category Comment API
40211
- * @async
40212
- * */
40213
- const unflagComment = async (commentId) => {
40214
- const client = getActiveClient();
40215
- client.log('comment/unflagComment', commentId);
40216
- const { data: payload } = await client.http.delete(`/api/v3/comments/${encodeURIComponent(commentId)}/unflag`);
40217
- if (client.cache) {
40218
- ingestInCache(payload);
40219
- }
40220
- fireEvent('comment.unflagged', payload);
40221
- return !!payload;
40222
- };
40223
- /* end_public_function */
40224
-
40225
- /* begin_public_function
40226
- id: comment.check_flag_by_me
40227
- */
40228
- /**
40229
- * ```js
40230
- * import { CommentRepository } from '@amityco/ts-sdk'
40231
- * const isReported = await CommentRepository.isCommentFlaggedByMe('commentId')
40232
- * ```
40233
- *
40234
- * @param commentId The ID of the comment to check if flagged by current user
40235
- * @returns `true` if the comment is flagged by me, `false` if doesn't.
40236
- *
40237
- * @category Comment API
40238
- * @async
40239
- * */
40240
- const isCommentFlaggedByMe = async (commentId) => {
40241
- const client = getActiveClient();
40242
- client.log('comment/isCommentFlaggedByMe', commentId);
40243
- const { data: { result }, } = await client.http.get(`/api/v3/comments/${commentId}/isflagbyme`);
40244
- return result;
40245
- };
40246
- /* end_public_function */
40249
+ var index$a = /*#__PURE__*/Object.freeze({
40250
+ __proto__: null,
40251
+ getCommentByIds: getCommentByIds,
40252
+ createComment: createComment,
40253
+ updateComment: updateComment,
40254
+ deleteComment: deleteComment,
40255
+ softDeleteComment: softDeleteComment,
40256
+ hardDeleteComment: hardDeleteComment,
40257
+ flagComment: flagComment,
40258
+ unflagComment: unflagComment,
40259
+ isCommentFlaggedByMe: isCommentFlaggedByMe,
40260
+ onCommentCreated: onCommentCreated,
40261
+ onCommentUpdated: onCommentUpdated,
40262
+ onCommentDeleted: onCommentDeleted,
40263
+ onCommentFlagged: onCommentFlagged,
40264
+ onCommentUnflagged: onCommentUnflagged,
40265
+ onCommentReactionAdded: onCommentReactionAdded,
40266
+ onCommentReactionRemoved: onCommentReactionRemoved,
40267
+ getComment: getComment,
40268
+ getComments: getComments
40269
+ });
40247
40270
 
40248
- const getComment$1 = async (commentId) => {
40271
+ const getPost$1 = async (postId) => {
40249
40272
  const client = getActiveClient();
40250
- client.log('comment/getComment', commentId);
40251
- isInTombstone('comment', commentId);
40252
- let data;
40273
+ client.log('post/getPost', postId);
40274
+ isInTombstone('post', postId);
40275
+ let payload;
40253
40276
  try {
40254
40277
  // API-FIX: endpoint should not be /list, parameters should be querystring.
40255
- const response = await client.http.get(`/api/v3/comments/${encodeURIComponent(commentId)}`);
40256
- data = response.data;
40278
+ const response = await client.http.get(`/api/v3/posts/${encodeURIComponent(postId)}`);
40279
+ payload = response.data;
40257
40280
  }
40258
40281
  catch (error) {
40259
40282
  if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
40260
- pushToTombstone('comment', commentId);
40283
+ pushToTombstone('post', postId);
40261
40284
  }
40262
40285
  throw error;
40263
40286
  }
40287
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40264
40288
  const cachedAt = client.cache && Date.now();
40265
40289
  if (client.cache)
40266
40290
  ingestInCache(data, { cachedAt });
40267
- const { comments } = data;
40291
+ const { posts } = data;
40292
+ const result = posts.find(post => post.postId === postId);
40268
40293
  return {
40269
- data: comments.find(comment => comment.commentId === commentId),
40294
+ data: result,
40270
40295
  cachedAt,
40271
40296
  };
40272
40297
  };
40273
- getComment$1.locally = (commentId) => {
40298
+ getPost$1.locally = (postId) => {
40274
40299
  const client = getActiveClient();
40275
- client.log('comment/getComment.locally', commentId);
40300
+ client.log('post/getPost.locally', postId);
40276
40301
  if (!client.cache)
40277
40302
  return;
40278
- const cached = pullFromCache(['comment', 'get', commentId]);
40303
+ const cached = pullFromCache(['post', 'get', postId]);
40279
40304
  if (!cached)
40280
40305
  return;
40281
40306
  return {
@@ -40286,224 +40311,106 @@ getComment$1.locally = (commentId) => {
40286
40311
 
40287
40312
  /**
40288
40313
  * ```js
40289
- * import { onCommentDeleteLocal } from '@amityco/ts-sdk'
40290
- * const dispose = onCommentDeleteLocal(comment => {
40314
+ * import { onPostUpdatedLocal } from '@amityco/ts-sdk'
40315
+ * const dispose = onPostUpdatedLocal(post => {
40291
40316
  * // ...
40292
40317
  * })
40293
40318
  * ```
40294
40319
  *
40295
- * Fired when a {@link Amity.InternalComment} has been deleted
40320
+ * Fired when a {@link Amity.InternalPost} has been updated
40296
40321
  *
40297
40322
  * @param callback The function to call when the event was fired
40298
40323
  * @returns an {@link Amity.Unsubscriber} function to stop listening
40299
40324
  *
40300
- * @category Comment Events
40325
+ * @category Post Events
40301
40326
  */
40302
- const onCommentDeleteLocal = (callback) => createLocalCommentEventSubscriber('local.comment.deleted', callback);
40327
+ const onPostUpdatedLocal = (callback) => createLocalPostEventSubscriber('local.post.updated', callback);
40303
40328
 
40304
40329
  /**
40305
40330
  * ```js
40306
- * import { onLocalCommentReactionAdded } from '@amityco/ts-sdk'
40307
- * const dispose = onLocalCommentReactionAdded(comment => {
40331
+ * import { onLocalPostReactionAdded } from '@amityco/ts-sdk'
40332
+ * const dispose = onPostReactionAdded(post => {
40308
40333
  * // ...
40309
40334
  * })
40310
40335
  * ```
40311
40336
  *
40312
- * Fired when a {@link Amity.InternalComment} has been reacted
40337
+ * Fired when a {@link Amity.InternalPost} has been reacted
40313
40338
  *
40314
40339
  * @param callback The function to call when the event was fired
40315
40340
  * @returns an {@link Amity.Unsubscriber} function to stop listening
40316
40341
  *
40317
- * @category Comment Events
40342
+ * @category Post Events
40318
40343
  */
40319
- const onLocalCommentReactionAdded = (callback) => {
40344
+ const onLocalPostReactionAdded = (callback) => {
40320
40345
  const client = getActiveClient();
40321
- const filter = ({ comment }) => {
40346
+ const filter = ({ post }) => {
40322
40347
  if (!client.cache) {
40323
- callback(comment);
40348
+ callback(post);
40324
40349
  }
40325
40350
  else {
40326
- upsertInCache(['comment', 'get', comment.commentId], comment);
40327
- callback(commentLinkedObject(comment));
40351
+ upsertInCache(['post', 'get', post.postId], post);
40352
+ callback(post);
40328
40353
  }
40329
40354
  };
40330
- return createEventSubscriber(client, 'local.comment.addReaction', 'local.comment.addReaction', filter);
40355
+ return createEventSubscriber(client, 'local.post.addReaction', 'local.post.addReaction', filter);
40331
40356
  };
40332
40357
 
40333
40358
  /**
40334
40359
  * ```js
40335
- * import { onLocalCommentReactionRemoved } from '@amityco/ts-sdk'
40336
- * const dispose = onLocalCommentReactionRemoved(comment => {
40360
+ * import { onLocalPostReactionRemoved } from '@amityco/ts-sdk'
40361
+ * const dispose = onPostReactionRemoved(post => {
40337
40362
  * // ...
40338
40363
  * })
40339
40364
  * ```
40340
40365
  *
40341
- * Fired when a {@link Amity.InternalComment} has been reacted
40366
+ * Fired when a {@link Amity.InternalPost} has been reacted
40342
40367
  *
40343
40368
  * @param callback The function to call when the event was fired
40344
40369
  * @returns an {@link Amity.Unsubscriber} function to stop listening
40345
40370
  *
40346
- * @category Comment Events
40371
+ * @category Post Events
40347
40372
  */
40348
- const onLocalCommentReactionRemoved = (callback) => {
40373
+ const onLocalPostReactionRemoved = (callback) => {
40349
40374
  const client = getActiveClient();
40350
- const filter = ({ comment }) => {
40375
+ const filter = ({ post }) => {
40351
40376
  if (!client.cache) {
40352
- callback(comment);
40377
+ callback(post);
40353
40378
  }
40354
40379
  else {
40355
- upsertInCache(['comment', 'get', comment.commentId], comment);
40356
- callback(commentLinkedObject(comment));
40380
+ upsertInCache(['post', 'get', post.postId], post);
40381
+ callback(post);
40357
40382
  }
40358
40383
  };
40359
- return createEventSubscriber(client, 'local.comment.removeReaction', 'local.comment.removeReaction', filter);
40384
+ return createEventSubscriber(client, 'local.post.removeReaction', 'local.post.removeReaction', filter);
40360
40385
  };
40361
40386
 
40362
- /* begin_public_function
40363
- id: comment.get
40364
- */
40365
40387
  /**
40366
40388
  * ```js
40367
- * import { CommentRepository } from '@amityco/ts-sdk';
40368
- *
40369
- * let comment;
40370
- *
40371
- * const unsub = CommentRepository.getComment(commentId, response => {
40372
- * comment = response.data;
40373
- * });
40389
+ * import { onLocalPostDeleted } from '@amityco/ts-sdk'
40390
+ * const dispose = onLocalPostDeleted(post => {
40391
+ * // ...
40392
+ * })
40374
40393
  * ```
40375
40394
  *
40376
- * Observe all mutation on a given {@link Amity.Comment}
40395
+ * Fired when a {@link Amity.InternalPost} has been deleted
40377
40396
  *
40378
- * @param commentId the ID of the comment to observe
40379
- * @param callback the function to call when new data are available
40380
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the comment
40397
+ * @param callback The function to call when the event was fired
40398
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
40381
40399
  *
40382
- * @category Comment Live Object
40400
+ * @category Post Events
40383
40401
  */
40384
- const getComment = (commentId, callback) => {
40385
- return liveObject(commentId, callback, 'commentId', getComment$1, [
40386
- onCommentDeleteLocal,
40387
- onCommentDeleted,
40388
- onCommentFlagged,
40389
- onCommentReactionAdded,
40390
- onCommentReactionRemoved,
40391
- onCommentUnflagged,
40392
- onCommentUpdated,
40393
- onLocalCommentReactionAdded,
40394
- onLocalCommentReactionRemoved,
40395
- ]);
40396
- };
40397
- /* end_public_function */
40398
-
40399
- class CommentPaginationController extends PaginationController {
40400
- async getRequest(queryParams, token) {
40401
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
40402
- const baseOptions = {
40403
- type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
40404
- };
40405
- const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
40406
- const { data: queryResponse } = await this.http.get(`/api/v3/comments`, {
40407
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
40408
- });
40409
- return queryResponse;
40410
- }
40411
- }
40412
-
40413
- var EnumCommentActions;
40414
- (function (EnumCommentActions) {
40415
- EnumCommentActions["OnCommentCreated"] = "onCommentCreated";
40416
- EnumCommentActions["OnCommentUpdated"] = "onCommentUpdated";
40417
- EnumCommentActions["OnCommentDeleted"] = "onCommentDeleted";
40418
- EnumCommentActions["OnCommentFlagged"] = "onCommentFlagged";
40419
- EnumCommentActions["OnCommentUnflagged"] = "onCommentUnflagged";
40420
- EnumCommentActions["OnCommentReactionAdded"] = "onCommentReactionAdded";
40421
- EnumCommentActions["OnCommentReactionRemoved"] = "onCommentReactionRemoved";
40422
- })(EnumCommentActions || (EnumCommentActions = {}));
40402
+ const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.post.deleted', callback);
40423
40403
 
40424
- class CommentQueryStreamController extends QueryStreamController {
40425
- constructor(query, cacheKey, notifyChange, preparePayload) {
40426
- super(query, cacheKey);
40427
- this.notifyChange = notifyChange;
40428
- this.preparePayload = preparePayload;
40429
- }
40430
- async saveToMainDB(response) {
40431
- const processedPayload = await this.preparePayload(response);
40432
- const client = getActiveClient();
40433
- const cachedAt = client.cache && Date.now();
40434
- if (client.cache) {
40435
- ingestInCache(processedPayload, { cachedAt });
40436
- }
40437
- }
40438
- appendToQueryStream(response, direction, refresh = false) {
40439
- var _a, _b;
40440
- if (refresh) {
40441
- pushToCache(this.cacheKey, {
40442
- data: response.comments.map(getResolver('comment')),
40443
- });
40444
- }
40445
- else {
40446
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40447
- const comments = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
40448
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...comments, ...response.comments.map(getResolver('comment'))])] }));
40449
- }
40450
- }
40451
- reactor(action) {
40452
- return (comment) => {
40453
- var _a;
40454
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40455
- if (this.query.referenceId !== comment.referenceId ||
40456
- this.query.referenceType !== comment.referenceType ||
40457
- !collection) {
40458
- return;
40459
- }
40460
- if (this.query.parentId && this.query.parentId !== comment.parentId) {
40461
- return;
40462
- }
40463
- if (!this.query.parentId && comment.parentId) {
40464
- return;
40465
- }
40466
- if (action === EnumCommentActions.OnCommentCreated) {
40467
- collection.data = [...new Set([comment.commentId, ...collection.data])];
40468
- }
40469
- pushToCache(this.cacheKey, collection);
40470
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
40471
- };
40472
- }
40473
- subscribeRTE(createSubscriber) {
40474
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
40475
- }
40476
- }
40477
-
40478
- /**
40479
- * ```js
40480
- * import { onCommentCreated } from '@amityco/ts-sdk'
40481
- * const dispose = onCommentCreated(comment => {
40482
- * // ...
40483
- * })
40484
- * ```
40485
- *
40486
- * Fired when a {@link Amity.InternalComment} has been created
40487
- *
40488
- * @param callback The function to call when the event was fired
40489
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40490
- *
40491
- * @category Comment Events
40492
- */
40493
- const onCommentCreatedLocal = (callback) => {
40494
- return createLocalCommentEventSubscriber('local.comment.created', callback);
40495
- };
40496
-
40497
- class CommentLiveCollectionController extends LiveCollectionController {
40498
- constructor(query, callback) {
40499
- const queryStreamId = hash(query);
40500
- const cacheKey = ['comments', 'collection', queryStreamId];
40501
- const paginationController = new CommentPaginationController(query);
40502
- super(paginationController, queryStreamId, cacheKey, callback);
40503
- this.query = query;
40504
- this.queryStreamController = new CommentQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommentPayload);
40505
- this.callback = callback.bind(this);
40506
- this.loadPage({ initial: true });
40404
+ class UserFeedLiveCollectionController extends LiveCollectionController {
40405
+ constructor(query, callback) {
40406
+ const queryStreamId = hash(query);
40407
+ const cacheKey = ['userFeed', 'collection', queryStreamId];
40408
+ const paginationController = new UserFeedPaginationController(query);
40409
+ super(paginationController, queryStreamId, cacheKey, callback);
40410
+ this.query = query;
40411
+ this.queryStreamController = new UserFeedQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), preparePostPayload);
40412
+ this.callback = callback.bind(this);
40413
+ this.loadPage({ initial: true });
40507
40414
  }
40508
40415
  setup() {
40509
40416
  var _a;
@@ -40523,17 +40430,45 @@ class CommentLiveCollectionController extends LiveCollectionController {
40523
40430
  }
40524
40431
  startSubscription() {
40525
40432
  return this.queryStreamController.subscribeRTE([
40526
- { fn: onCommentCreatedLocal, action: EnumCommentActions.OnCommentCreated },
40527
- { fn: onCommentDeleteLocal, action: EnumCommentActions.OnCommentDeleted },
40528
- { fn: onCommentCreated, action: EnumCommentActions.OnCommentCreated },
40529
- { fn: onCommentUpdated, action: EnumCommentActions.OnCommentUpdated },
40530
- { fn: onCommentDeleted, action: EnumCommentActions.OnCommentDeleted },
40531
- { fn: onCommentFlagged, action: EnumCommentActions.OnCommentFlagged },
40532
- { fn: onCommentUnflagged, action: EnumCommentActions.OnCommentUnflagged },
40533
- { fn: onCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
40534
- { fn: onCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
40535
- { fn: onLocalCommentReactionAdded, action: EnumCommentActions.OnCommentReactionAdded },
40536
- { fn: onLocalCommentReactionRemoved, action: EnumCommentActions.OnCommentReactionRemoved },
40433
+ { fn: onPostCreated, action: EnumPostActions.OnPostCreated },
40434
+ { fn: onPostUpdated, action: EnumPostActions.OnPostUpdated },
40435
+ { fn: onPostUpdatedLocal, action: EnumPostActions.OnPostUpdated },
40436
+ { fn: onPostDeleted, action: EnumPostActions.OnPostDeleted },
40437
+ { fn: onPostFlagged, action: EnumPostActions.OnPostFlagged },
40438
+ { fn: onPostUnflagged, action: EnumPostActions.OnPostUnflagged },
40439
+ { fn: onPostApproved, action: EnumPostActions.OnPostApproved },
40440
+ { fn: onPostDeclined, action: EnumPostActions.OnPostDeclined },
40441
+ { fn: onPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
40442
+ { fn: onPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
40443
+ { fn: onLocalPostReactionAdded, action: EnumPostActions.OnPostReactionAdded },
40444
+ { fn: onLocalPostReactionRemoved, action: EnumPostActions.OnPostReactionRemoved },
40445
+ { fn: onLocalPostDeleted, action: EnumPostActions.OnPostDeleted },
40446
+ {
40447
+ fn: convertEventPayload((callback) => {
40448
+ return onCommentCreated(async (comment) => {
40449
+ var _a;
40450
+ const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40451
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
40452
+ return;
40453
+ await getPost$1(comment.referenceId);
40454
+ callback(comment);
40455
+ });
40456
+ }, 'referenceId', 'post'),
40457
+ action: EnumPostActions.OnPostUpdated,
40458
+ },
40459
+ {
40460
+ fn: convertEventPayload((callback) => {
40461
+ return onCommentDeleted(async (comment) => {
40462
+ var _a;
40463
+ const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
40464
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
40465
+ return;
40466
+ await getPost$1(comment.referenceId);
40467
+ callback(comment);
40468
+ });
40469
+ }, 'referenceId', 'post'),
40470
+ action: EnumPostActions.OnPostUpdated,
40471
+ },
40537
40472
  ]);
40538
40473
  }
40539
40474
  notifyChange({ origin, loading, error }) {
@@ -40542,9 +40477,9 @@ class CommentLiveCollectionController extends LiveCollectionController {
40542
40477
  if (!collection)
40543
40478
  return;
40544
40479
  const data = this.applyFilter((_b = collection.data
40545
- .map(id => pullFromCache(['comment', 'get', id]))
40480
+ .map(id => pullFromCache(['post', 'get', id]))
40546
40481
  .filter(isNonNullable)
40547
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.comment);
40482
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.post);
40548
40483
  if (!this.shouldNotify(data) && origin === 'event')
40549
40484
  return;
40550
40485
  this.callback({
@@ -40556,86 +40491,64 @@ class CommentLiveCollectionController extends LiveCollectionController {
40556
40491
  });
40557
40492
  }
40558
40493
  applyFilter(data) {
40559
- let comments = data;
40494
+ var _a;
40495
+ let posts = data;
40560
40496
  if (!this.query.includeDeleted) {
40561
- comments = filterByPropEquality(comments, 'isDeleted', false);
40562
- }
40563
- if (this.query.parentId) {
40564
- comments = comments.filter(comment => comment.parentId === this.query.parentId);
40565
- }
40566
- if (typeof this.query.hasFlag === 'boolean') {
40567
- if (this.query.hasFlag) {
40568
- comments = comments.filter(comment => comment.hashFlag != null);
40569
- }
40570
- else {
40571
- comments = comments.filter(comment => comment.hashFlag == null);
40572
- }
40497
+ posts = filterByPropEquality(posts, 'isDeleted', false);
40573
40498
  }
40574
- if (this.query.dataTypes) {
40575
- if (this.query.dataTypes.matchType === 'exact') {
40576
- comments = comments.filter(comment => {
40577
- var _a, _b;
40578
- const sortedDataTypesQueryValue = ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.values.sort()) || [];
40579
- const sortedDataTypesCommentValue = ((_b = comment.dataTypes) === null || _b === void 0 ? void 0 : _b.sort()) || [];
40580
- if (sortedDataTypesCommentValue.length !== sortedDataTypesQueryValue.length) {
40581
- return false;
40582
- }
40583
- return sortedDataTypesQueryValue.every((value, index) => value === sortedDataTypesCommentValue[index]);
40584
- });
40585
- }
40586
- if (this.query.dataTypes.matchType === 'any') {
40587
- 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); }); });
40588
- }
40499
+ if ((_a = this.query.dataTypes) === null || _a === void 0 ? void 0 : _a.length) {
40500
+ posts = filterByPostDataTypes(posts, this.query.dataTypes);
40589
40501
  }
40590
40502
  switch (this.query.sortBy) {
40591
40503
  case 'firstCreated':
40592
- comments = comments.sort(sortByFirstCreated);
40504
+ posts = posts.sort(sortByFirstCreated);
40593
40505
  break;
40594
40506
  case 'lastCreated':
40595
40507
  default:
40596
- comments = comments.sort(sortByLastCreated);
40508
+ posts = posts.sort(sortByLastCreated);
40597
40509
  break;
40598
40510
  }
40599
- return comments;
40511
+ return posts;
40600
40512
  }
40601
40513
  }
40602
40514
 
40603
40515
  /* begin_public_function
40604
- id: comment.query
40516
+ id: feed.query.user_feed
40605
40517
  */
40606
40518
  /**
40607
40519
  * ```js
40608
- * import { getComments } from '@amityco/ts-sdk'
40520
+ * import { FeedRepository } from '@amityco/ts-sdk'
40609
40521
  *
40610
- * let comments = []
40611
- * const unsub = getComments({
40612
- * referenceType: Amity.InternalComment['referenceType'];
40613
- * referenceId: Amity.InternalComment['referenceId'];
40614
- * }, response => merge(comments, response.data))
40522
+ * let posts = []
40523
+ * const unsubscribe = FeedRepository.getUserFeed({
40524
+ * userId: string,
40525
+ * feedSources: ['user', 'community'],
40526
+ * }, response => response => processResponse(response))
40615
40527
  * ```
40616
40528
  *
40617
- * Observe all mutations on a list of {@link Amity.InternalComment} for a given target object
40529
+ * Observe all mutations on a list of {@link Amity.Post} for a given user and feedSources
40618
40530
  *
40619
- * @param referenceType the type of the target
40620
- * @param referenceId the ID of the target
40531
+ * @param params.userId the ID of the user
40532
+ * @param params.feedSources the sources of the feed
40621
40533
  * @param callback the function to call when new data are available
40534
+ * @param config
40622
40535
  * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
40623
40536
  *
40624
- * @category Comments Live Collection
40537
+ * @category Posts Live Collection
40625
40538
  */
40626
- const getComments = (params, callback, config) => {
40539
+ const getUserFeed = (params, callback, config) => {
40627
40540
  const { log, cache } = getActiveClient();
40628
40541
  if (!cache) {
40629
- console.log('For using Live Collection feature you need to enable Cache!');
40542
+ console.log(ENABLE_CACHE_MESSAGE);
40630
40543
  }
40631
40544
  const timestamp = Date.now();
40632
- log(`getComments(tmpid: ${timestamp}) > listen`);
40633
- const commentsLiveCollection = new CommentLiveCollectionController(params, callback);
40634
- const disposers = commentsLiveCollection.startSubscription();
40635
- const cacheKey = commentsLiveCollection.getCacheKey();
40545
+ log(`getUserFeed(tmpid: ${timestamp}) > listen`);
40546
+ const userFeedLiveCollection = new UserFeedLiveCollectionController(params, callback);
40547
+ const disposers = userFeedLiveCollection.startSubscription();
40548
+ const cacheKey = userFeedLiveCollection.getCacheKey();
40636
40549
  disposers.push(() => dropFromCache(cacheKey));
40637
40550
  return () => {
40638
- log(`getComments(tmpid: ${timestamp}) > dispose`);
40551
+ log(`getUserFeed(tmpid: ${timestamp}) > dispose`);
40639
40552
  disposers.forEach(fn => fn());
40640
40553
  };
40641
40554
  };
@@ -40643,117 +40556,495 @@ const getComments = (params, callback, config) => {
40643
40556
 
40644
40557
  var index$9 = /*#__PURE__*/Object.freeze({
40645
40558
  __proto__: null,
40646
- getCommentByIds: getCommentByIds,
40647
- createComment: createComment,
40648
- updateComment: updateComment,
40649
- deleteComment: deleteComment,
40650
- softDeleteComment: softDeleteComment,
40651
- hardDeleteComment: hardDeleteComment,
40652
- flagComment: flagComment,
40653
- unflagComment: unflagComment,
40654
- isCommentFlaggedByMe: isCommentFlaggedByMe,
40655
- onCommentCreated: onCommentCreated,
40656
- onCommentUpdated: onCommentUpdated,
40657
- onCommentDeleted: onCommentDeleted,
40658
- onCommentFlagged: onCommentFlagged,
40659
- onCommentUnflagged: onCommentUnflagged,
40660
- onCommentReactionAdded: onCommentReactionAdded,
40661
- onCommentReactionRemoved: onCommentReactionRemoved,
40662
- getComment: getComment,
40663
- getComments: getComments
40559
+ queryGlobalFeed: queryGlobalFeed,
40560
+ getCustomRankingGlobalFeed: getCustomRankingGlobalFeed,
40561
+ getUserFeed: getUserFeed
40664
40562
  });
40665
40563
 
40564
+ /* begin_public_function
40565
+ id: post.get_by_ids
40566
+ */
40567
+ /**
40568
+ * ```js
40569
+ * import { getPostByIds } from '@amityco/ts-sdk'
40570
+ * const { data: posts } = await getPostByIds(['foo', 'bar'])
40571
+ * ```
40572
+ *
40573
+ * Fetches a collection of {@link Amity.Post} objects
40574
+ *
40575
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
40576
+ * @returns the associated collection of {@link Amity.Post} objects
40577
+ *
40578
+ * @category Post API
40579
+ * @async
40580
+ */
40581
+ const getPostByIds = async (postIds) => {
40582
+ const client = getActiveClient();
40583
+ client.log('post/getPostByIds', postIds);
40584
+ const encodedPostIds = postIds.map(postId => encodeURIComponent(postId));
40585
+ let payload;
40586
+ try {
40587
+ // API-FIX: endpoint should not be /list, parameters should be querystring.
40588
+ const response = await client.http.get(`/api/v3/posts/list`, {
40589
+ params: { postIds: encodedPostIds },
40590
+ });
40591
+ payload = response.data;
40592
+ }
40593
+ catch (error) {
40594
+ postIds.forEach(postId => {
40595
+ if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
40596
+ pushToTombstone('post', postId);
40597
+ }
40598
+ });
40599
+ throw error;
40600
+ }
40601
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40602
+ const cachedAt = client.cache && Date.now();
40603
+ if (client.cache)
40604
+ ingestInCache(data, { cachedAt });
40605
+ return {
40606
+ data: data.posts.map(LinkedObject.post),
40607
+ cachedAt,
40608
+ };
40609
+ };
40610
+ /* end_public_function */
40611
+ /**
40612
+ * ```js
40613
+ * import { getPostByIds } from '@amityco/ts-sdk'
40614
+ * const { data: posts } = getPostByIds.locally(['foo', 'bar'])
40615
+ * ```
40616
+ *
40617
+ * Fetches a collection of {@link Amity.Post} objects from cache
40618
+ *
40619
+ * @param postIds the IDs of the {@link Amity.Post} to fetch
40620
+ * @returns the associated collection of {@link Amity.Post} objects
40621
+ *
40622
+ * @category Post API
40623
+ */
40624
+ getPostByIds.locally = (postIds) => {
40625
+ var _a;
40626
+ const client = getActiveClient();
40627
+ client.log('post/getPostByIds.locally', postIds);
40628
+ if (!client.cache)
40629
+ return;
40630
+ const cached = postIds
40631
+ .map(postId => pullFromCache(['post', 'get', postId]))
40632
+ .filter(Boolean);
40633
+ const posts = cached.map(({ data }) => data);
40634
+ const oldest = (_a = cached.sort((a, b) => (a.cachedAt < b.cachedAt ? -1 : 1))) === null || _a === void 0 ? void 0 : _a[0];
40635
+ if ((cached === null || cached === void 0 ? void 0 : cached.length) < postIds.length)
40636
+ return;
40637
+ return {
40638
+ data: posts.map(LinkedObject.post),
40639
+ cachedAt: oldest.cachedAt,
40640
+ };
40641
+ };
40642
+
40643
+ /* begin_public_function
40644
+ 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
40645
+ */
40646
+ /**
40647
+ * ```js
40648
+ * import { PostRepository } from '@amityco/ts-sdk'
40649
+ * const created = await PostRepository.createPost({
40650
+ * targetType: 'user',
40651
+ * targetId: 'foobar',
40652
+ * data: { text: 'hello world' }
40653
+ * }))
40654
+ * ```
40655
+ *
40656
+ * Creates an {@link Amity.Post}
40657
+ *
40658
+ * @param bundle The data necessary to create a new {@link Amity.Post}
40659
+ * @returns The newly created {@link Amity.Post}
40660
+ *
40661
+ * @category Post API
40662
+ * @async
40663
+ */
40664
+ const createPost = async (bundle) => {
40665
+ const client = getActiveClient();
40666
+ client.log('post/createPost', bundle);
40667
+ if (!bundle.dataType || ['text', 'image', 'file', 'video'].includes(bundle.dataType)) {
40668
+ // eslint-disable-next-line no-param-reassign
40669
+ delete bundle.dataType;
40670
+ }
40671
+ const { data: payload } = await client.http.post('/api/v4/posts', bundle);
40672
+ fireEvent('post.created', payload);
40673
+ const data = preparePostPayload(payload);
40674
+ const cachedAt = client.cache && Date.now();
40675
+ if (client.cache)
40676
+ ingestInCache(data, { cachedAt });
40677
+ const { posts } = data;
40678
+ return {
40679
+ data: LinkedObject.post(posts[0]),
40680
+ cachedAt,
40681
+ };
40682
+ };
40683
+ /* end_public_function */
40684
+
40685
+ /* begin_public_function
40686
+ id: post.edit, post.edit.custom_post
40687
+ */
40688
+ /**
40689
+ * ```js
40690
+ * import { PostRepository } from '@amityco/ts-sdk'
40691
+ * const updated = await PostRepository.editPost(postId, {
40692
+ * data: { text: 'hello world' }
40693
+ * })
40694
+ * ```
40695
+ *
40696
+ * Updates an {@link Amity.Post}
40697
+ *
40698
+ * @param postId The ID of the {@link Amity.Post} to edit
40699
+ * @param patch The patch data to apply
40700
+ * @returns the updated {@link Amity.Post} object
40701
+ *
40702
+ * @category Post API
40703
+ * @async
40704
+ */
40705
+ const editPost = async (postId, patch) => {
40706
+ const client = getActiveClient();
40707
+ client.log('user/editPost', patch);
40708
+ const { data: payload } = await client.http.put(`/api/v4/posts/${encodeURIComponent(postId)}`, patch);
40709
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40710
+ const cachedAt = client.cache && Date.now();
40711
+ if (client.cache)
40712
+ ingestInCache(data, { cachedAt });
40713
+ fireEvent('local.post.updated', data);
40714
+ const { posts } = data;
40715
+ return {
40716
+ data: LinkedObject.post(posts.find(post => post.postId === postId)),
40717
+ cachedAt,
40718
+ };
40719
+ };
40720
+ /* end_public_function */
40721
+
40722
+ /**
40723
+ * ```js
40724
+ * import { deletePost } from '@amityco/ts-sdk'
40725
+ * const success = await deletePost('foobar')
40726
+ * ```
40727
+ *
40728
+ * Deletes a {@link Amity.Post}
40729
+ *
40730
+ * @param postId The {@link Amity.Post} ID to delete
40731
+ * @return A success boolean if the {@link Amity.Post} was deleted
40732
+ *
40733
+ * @private
40734
+ * @async
40735
+ */
40736
+ const deletePost = async (postId, permanent = false) => {
40737
+ var _a;
40738
+ const client = getActiveClient();
40739
+ const post = await getPost$2(postId);
40740
+ await client.http.delete(`/api/v4/posts/${encodeURIComponent(postId)}`, {
40741
+ params: {
40742
+ postId,
40743
+ permanent,
40744
+ },
40745
+ });
40746
+ // there is currently a limitation which doesn't allow us to fire event to tell that community
40747
+ // has been updated. reason is that, when the object is deleted, we don't have its `communityId`
40748
+ // and so we cannot refetch the community or advertise on events. hopefully this should be solved
40749
+ // later when realtime events covers that for us.
40750
+ if (post.data.targetType === 'community') {
40751
+ const community = await getCommunity$1(post.data.targetId);
40752
+ const communityUsersCache = (_a = queryCache(['communityUsers', 'get'])) !== null && _a !== void 0 ? _a : [];
40753
+ const communityUsers = communityUsersCache
40754
+ .filter(({ key }) => {
40755
+ // cache key is ['communityUsers', 'get', `${communityId}#`${userId}`}]
40756
+ if (key[0] !== 'communityUsers')
40757
+ return false;
40758
+ if (key[1] !== 'get')
40759
+ return false;
40760
+ if (typeof key[2] === 'string')
40761
+ return key[2].includes(community.data.communityId);
40762
+ return false;
40763
+ })
40764
+ .map(({ data }) => data);
40765
+ fireEvent('community.updated', {
40766
+ communities: [community.data],
40767
+ categories: [],
40768
+ communityUsers,
40769
+ feeds: [],
40770
+ files: [],
40771
+ users: [],
40772
+ });
40773
+ }
40774
+ // to support hard deletion
40775
+ const deleted = Object.assign(Object.assign({}, post.data), { isDeleted: true });
40776
+ if (permanent) {
40777
+ setTimeout(() => {
40778
+ pushToTombstone('post', postId);
40779
+ }, 0);
40780
+ }
40781
+ else {
40782
+ upsertInCache(['post', 'get', postId], { isDeleted: true });
40783
+ }
40784
+ fireEvent('local.post.deleted', {
40785
+ posts: [deleted],
40786
+ categories: [],
40787
+ comments: [],
40788
+ communities: [],
40789
+ communityUsers: [],
40790
+ feeds: [],
40791
+ files: [],
40792
+ postChildren: [],
40793
+ users: [],
40794
+ videoStreamings: [],
40795
+ });
40796
+ return LinkedObject.post(deleted);
40797
+ };
40798
+
40799
+ /* begin_public_function
40800
+ id: post.soft_delete
40801
+ */
40802
+ /**
40803
+ * ```js
40804
+ * import { PostRepository } from '@amityco/ts-sdk'
40805
+ * const success = await PostRepository.softDeletePost('foobar')
40806
+ * ```
40807
+ *
40808
+ * Soft deletes a {@link Amity.Post}
40809
+ *
40810
+ * @param postId The {@link Amity.Post} ID to soft delete
40811
+ * @return A success boolean if the {@link Amity.Post} was deleted
40812
+ *
40813
+ * @category Post API
40814
+ * @async
40815
+ */
40816
+ const softDeletePost = async (postId) => {
40817
+ const client = getActiveClient();
40818
+ client.log('post/softDeletePost', postId);
40819
+ const softDeleted = await deletePost(postId, false);
40820
+ return LinkedObject.post(softDeleted);
40821
+ };
40822
+ /* end_public_function */
40823
+
40824
+ /* begin_public_function
40825
+ id: post.hard_delete
40826
+ */
40827
+ /**
40828
+ * ```js
40829
+ * import { hardDeletePost } from '@amityco/ts-sdk'
40830
+ * const success = await hardDeletePost('foobar')
40831
+ * ```
40832
+ *
40833
+ * Hard deletes a {@link Amity.Post}
40834
+ *
40835
+ * @param postId The {@link Amity.Post} ID to be hard delete
40836
+ * @return A success boolean if the {@link Amity.Post} was deleted
40837
+ *
40838
+ * @category Post API
40839
+ * @async
40840
+ */
40841
+ const hardDeletePost = async (postId) => {
40842
+ const client = getActiveClient();
40843
+ client.log('post/hardDeletePost', postId);
40844
+ const hardDeleted = await deletePost(postId, true);
40845
+ return LinkedObject.post(hardDeleted);
40846
+ };
40847
+ /* end_public_function */
40848
+
40849
+ /* begin_public_function
40850
+ id: post.approve
40851
+ */
40852
+ /**
40853
+ * ```js
40854
+ * import { approvePost } from '@amityco/ts-sdk'
40855
+ *
40856
+ * const { data: post } = await approvePost('postId')
40857
+ * ```
40858
+ *
40859
+ * Approves a {@link Amity.Post}
40860
+ *
40861
+ * @param postId The {@link Amity.Post} ID to be approved
40862
+ * @return A {@link Amity.Post} that was approved
40863
+ *
40864
+ * @category Post API
40865
+ * @async
40866
+ */
40867
+ const approvePost = async (postId) => {
40868
+ const client = getActiveClient();
40869
+ client.log('post/approvePost', postId);
40870
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/approve`);
40871
+ fireEvent('post.approved', payload);
40872
+ // fire virtual event for community update
40873
+ if (payload.posts[0].targetType === 'community') {
40874
+ fireEvent('community.updated', payload);
40875
+ }
40876
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40877
+ const cachedAt = client.cache && Date.now();
40878
+ if (client.cache)
40879
+ ingestInCache(data, { cachedAt });
40880
+ return {
40881
+ data: LinkedObject.post(data.posts.find(post => post.postId === postId)),
40882
+ cachedAt,
40883
+ };
40884
+ };
40885
+ /* end_public_function */
40886
+
40887
+ /* begin_public_function
40888
+ id: post.decline
40889
+ */
40666
40890
  /**
40667
40891
  * ```js
40668
- * import { onPostUpdatedLocal } from '@amityco/ts-sdk'
40669
- * const dispose = onPostUpdatedLocal(post => {
40670
- * // ...
40671
- * })
40892
+ * import { declinePost } from '@amityco/ts-sdk'
40893
+ *
40894
+ * const {data: post} = await declinePost('postId')
40672
40895
  * ```
40673
40896
  *
40674
- * Fired when a {@link Amity.InternalPost} has been updated
40897
+ * Declines a {@link Amity.Post}
40675
40898
  *
40676
- * @param callback The function to call when the event was fired
40677
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40899
+ * @param postId The {@link Amity.Post} ID to be declined
40900
+ * @return A {@link Amity.Post} that was declined
40678
40901
  *
40679
- * @category Post Events
40902
+ * @category Post API
40903
+ * @async
40680
40904
  */
40681
- const onPostUpdatedLocal = (callback) => createLocalPostEventSubscriber('local.post.updated', callback);
40905
+ const declinePost = async (postId) => {
40906
+ const client = getActiveClient();
40907
+ client.log('post/declinePost', postId);
40908
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/decline`);
40909
+ // fire virtual event
40910
+ if (payload.posts[0].targetType === 'community') {
40911
+ fireEvent('community.updated', payload);
40912
+ }
40913
+ fireEvent('post.declined', payload);
40914
+ const data = prepareMembershipPayload(payload, 'communityUsers');
40915
+ const cachedAt = client.cache && Date.now();
40916
+ if (client.cache)
40917
+ ingestInCache(data, { cachedAt });
40918
+ return {
40919
+ data: LinkedObject.post(payload.posts.find(post => post.postId === postId)),
40920
+ cachedAt,
40921
+ };
40922
+ };
40923
+ /* end_public_function */
40682
40924
 
40925
+ /* begin_public_function
40926
+ id: post.flag
40927
+ */
40683
40928
  /**
40684
40929
  * ```js
40685
- * import { onLocalPostReactionAdded } from '@amityco/ts-sdk'
40686
- * const dispose = onPostReactionAdded(post => {
40687
- * // ...
40688
- * })
40930
+ * import { PostRepository } from '@amityco/ts-sdk'
40931
+ * const flagged = await PostRepository.flagPost(postId, reason)
40689
40932
  * ```
40690
40933
  *
40691
- * Fired when a {@link Amity.InternalPost} has been reacted
40692
- *
40693
- * @param callback The function to call when the event was fired
40694
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40934
+ * @param postId of the post to flag
40935
+ * @param reason the reason to flag the post
40936
+ * @returns a boolean
40695
40937
  *
40696
- * @category Post Events
40697
- */
40698
- const onLocalPostReactionAdded = (callback) => {
40938
+ * @category Post API
40939
+ * @async
40940
+ * */
40941
+ const flagPost = async (postId, reason) => {
40699
40942
  const client = getActiveClient();
40700
- const filter = ({ post }) => {
40701
- if (!client.cache) {
40702
- callback(post);
40703
- }
40704
- else {
40705
- upsertInCache(['post', 'get', post.postId], post);
40706
- callback(post);
40707
- }
40943
+ client.log('post/flagPost', postId);
40944
+ const isPredefinedReason = reason &&
40945
+ Object.entries(ContentFlagReasonEnum).some(([key, value]) => key !== ContentFlagReasonEnum.Others && value === reason);
40946
+ const body = {
40947
+ reason: reason && isPredefinedReason ? reason : ContentFlagReasonEnum.Others,
40948
+ detail: reason && !isPredefinedReason ? reason : '',
40708
40949
  };
40709
- return createEventSubscriber(client, 'local.post.addReaction', 'local.post.addReaction', filter);
40950
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/flag`, body);
40951
+ if (client.cache) {
40952
+ ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
40953
+ }
40954
+ fireEvent('post.flagged', payload);
40955
+ return !!payload;
40710
40956
  };
40957
+ /* end_public_function */
40711
40958
 
40959
+ /* begin_public_function
40960
+ id: post.unflag
40961
+ */
40712
40962
  /**
40713
40963
  * ```js
40714
- * import { onLocalPostReactionRemoved } from '@amityco/ts-sdk'
40715
- * const dispose = onPostReactionRemoved(post => {
40716
- * // ...
40717
- * })
40964
+ * import { PostRepository } from '@amityco/ts-sdk'
40965
+ * const unflagged = await PostRepository.unflagPost(postId)
40718
40966
  * ```
40719
40967
  *
40720
- * Fired when a {@link Amity.InternalPost} has been reacted
40968
+ * @param postId of the post to unflag
40969
+ * @returns the unflag post result
40721
40970
  *
40722
- * @param callback The function to call when the event was fired
40723
- * @returns an {@link Amity.Unsubscriber} function to stop listening
40971
+ * @category Post API
40972
+ * @async
40973
+ * */
40974
+ const unflagPost = async (postId) => {
40975
+ const client = getActiveClient();
40976
+ client.log('post/unflagPost', postId);
40977
+ const { data: payload } = await client.http.delete(`/api/v3/posts/${encodeURIComponent(postId)}/unflag`);
40978
+ if (client.cache) {
40979
+ ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
40980
+ }
40981
+ fireEvent('post.unflagged', payload);
40982
+ return !!payload;
40983
+ };
40984
+ /* end_public_function */
40985
+
40986
+ /* begin_public_function
40987
+ id: post.check_flag_by_me
40988
+ */
40989
+ /**
40990
+ * ```js
40991
+ * import { PostRepository } from '@amityco/ts-sdk'
40992
+ * const isReported = await PostRepository.isPostFlaggedByMe('post', postId)
40993
+ * ```
40724
40994
  *
40725
- * @category Post Events
40726
- */
40727
- const onLocalPostReactionRemoved = (callback) => {
40995
+ * @param postId of the post to check if flagged by current user
40996
+ * @returns `true` if the post is flagged by me, `false` if doesn't.
40997
+ *
40998
+ * @category Post API
40999
+ * @async
41000
+ * */
41001
+ const isPostFlaggedByMe = async (postId) => {
40728
41002
  const client = getActiveClient();
40729
- const filter = ({ post }) => {
40730
- if (!client.cache) {
40731
- callback(post);
40732
- }
40733
- else {
40734
- upsertInCache(['post', 'get', post.postId], post);
40735
- callback(post);
40736
- }
40737
- };
40738
- return createEventSubscriber(client, 'local.post.removeReaction', 'local.post.removeReaction', filter);
41003
+ client.log('post/isPostFlaggedByMe', postId);
41004
+ const { data: { result }, } = await client.http.get(`/api/v3/posts/${postId}/isflagbyme`);
41005
+ return result;
40739
41006
  };
41007
+ /* end_public_function */
40740
41008
 
41009
+ /* begin_public_function
41010
+ id: post.create.clip_post
41011
+ */
40741
41012
  /**
40742
41013
  * ```js
40743
- * import { onLocalPostDeleted } from '@amityco/ts-sdk'
40744
- * const dispose = onLocalPostDeleted(post => {
40745
- * // ...
40746
- * })
41014
+ * import { PostRepository } from '@amityco/ts-sdk'
41015
+ * const created = await PostRepository.createClipPost({
41016
+ * targetType: 'user',
41017
+ * targetId: 'foobar',
41018
+ * dataType: 'clip',
41019
+ * data: { text: 'hello world' },
41020
+ * attachments: [{ type: 'clip', fileId: 'fileId123', displayMode: 'fill', isMuted: false }]
41021
+ * }))
40747
41022
  * ```
40748
41023
  *
40749
- * Fired when a {@link Amity.InternalPost} has been deleted
41024
+ * Creates an {@link Amity.Post}
40750
41025
  *
40751
- * @param callback The function to call when the event was fired
40752
- * @returns an {@link Amity.Unsubscriber} function to stop listening
41026
+ * @param bundle The data necessary to create a new {@link Amity.Post}
41027
+ * @returns The newly created {@link Amity.Post}
40753
41028
  *
40754
- * @category Post Events
41029
+ * @category Post API
41030
+ * @async
40755
41031
  */
40756
- const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.post.deleted', callback);
41032
+ const createClipPost = async (bundle) => {
41033
+ const client = getActiveClient();
41034
+ client.log('post/createPost', bundle);
41035
+ const { data: payload } = await client.http.post('/api/v4/posts', bundle);
41036
+ fireEvent('post.created', payload);
41037
+ const data = prepareMembershipPayload(payload, 'communityUsers');
41038
+ const cachedAt = client.cache && Date.now();
41039
+ if (client.cache)
41040
+ ingestInCache(data, { cachedAt });
41041
+ const { posts } = data;
41042
+ return {
41043
+ data: LinkedObject.post(posts[0]),
41044
+ cachedAt,
41045
+ };
41046
+ };
41047
+ /* end_public_function */
40757
41048
 
40758
41049
  /* begin_public_function
40759
41050
  id: post.get
@@ -40777,7 +41068,7 @@ const onLocalPostDeleted = (callback) => createLocalPostEventSubscriber('local.p
40777
41068
  *
40778
41069
  * @category Post Live Object
40779
41070
  */
40780
- const getPost$1 = (postId, callback) => {
41071
+ const getPost = (postId, callback) => {
40781
41072
  const responder = (snapshot) => {
40782
41073
  const { data } = snapshot;
40783
41074
  callback(Object.assign(Object.assign({}, snapshot), { data: data ? LinkedObject.post(snapshot.data) : data }));
@@ -40866,19 +41157,6 @@ class PostPaginationController extends PaginationController {
40866
41157
  }
40867
41158
  }
40868
41159
 
40869
- var EnumPostActions;
40870
- (function (EnumPostActions) {
40871
- EnumPostActions["OnPostCreated"] = "onPostCreated";
40872
- EnumPostActions["OnPostUpdated"] = "onPostUpdated";
40873
- EnumPostActions["OnPostDeleted"] = "onPostDeleted";
40874
- EnumPostActions["OnPostFlagged"] = "onPostFlagged";
40875
- EnumPostActions["OnPostUnflagged"] = "onPostUnflagged";
40876
- EnumPostActions["OnPostReactionAdded"] = "onPostReactionAdded";
40877
- EnumPostActions["OnPostReactionRemoved"] = "onPostReactionRemoved";
40878
- EnumPostActions["OnPostApproved"] = "onPostApproved";
40879
- EnumPostActions["OnPostDeclined"] = "onPostDeclined";
40880
- })(EnumPostActions || (EnumPostActions = {}));
40881
-
40882
41160
  class PostQueryStreamController extends QueryStreamController {
40883
41161
  constructor(query, cacheKey, notifyChange, preparePayload) {
40884
41162
  super(query, cacheKey);
@@ -40944,47 +41222,6 @@ class PostQueryStreamController extends QueryStreamController {
40944
41222
  }
40945
41223
  }
40946
41224
 
40947
- const getPost = async (postId) => {
40948
- const client = getActiveClient();
40949
- client.log('post/getPost', postId);
40950
- isInTombstone('post', postId);
40951
- let payload;
40952
- try {
40953
- // API-FIX: endpoint should not be /list, parameters should be querystring.
40954
- const response = await client.http.get(`/api/v3/posts/${encodeURIComponent(postId)}`);
40955
- payload = response.data;
40956
- }
40957
- catch (error) {
40958
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
40959
- pushToTombstone('post', postId);
40960
- }
40961
- throw error;
40962
- }
40963
- const data = prepareMembershipPayload(payload, 'communityUsers');
40964
- const cachedAt = client.cache && Date.now();
40965
- if (client.cache)
40966
- ingestInCache(data, { cachedAt });
40967
- const { posts } = data;
40968
- const result = posts.find(post => post.postId === postId);
40969
- return {
40970
- data: result,
40971
- cachedAt,
40972
- };
40973
- };
40974
- getPost.locally = (postId) => {
40975
- const client = getActiveClient();
40976
- client.log('post/getPost.locally', postId);
40977
- if (!client.cache)
40978
- return;
40979
- const cached = pullFromCache(['post', 'get', postId]);
40980
- if (!cached)
40981
- return;
40982
- return {
40983
- data: cached.data,
40984
- cachedAt: cached.cachedAt,
40985
- };
40986
- };
40987
-
40988
41225
  class PostLiveCollectionController extends LiveCollectionController {
40989
41226
  constructor(query, callback) {
40990
41227
  const queryStreamId = hash(query);
@@ -41034,7 +41271,7 @@ class PostLiveCollectionController extends LiveCollectionController {
41034
41271
  const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
41035
41272
  if (!currentCollection || currentCollection.data.includes(comment.referenceId))
41036
41273
  return;
41037
- await getPost(comment.referenceId);
41274
+ await getPost$1(comment.referenceId);
41038
41275
  callback(comment);
41039
41276
  });
41040
41277
  }, 'referenceId', 'post'),
@@ -41047,7 +41284,7 @@ class PostLiveCollectionController extends LiveCollectionController {
41047
41284
  const currentCollection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
41048
41285
  if (!currentCollection || currentCollection.data.includes(comment.referenceId))
41049
41286
  return;
41050
- await getPost(comment.referenceId);
41287
+ await getPost$1(comment.referenceId);
41051
41288
  callback(comment);
41052
41289
  });
41053
41290
  }, 'referenceId', 'post'),
@@ -41673,7 +41910,7 @@ var index$8 = /*#__PURE__*/Object.freeze({
41673
41910
  onPostUnflagged: onPostUnflagged,
41674
41911
  onPostReactionAdded: onPostReactionAdded,
41675
41912
  onPostReactionRemoved: onPostReactionRemoved,
41676
- getPost: getPost$1,
41913
+ getPost: getPost,
41677
41914
  getPosts: getPosts,
41678
41915
  getPinnedPosts: getPinnedPosts,
41679
41916
  getGlobalPinnedPosts: getGlobalPinnedPosts,
@@ -44874,4 +45111,4 @@ var index = /*#__PURE__*/Object.freeze({
44874
45111
  getReactions: getReactions
44875
45112
  });
44876
45113
 
44877
- export { API_REGIONS, index$3 as AdRepository, index$b as CategoryRepository, index$f as ChannelRepository, index$o as Client, index$9 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$c as CommunityRepository, ContentFeedType, ContentFlagReasonEnum, DefaultCommunityPostSetting, index$a as FeedRepository, FileAccessTypeEnum, index$l as FileRepository, FileType, index$1 as InvitationRepository, InvitationSortByEnum, InvitationStatusEnum, InvitationTypeEnum, JoinRequestStatusEnum, JoinResultStatusEnum, index as LiveReactionRepository, index$5 as LiveStreamPlayer, MembershipAcceptanceTypeEnum, MessageContentType, index$j as MessageRepository, index$6 as PollRepository, PostContentType, index$8 as PostRepository, index$k as ReactionRepository, index$4 as StoryRepository, index$7 as StreamRepository, index$i as SubChannelRepository, SubscriptionLevels, index$m as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveReactionTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, index$2 as notificationTray, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };
45114
+ export { API_REGIONS, index$3 as AdRepository, index$b as CategoryRepository, index$f as ChannelRepository, index$o as Client, index$a as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$c as CommunityRepository, ContentFeedType, ContentFlagReasonEnum, DefaultCommunityPostSetting, index$9 as FeedRepository, FileAccessTypeEnum, index$l as FileRepository, FileType, index$1 as InvitationRepository, InvitationSortByEnum, InvitationStatusEnum, InvitationTypeEnum, JoinRequestStatusEnum, JoinResultStatusEnum, index as LiveReactionRepository, index$5 as LiveStreamPlayer, MembershipAcceptanceTypeEnum, MessageContentType, index$j as MessageRepository, index$6 as PollRepository, PostContentType, index$8 as PostRepository, index$k as ReactionRepository, index$4 as StoryRepository, index$7 as StreamRepository, index$i as SubChannelRepository, SubscriptionLevels, index$m as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getLiveReactionTopic, getLiveStreamTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, index$2 as notificationTray, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };