@amityco/ts-sdk 0.0.1-beta.22 → 0.0.1-beta.25

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 (81) hide show
  1. package/dist/@types/core/events.d.ts +5 -1
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/domains/channel.d.ts +1 -2
  4. package/dist/@types/domains/channel.d.ts.map +1 -1
  5. package/dist/@types/domains/reaction.d.ts +1 -1
  6. package/dist/@types/domains/reaction.d.ts.map +1 -1
  7. package/dist/channel/api/queryChannelMembers.d.ts +2 -1
  8. package/dist/channel/api/queryChannelMembers.d.ts.map +1 -1
  9. package/dist/channel/api/updateChannel.d.ts +1 -1
  10. package/dist/channel/api/updateChannel.d.ts.map +1 -1
  11. package/dist/client/api/connectClient.d.ts +3 -1
  12. package/dist/client/api/connectClient.d.ts.map +1 -1
  13. package/dist/comment/api/queryComments.d.ts +1 -0
  14. package/dist/comment/api/queryComments.d.ts.map +1 -1
  15. package/dist/core/events.d.ts +3 -3
  16. package/dist/core/events.d.ts.map +1 -1
  17. package/dist/core/model/identifyModel.d.ts +1 -0
  18. package/dist/core/model/identifyModel.d.ts.map +1 -1
  19. package/dist/core/query/query.d.ts.map +1 -1
  20. package/dist/index.cjs.js +381 -67
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.esm.js +376 -68
  24. package/dist/index.umd.js +5 -5
  25. package/dist/message/api/createMessage.d.ts.map +1 -1
  26. package/dist/message/events/onMessageUpdated.d.ts.map +1 -1
  27. package/dist/poll/api/closePoll.d.ts.map +1 -1
  28. package/dist/poll/api/deletePoll.d.ts.map +1 -1
  29. package/dist/poll/api/votePoll.d.ts.map +1 -1
  30. package/dist/poll/events/index.d.ts +3 -0
  31. package/dist/poll/events/index.d.ts.map +1 -0
  32. package/dist/poll/events/onPollDeleted.d.ts +17 -0
  33. package/dist/poll/events/onPollDeleted.d.ts.map +1 -0
  34. package/dist/poll/events/onPollUpdated.d.ts +17 -0
  35. package/dist/poll/events/onPollUpdated.d.ts.map +1 -0
  36. package/dist/poll/observers/index.d.ts +2 -0
  37. package/dist/poll/observers/index.d.ts.map +1 -0
  38. package/dist/poll/observers/observePoll.d.ts +18 -0
  39. package/dist/poll/observers/observePoll.d.ts.map +1 -0
  40. package/dist/post/api/approvePost.d.ts +17 -0
  41. package/dist/post/api/approvePost.d.ts.map +1 -0
  42. package/dist/post/api/declinePost.d.ts +17 -0
  43. package/dist/post/api/declinePost.d.ts.map +1 -0
  44. package/dist/post/api/index.d.ts +2 -0
  45. package/dist/post/api/index.d.ts.map +1 -1
  46. package/dist/reaction/events/onReactionAdded.d.ts.map +1 -1
  47. package/dist/reaction/utils/index.d.ts +1 -0
  48. package/dist/reaction/utils/index.d.ts.map +1 -1
  49. package/dist/reaction/utils/prepareMessagePayloadForCache.d.ts +3 -0
  50. package/dist/reaction/utils/prepareMessagePayloadForCache.d.ts.map +1 -0
  51. package/dist/report/api/createReport.d.ts.map +1 -1
  52. package/dist/report/api/deleteReport.d.ts.map +1 -1
  53. package/package.json +1 -1
  54. package/src/@types/core/events.ts +6 -1
  55. package/src/@types/domains/channel.ts +1 -2
  56. package/src/@types/domains/reaction.ts +1 -1
  57. package/src/channel/api/queryChannelMembers.ts +4 -4
  58. package/src/channel/api/updateChannel.ts +1 -1
  59. package/src/client/api/connectClient.ts +12 -7
  60. package/src/comment/api/queryComments.ts +6 -3
  61. package/src/core/model/identifyModel.ts +18 -0
  62. package/src/core/query/query.ts +19 -1
  63. package/src/index.ts +2 -0
  64. package/src/message/api/createMessage.ts +22 -6
  65. package/src/message/events/onMessageUpdated.ts +9 -1
  66. package/src/poll/api/closePoll.ts +3 -0
  67. package/src/poll/api/deletePoll.ts +3 -0
  68. package/src/poll/api/votePoll.ts +3 -0
  69. package/src/poll/events/index.ts +2 -0
  70. package/src/poll/events/onPollDeleted.ts +31 -0
  71. package/src/poll/events/onPollUpdated.ts +31 -0
  72. package/src/poll/observers/index.ts +1 -0
  73. package/src/poll/observers/observePoll.ts +67 -0
  74. package/src/post/api/approvePost.ts +48 -0
  75. package/src/post/api/declinePost.ts +48 -0
  76. package/src/post/api/index.ts +3 -0
  77. package/src/reaction/events/onReactionAdded.ts +4 -0
  78. package/src/reaction/utils/index.ts +1 -0
  79. package/src/reaction/utils/prepareMessagePayloadForCache.ts +40 -0
  80. package/src/report/api/createReport.ts +7 -1
  81. package/src/report/api/deleteReport.ts +7 -1
