@amityco/ts-sdk 7.7.1-3f344102.0 → 7.7.1-47be9e51.0

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