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