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