package/dist/index.cjs.js CHANGED
@@ -9,6 +9,7 @@ var debug = require('debug');
9
9
  var axios = require('axios');
10
10
  var HttpAgent = require('agentkeepalive');
11
11
  var io = require('socket.io-client');
12
+ var nativeIdGenerator = require('react-native-uuid');
12
13
 
13
14
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
15
 
@@ -18,6 +19,7 @@ var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug);
18
19
  var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
19
20
  var HttpAgent__default = /*#__PURE__*/_interopDefaultLegacy(HttpAgent);
20
21
  var io__default = /*#__PURE__*/_interopDefaultLegacy(io);
22
+ var nativeIdGenerator__default = /*#__PURE__*/_interopDefaultLegacy(nativeIdGenerator);
21
23
 
22
24
  var _a$1;
23
25
  /* eslint-disable no-undef */
@@ -179,6 +181,121 @@ const toPageRaw = (token) => {
179
181
  return undefined;
180
182
  };
181
183
 
184
+ /** @hidden */
185
+ const idResolvers = {
186
+ user: ({ userId }) => userId,
187
+ file: ({ fileId }) => fileId,
188
+ role: ({ roleId }) => roleId,
189
+ channel: ({ channelId }) => channelId,
190
+ channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
191
+ message: ({ messageId }) => messageId,
192
+ community: ({ communityId }) => communityId,
193
+ category: ({ categoryId }) => categoryId,
194
+ communityUsers: ({ communityId, userId }) => `${communityId}#${userId}`,
195
+ post: ({ postId }) => postId,
196
+ comment: ({ commentId }) => commentId,
197
+ poll: ({ pollId }) => pollId,
198
+ reaction: ({ reactionId }) => reactionId,
199
+ stream: ({ streamId }) => streamId,
200
+ follow: ({ from, to }) => `${from}#${to}`,
201
+ followCount: ({ userId }) => userId,
202
+ };
203
+ /**
204
+ * Retrieve the id resolver matching a domain name
205
+ *
206
+ * @param name the domain name for the resolve
207
+ * @returns an idResolver function for the given domain name
208
+ */
209
+ const getResolver = (name) => idResolvers[name];
210
+
211
+ /**
212
+ * Identification criterias
213
+ *
214
+ * As key, the name of the identified model ;
215
+ * As value, the list of properties to consider a given model as of type
216
+ *
217
+ * Used as source of truth for {@link identifyModel}
218
+ *
219
+ * @hidden
220
+ */
221
+ const CRITERIAS = {
222
+ file: ['fileId', 'attributes'],
223
+ user: ['userId', 'avatarFileId'],
224
+ role: ['roleId'],
225
+ channel: ['channelId', 'rateLimit'],
226
+ channelUsers: ['channelId', 'userId', 'membership'],
227
+ message: ['messageId'],
228
+ community: ['communityId', 'onlyAdminCanPost'],
229
+ category: ['categoryId'],
230
+ communityUsers: ['userId', 'communityId', 'communityMembership'],
231
+ post: ['postId', 'feedId'],
232
+ comment: ['commentId', 'referenceId'],
233
+ poll: ['pollId'],
234
+ reaction: ['reactionId'],
235
+ stream: ['streamId'],
236
+ follow: ['from', 'to'],
237
+ followCount: ['userId', 'followerCount'],
238
+ };
239
+ /** @hidden */
240
+ const hasKeys = (object, needles) => {
241
+ const haystack = Object.keys(object);
242
+ return needles.every(needle => haystack.includes(needle));
243
+ };
244
+ /**
245
+ * Finds the name of the store for a given unknown model
246
+ *
247
+ * @param model one of the {@link Amity.Model} to identify
248
+ * @returns the name of the corresponding store
249
+ */
250
+ const identifyModel = (model) => {
251
+ var _a;
252
+ // we cannot avoid "as" in here because Object.entries does not
253
+ // allow anything else than "string" as key in the iterator type
254
+ const criterias = Object.entries(CRITERIAS);
255
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
256
+ return (_a = criterias.find(([_, keys]) => hasKeys(model, keys))) === null || _a === void 0 ? void 0 : _a[0];
257
+ };
258
+ /*
259
+ * Identify the modal key for a model
260
+ * Used to get args for optimistic updates
261
+ * Example: createMessage: get messageId on optimistic message creation
262
+ *
263
+ * @param model to be recognized
264
+ * @returns model key array if one if found or undefined
265
+ */
266
+ const identifyModelKey = (model) => {
267
+ var _a;
268
+ const modalKey = identifyModel(model);
269
+ if (!modalKey) {
270
+ return undefined;
271
+ }
272
+ return (_a = CRITERIAS[modalKey]) === null || _a === void 0 ? void 0 : _a[0];
273
+ };
274
+
275
+ /**
276
+ * A map of v3 response keys to a store name.
277
+ * @hidden
278
+ */
279
+ const PAYLOAD2MODEL = {
280
+ users: 'user',
281
+ files: 'file',
282
+ roles: 'role',
283
+ channels: 'channel',
284
+ channelUsers: 'channelUsers',
285
+ messages: 'message',
286
+ communities: 'community',
287
+ categories: 'category',
288
+ communityUsers: 'communityUsers',
289
+ posts: 'post',
290
+ postChildren: 'post',
291
+ comments: 'comment',
292
+ polls: 'poll',
293
+ reactions: 'reaction',
294
+ videoStreamings: 'stream',
295
+ follows: 'follow',
296
+ followCounts: 'followCount',
297
+ };
298
+
182
299
  /* eslint-disable no-use-before-define */
