@amityco/ts-sdk 7.7.1-1cf499d.0 → 7.7.1-47be9e51.0

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