183
300
  /**
184
301
  * Type guard to check and cast that a given async function is has the ".locally" property
@@ -323,7 +440,23 @@ const runQuery = ({ func, args }, callback, options = queryOptions('cache_then_s
323
440
  loading: true,
324
441
  }));
325
442
  }
326
- func(...args)
443
+ let optimisticArgs = args;
444
+ /* get args for optimistic method calls
445
+ *
446
+ * On optimistic updates, the modal key for the update needs to be passed to
447
+ * the server so as to avoid duplicate modal creation
448
+ *
449
+ * ex: on creating a new message pass the modalKey is messageId, pass this
450
+ * id onto the server so that a duplicate with seperate messageId is not
451
+ * created.
452
+ */
453
+ if (isMutator(func)) {
454
+ // @ts-ignore
455
+ const modelKey = local && local.data && identifyModelKey(local.data);
456
+ // @ts-ignore
457
+ optimisticArgs = modelKey ? [...args, { [modelKey]: local.data[modelKey] }] : args;
458
+ }
459
+ func(...optimisticArgs)
327
460
  .then(fresh => {
328
461
  // @ts-ignore i know.
329
462
  // isLocal(local) && syncInCache(local, fresh)
@@ -20216,57 +20349,6 @@ const onClientBanned = (callback) => {
20216
20349
  });
20217
20350
  };
20218
20351
 
20219
- /** @hidden */
20220
- const idResolvers = {
20221
- user: ({ userId }) => userId,
20222
- file: ({ fileId }) => fileId,
20223
- role: ({ roleId }) => roleId,
20224
- channel: ({ channelId }) => channelId,
20225
- channelUsers: ({ channelId, userId }) => `${channelId}#${userId}`,
20226
- message: ({ messageId }) => messageId,
20227
- community: ({ communityId }) => communityId,
20228
- category: ({ categoryId }) => categoryId,
20229
- communityUsers: ({ communityId, userId }) => `${communityId}#${userId}`,
20230
- post: ({ postId }) => postId,
20231
- comment: ({ commentId }) => commentId,
20232
- poll: ({ pollId }) => pollId,
20233
- reaction: ({ reactionId }) => reactionId,
20234
- stream: ({ streamId }) => streamId,
20235
- follow: ({ from, to }) => `${from}#${to}`,
20236
- followCount: ({ userId }) => userId,
20237
- };
20238
- /**
20239
- * Retrieve the id resolver matching a domain name
20240
- *
20241
- * @param name the domain name for the resolve
20242
- * @returns an idResolver function for the given domain name
20243
- */
20244
- const getResolver = (name) => idResolvers[name];
20245
-
20246
- /**
20247
- * A map of v3 response keys to a store name.
20248
- * @hidden
20249
- */
20250
- const PAYLOAD2MODEL = {
20251
- users: 'user',
20252
- files: 'file',
20253
- roles: 'role',
20254
- channels: 'channel',
20255
- channelUsers: 'channelUsers',
20256
- messages: 'message',
20257
- communities: 'community',
20258
- categories: 'category',
20259
- communityUsers: 'communityUsers',
20260
- posts: 'post',
20261
- postChildren: 'post',
20262
- comments: 'comment',
20263
- polls: 'poll',
20264
- reactions: 'reaction',
20265
- videoStreamings: 'stream',
20266
- follows: 'follow',
20267
- followCounts: 'followCount',
20268
- };
20269
-
20270
20352
  /**
20271
20353
  * Ingest a payload (v3) into the cache
20272
20354
  *
@@ -20340,7 +20422,7 @@ const onUserDeleted = (callback) => createUserEventSubscriber('user.deleted', ca
20340
20422
  * @category Client API
20341
20423
  * @async
20342
20424
  */
20343
- const connectClient = async (params) => {
20425
+ const connectClient = async (params, config) => {
20344
20426
  var _a;
20345
20427
  const client = getActiveClient();
20346
20428
  client.log('client/api/connectClient', Object.assign({ apiKey: client.apiKey }, params));
@@ -20365,7 +20447,9 @@ const connectClient = async (params) => {
20365
20447
  client.userId = params.userId;
20366
20448
  client.accessToken = accessToken;
20367
20449
  setActiveUser(users[0]);
20368
- subscribeTopic(getNetworkTopic());
20450
+ if ((config === null || config === void 0 ? void 0 : config.disableRTE) !== true) {
20451
+ subscribeTopic(getNetworkTopic());
20452
+ }
20369
20453
  const subscriptions = [
20370
20454
  onClientBanned(() => {
20371
20455
  disconnectClient();
@@ -21311,6 +21395,8 @@ queryMessages.locally = (query) => {
21311
21395
  : undefined;
21312
21396
  };
21313
21397
 
21398
+ const uuid = () => nativeIdGenerator__default["default"].v4().toString();
21399
+
21314
21400
  /**
21315
21401
  * ```js
21316
21402
  * import { createMessage } from '@amityco/ts-sdk'
@@ -21361,12 +21447,23 @@ const createMessage = async (bundle) => {
21361
21447
  createMessage.optimistically = (bundle) => {
21362
21448
  var _a, _b;
21363
21449
  const client = getActiveClient();
21364
- client.log('user/createMessage.locally', bundle);
21365
21450
  if (!client.cache)
21366
21451
  return;
21367
- const channel = pullFromCache(['channel', 'get', bundle.channelId]);
21368
- upsertInCache(['channel', 'get', bundle.channelId], Object.assign(Object.assign({}, channel === null || channel === void 0 ? void 0 : channel.data), { messageCount: ((_a = channel === null || channel === void 0 ? void 0 : channel.data.messageCount) !== null && _a !== void 0 ? _a : 0) + 1 }));
21369
- const message = Object.assign({ messageId: Math.random().toString(16), userId: client.userId, channelSegment: ((_b = channel === null || channel === void 0 ? void 0 : channel.data.messageCount) !== null && _b !== void 0 ? _b : 0) + 1, createdAt: new Date().toISOString() }, bundle);
21452
+ /*
21453
+ * when creating messages optimistically a messageId needs to be added by the
21454
+ * client, created a new variable so as to allow backward compatibility of API
21455
+ *
21456
+ * Updated to handle client requirement to add messageId while uploading
21457
+ * message with image. Temporary!
21458
+ */
21459
+ const bundleWithMessageId = Object.assign({ messageId: uuid() }, bundle);
21460
+ // only log if cache is enabled
21461
+ client.log('user/createMessage.locally', bundleWithMessageId);
21462
+ const channel = pullFromCache(['channel', 'get', bundleWithMessageId.channelId]);
21463
+ upsertInCache(['channel', 'get', bundleWithMessageId.channelId], Object.assign(Object.assign({}, channel === null || channel === void 0 ? void 0 : channel.data), { messageCount: ((_a = channel === null || channel === void 0 ? void 0 : channel.data.messageCount) !== null && _a !== void 0 ? _a : 0) + 1 }));
21464
+ // as reused to update created and updated time, which should be the same
21465
+ const createdTime = new Date().toISOString();
21466
+ const message = Object.assign({ userId: client.userId, channelSegment: ((_b = channel === null || channel === void 0 ? void 0 : channel.data.messageCount) !== null && _b !== void 0 ? _b : 0) + 1, createdAt: createdTime, updatedAt: createdTime }, bundleWithMessageId);
21370
21467
  pushToCache(['message', 'get', message.messageId], message, { cachedAt: -1 });
21371
21468
  fireEvent('v3.message.didCreate', { messages: [message] });
21372
21469
  return {
@@ -22409,6 +22506,78 @@ const deletePost = async (postId, permanent = false) => {
22409
22506
  return deleted;
22410
22507
  };
22411
22508
 
22509
+ /**
22510
+ * ```js
22511
+ * import { approvePost } from '@amityco/ts-sdk'
22512
+ *
22513
+ * const { data: post } = await approvePost('postId')
22514
+ * ```
22515
+ *
22516
+ * Approves a {@link Amity.Post}
22517
+ *
22518
+ * @param postId The {@link Amity.Post} ID to be approved
22519
+ * @return A {@link Amity.Post} that was approved
22520
+ *
22521
+ * @category Post API
22522
+ * @async
22523
+ */
22524
+ const approvePost = async (postId) => {
22525
+ var _a;
22526
+ const client = getActiveClient();
22527
+ client.log('post/approvePost', postId);
22528
+ const { data: approved } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/approve`);
22529
+ const cachedAt = client.cache && Date.now();
22530
+ if (client.cache)
22531
+ ingestInCache(approved, { cachedAt });
22532
+ // fire virtual event for community update
22533
+ if (approved.posts[0].targetType === 'community') {
22534
+ const community = (_a = approved.communities) === null || _a === void 0 ? void 0 : _a[0];
22535
+ // @ts-ignore as communities is optional currently in PostPayload
22536
+ fireEvent('community.updated', { communities: [community] });
22537
+ }
22538
+ fireEvent('post.approved', { posts: [approved.posts[0]] });
22539
+ return {
22540
+ data: approved.posts.find(post => post.postId === postId),
22541
+ cachedAt,
22542
+ };
22543
+ };
22544
+
22545
+ /**
22546
+ * ```js
22547
+ * import { declinePost } from '@amityco/ts-sdk'
22548
+ *
22549
+ * const {data: post} = await declinePost('postId')
22550
+ * ```
22551
+ *
22552
+ * Declines a {@link Amity.Post}
22553
+ *
22554
+ * @param postId The {@link Amity.Post} ID to be declined
22555
+ * @return A {@link Amity.Post} that was declined
22556
+ *
22557
+ * @category Post API
22558
+ * @async
22559
+ */
22560
+ const declinePost = async (postId) => {
22561
+ var _a;
22562
+ const client = getActiveClient();
22563
+ client.log('post/declinePost', postId);
22564
+ const { data: declined } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/decline`);
22565
+ const cachedAt = client.cache && Date.now();
22566
+ if (client.cache)
22567
+ ingestInCache(declined, { cachedAt });
22568
+ // fire virtual event
22569
+ if (declined.posts[0].targetType === 'community') {
22570
+ const community = (_a = declined.communities) === null || _a === void 0 ? void 0 : _a[0];
22571
+ // @ts-ignore as communities is optional currently in PostPayload
22572
+ fireEvent('community.updated', { communities: [community] });
22573
+ }
22574
+ fireEvent('post.declined', { posts: [declined.posts[0]] });
22575
+ return {
22576
+ data: declined.posts.find(post => post.postId === postId),
22577
+ cachedAt,
22578
+ };
22579
+ };
22580
+
22412
22581
  /**
22413
22582
  * ```js
22414
22583
  * import { queryComments } from '@amityco/ts-sdk'
@@ -22427,6 +22596,10 @@ const queryComments = async (query) => {
22427
22596
  const client = getActiveClient();
22428
22597
  client.log('comment/queryComments', query);
22429
22598
  const { page = { limit: 10 } } = query, params = __rest(query, ["page"]);
22599
+ const options = {
22600
+ type: params.sortBy ? 'pagination' : undefined,
22601
+ token: toToken(page, params.sortBy ? 'skiplimit' : 'afterbefore'),
22602
+ };
22430
22603
  // const filterByParentId = query.parentId !== undefined
22431
22604
  // API-FIX: parameters should be querystring. (1)
22432
22605
  // API-FIX: backend should answer Amity.Response (2)
@@ -22434,9 +22607,7 @@ const queryComments = async (query) => {
22434
22607
  const { data } = await client.http.get(`/api/v3/comments`, {
22435
22608
  params: Object.assign(Object.assign({}, params), {
22436
22609
  // filterByParentId, API-FIX: backend does not support this boolean LOL. what the hell seriously.
22437
- options: {
22438
- token: toToken(page, 'afterbefore'),
22439
- } }),
22610
+ options }),
22440
22611
  });
22441
22612
  // API-FIX: backend should answer Amity.Response (2)
22442
22613
  // const { paging, comments } = unwrapPayload(data)
@@ -22771,6 +22942,38 @@ const preparePayloadForCache = (event, payload) => {
22771
22942
  }
22772
22943
  };
22773
22944
 
22945
+ /** @hidden */
22946
+ /*
22947
+ * @param message payload from http request without myReactions
22948
+ * add myReactions to http response if the event was a reaction event
22949
+ */
22950
+ const prepareMessagePayloadForCache = (payload) => {
22951
+ const client = getActiveClient();
22952
+ const cached = pullFromCache(['message', 'get', payload.messageId]);
22953
+ // '[]' in cases where the new reaction is the first one
22954
+ const myReactions = (cached === null || cached === void 0 ? void 0 : cached.data.myReactions) || [];
22955
+ // add myReactions to the payload
22956
+ Object.assign(payload, { myReactions });
22957
+ // check if there are any updates to the reactions
22958
+ const latestReaction = payload === null || payload === void 0 ? void 0 : payload.latestReaction;
22959
+ const isLatestReactionMine = latestReaction && latestReaction.userId === client.userId;
22960
+ if (!isLatestReactionMine) {
22961
+ return;
22962
+ }
22963
+ // new reaction added
22964
+ if (latestReaction.eventName === 'add' && !myReactions.includes(latestReaction.reactionName)) {
22965
+ Object.assign(payload, {
22966
+ myReactions: [...myReactions, latestReaction.reactionName],
22967
+ });
22968
+ }
22969
+ // existing reaction removed
22970
+ if (latestReaction.eventName === 'remove' && myReactions.includes(latestReaction.reactionName)) {
22971
+ Object.assign(payload, {
22972
+ myReactions: myReactions.filter(x => x !== latestReaction.reactionName),
22973
+ });
22974
+ }
22975
+ };
22976
+
22774
22977
  /**
22775
22978
  * ```js
22776
22979
  * import { addReaction } from '@amityco/ts-sdk'
@@ -23427,7 +23630,9 @@ const createReport = async (referenceType, referenceId) => {
23427
23630
  const client = getActiveClient();
23428
23631
  client.log('report/createReport', { referenceType, referenceId });
23429
23632
  const { domainName } = REFERENCE_TYPES[referenceType];
23430
- const { data } = await client.http.post(`/api/v3/${domainName}/${encodeURIComponent(referenceId)}/flag`);
23633
+ const { data } = await client.http.post(`/api/${referenceType === 'user'
23634
+ ? `v4/me/flags/${encodeURIComponent(referenceId)}`
23635
+ : `v3/${domainName}/${encodeURIComponent(referenceId)}/flag`}`);
23431
23636
  if (client.cache)
23432
23637
  ingestInCache(data);
23433
23638
  const event = referenceType === 'message'
@@ -23454,7 +23659,9 @@ const deleteReport = async (referenceType, referenceId) => {
23454
23659
  const client = getActiveClient();
23455
23660
  client.log('report/deleteReport', { referenceType, referenceId });
23456
23661
  const { domainName } = REFERENCE_TYPES[referenceType];
23457
- const { data } = await client.http.delete(`/api/v3/${domainName}/${encodeURIComponent(referenceId)}/unflag`);
23662
+ const { data } = await client.http.delete(`/api/${referenceType === 'user'
23663
+ ? `v4/me/flags/${encodeURIComponent(referenceId)}`
23664
+ : `v3/${domainName}/${encodeURIComponent(referenceId)}/unflag`}`);
23458
23665
  if (client.cache)
23459
23666
  ingestInCache(data);
23460
23667
  const event = referenceType === 'message'
@@ -23819,9 +24026,9 @@ const leaveChannel = async (channelId) => {
23819
24026
  const queryChannelMembers = async (query) => {
23820
24027
  const client = getActiveClient();
23821
24028
  client.log('channel/queryChannelMembers', query);
23822
- const _a = query !== null && query !== void 0 ? query : {}, { page, channelId, membership } = _a, params = __rest(_a, ["page", "channelId", "membership"]);
23823
- const { data } = await client.http.get(`/api/v3/channels/${encodeURIComponent(channelId)}/users`, {
23824
- params: Object.assign(Object.assign({}, params), { filter: membership, options: {
24029
+ const _a = query !== null && query !== void 0 ? query : {}, { page, channelId } = _a, params = __rest(_a, ["page", "channelId"]);
24030
+ const { data } = await client.http.get(`/api/v4/channels/${encodeURIComponent(channelId)}/users`, {
24031
+ params: Object.assign(Object.assign({}, params), { options: {
23825
24032
  token: toToken(page, 'skiplimit'),
23826
24033
  } }),
23827
24034
  });
@@ -24192,7 +24399,12 @@ const onMessageUpdated = (callback) => {
24192
24399
  const client = getActiveClient();
24193
24400
  const filter = (payload) => {
24194
24401
  ingestInCache(payload);
24195
- callback(payload.messages[0]);
24402
+ const message = payload.messages[0];
24403
+ // if payload does not have myReactions
24404
+ if (!(message === null || message === void 0 ? void 0 : message.myReactions)) {
24405
+ prepareMessagePayloadForCache(message);
24406
+ }
24407
+ callback(message);
24196
24408
  };
24197
24409
  return createEventSubscriber(client, 'message/onMessageUpdated', 'v3.message.didUpdate', filter);
24198
24410
  };
@@ -25628,6 +25840,7 @@ const closePoll = async (pollId) => {
25628
25840
  const cachedAt = client.cache && Date.now();
25629
25841
  if (client.cache)
25630
25842
  ingestInCache(data, { cachedAt });
25843
+ fireEvent('poll.updated', data);
25631
25844
  const { polls } = data;
25632
25845
  return {
25633
25846
  data: polls.find(poll => poll.pollId === pollId),
@@ -25658,6 +25871,7 @@ const deletePoll = async (pollId) => {
25658
25871
  const { success } = data; // unwrapPayload(data)
25659
25872
  const deleted = Object.assign(Object.assign({}, poll.data), { isDeleted: true });
25660
25873
  upsertInCache(['poll', 'get', pollId], deleted);
25874
+ fireEvent('poll.deleted', { polls: [deleted], users: [] });
25661
25875
  return success;
25662
25876
  };
25663
25877
 
@@ -25684,12 +25898,107 @@ const votePoll = async (pollId, answerIds) => {
25684
25898
  if (client.cache)
25685
25899
  ingestInCache(data, { cachedAt });
25686
25900
  const { polls } = data;
25901
+ fireEvent('poll.updated', data);
25687
25902
  return {
25688
25903
  data: polls.find(poll => poll.pollId === pollId),
25689
25904
  cachedAt,
25690
25905
  };
25691
25906
  };
25692
25907
 
25908
+ /**
25909
+ * ```js
25910
+ * import { onPollUpdated } from '@amityco/ts-sdk'
25911
+ * const dispose = onPollUpdated(poll => {
25912
+ * // ...
25913
+ * })
25914
+ * ```
25915
+ *
25916
+ * Fired when an {@link Amity.Poll} has been updated
25917
+ *
25918
+ * @param callback The function to call when the event was fired
25919
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25920
+ *
25921
+ * @category Poll Events
25922
+ */
25923
+ const onPollUpdated = (callback) => {
25924
+ const client = getActiveClient();
25925
+ const filter = (payload) => {
25926
+ if (client.cache)
25927
+ ingestInCache(payload);
25928
+ callback(payload.polls[0]);
25929
+ };
25930
+ return createEventSubscriber(client, 'poll/onPollUpdated', 'poll.updated', filter);
25931
+ };
25932
+
25933
+ /**
25934
+ * ```js
25935
+ * import { onPollDeleted } from '@amityco/ts-sdk'
25936
+ * const dispose = onPollDeleted(poll => {
25937
+ * // ...
25938
+ * })
25939
+ * ```
25940
+ *
25941
+ * Fired when an {@link Amity.Poll} has been deleted
25942
+ *
25943
+ * @param callback The function to call when the event was fired
25944
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
25945
+ *
25946
+ * @category Poll Events
25947
+ */
25948
+ const onPollDeleted = (callback) => {
25949
+ const client = getActiveClient();
25950
+ const filter = (payload) => {
25951
+ if (client.cache)
25952
+ ingestInCache(payload);
25953
+ callback(payload.polls[0]);
25954
+ };
25955
+ return createEventSubscriber(client, 'poll/onPollDeleted', 'poll.deleted', filter);
25956
+ };
25957
+
25958
+ /**
25959
+ * ```js
25960
+ * import { observePoll } from '@amityco/ts-sdk'
25961
+ *
25962
+ * let poll = {}
25963
+ * const dispose = observePoll(pollId, updated => poll = updated)
25964
+ * ```
25965
+ *
25966
+ * Observe all mutation on a given {@link Amity.Poll}
25967
+ *
25968
+ * @param pollId the ID of the poll to observe
25969
+ * @param callback the function to call when new data are available
25970
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the poll
25971
+ *
25972
+ * @category Poll Observer
25973
+ */
25974
+ const observePoll = (pollId, callback, policy = 'cache_then_server') => {
25975
+ const { log } = getActiveClient();
25976
+ const timestamp = Date.now();
25977
+ log(`observePoll(tmpid: ${timestamp}) > listen`);
25978
+ // wrapper function to make sure
25979
+ const router = (result, action) => {
25980
+ var _a, _b;
25981
+ if (callback instanceof Function)
25982
+ return callback(result);
25983
+ if (action !== 'onFetch')
25984
+ (_a = callback.onEvent) === null || _a === void 0 ? void 0 : _a.call(callback, action, result);
25985
+ (_b = callback[action]) === null || _b === void 0 ? void 0 : _b.call(callback, result);
25986
+ };
25987
+ const realtimeRouter = (result, action) => {
25988
+ var _a;
25989
+ if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.pollId) !== pollId)
25990
+ return;
25991
+ router(result, action);
25992
+ };
25993
+ const disposers = [];
25994
+ disposers.push(onPollUpdated(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onUpdate')), onPollDeleted(data => realtimeRouter({ data, loading: false, origin: 'event' }, 'onDelete')));
25995
+ runQuery(createQuery(getPoll, pollId), result => (result.data || result.error) && router(result, 'onFetch'), queryOptions(policy));
25996
+ return () => {
25997
+ log(`observePoll(tmpid: ${timestamp}) > dispose`);
25998
+ disposers.forEach(fn => fn());
25999
+ };
26000
+ };
26001
+
25693
26002
  /**
25694
26003
  * ```js
25695
26004
  * import { getStream } from '@amityco/ts-sdk'
@@ -26013,6 +26322,7 @@ exports.addChannelMembersRole = addChannelMembersRole;
26013
26322
  exports.addCommunityMembers = addCommunityMembers;
26014
26323
  exports.addCommunityMembersRoles = addCommunityMembersRoles;
26015
26324
  exports.addReaction = addReaction;
26325
+ exports.approvePost = approvePost;
26016
26326
  exports.backupCache = backupCache;
26017
26327
  exports.closePoll = closePoll;
26018
26328
  exports.connectClient = connectClient;
@@ -26031,6 +26341,7 @@ exports.createStream = createStream;
26031
26341
  exports.createUserToken = createUserToken;
26032
26342
  exports.createVideo = createVideo;
26033
26343
  exports.declineFollower = declineFollower;
26344
+ exports.declinePost = declinePost;
26034
26345
  exports.deleteChannel = deleteChannel;
26035
26346
  exports.deleteComment = deleteComment;
26036
26347
  exports.deleteCommunity = deleteCommunity;
@@ -26103,6 +26414,7 @@ exports.observeFollowers = observeFollowers;
26103
26414
  exports.observeFollowings = observeFollowings;
26104
26415
  exports.observeMessage = observeMessage;
26105
26416
  exports.observeMessages = observeMessages;
26417
+ exports.observePoll = observePoll;
26106
26418
  exports.observePost = observePost;
26107
26419
  exports.observePosts = observePosts;
26108
26420
  exports.observeUser = observeUser;
@@ -26140,6 +26452,8 @@ exports.onFollowerRequested = onFollowerRequested;
26140
26452
  exports.onMessageCreated = onMessageCreated;
26141
26453
  exports.onMessageDeleted = onMessageDeleted;
26142
26454
  exports.onMessageUpdated = onMessageUpdated;
26455
+ exports.onPollDeleted = onPollDeleted;
26456
+ exports.onPollUpdated = onPollUpdated;
26143
26457
  exports.onPostApproved = onPostApproved;
26144
26458
  exports.onPostCreated = onPostCreated;
26145
26459
  exports.onPostDeclined = onPostDeclined;
package/dist/index.d.ts CHANGED
@@ -36,6 +36,8 @@ export * from './comment/api';
36
36
  export * from './comment/events';
37
37
  export * from './comment/observers';
38
38
  export * from './poll/api';
39
+ export * from './poll/events';
40
+ export * from './poll/observers';
39
41
  export * from './stream/api';
40
42
  export * from './stream/events';
41
43
  export * from './external/api';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,UAAU,CAAC;AAElB,cAAc,WAAW,CAAC;AAG1B,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAE5B,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAGvD,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,YAAY,CAAC;AAG3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAElC,cAAc,cAAc,CAAC;AAG7B,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AAEpC,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AAGpC,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,uBAAuB,CAAC;AAEtC,cAAc,gBAAgB,CAAC;AAE/B,cAAc,YAAY,CAAC;AAE3B,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AAEnC,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AAEpC,cAAc,YAAY,CAAC;AAE3B,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAGhC,cAAc,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,UAAU,CAAC;AAElB,cAAc,WAAW,CAAC;AAG1B,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAE5B,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAGvD,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,YAAY,CAAC;AAG3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAElC,cAAc,cAAc,CAAC;AAG7B,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AAEpC,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AAGpC,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,uBAAuB,CAAC;AAEtC,cAAc,gBAAgB,CAAC;AAE/B,cAAc,YAAY,CAAC;AAE3B,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AAEnC,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AAEpC,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAGhC,cAAc,gBAAgB,CAAC"}