import type { ActivityRequest, FeedResponse, GetOrCreateFeedRequest, GetOrCreateFeedResponse, QueryFollowsRequest, WSEvent, ActivityResponse, CommentResponse, PagerResponse, QueryFeedMembersRequest, SortParamRequest, ThreadedCommentResponse, FollowRequest, QueryCommentsRequest, EnrichmentOptions, } from '../gen/models'; import type { StreamResponse } from '../gen-imports'; import { StateStore } from '@stream-io/state-store'; import { EventDispatcher } from '../common/EventDispatcher'; import { FeedApi } from '../gen/feeds/FeedApi'; import type { FeedsClient } from '../feeds-client'; import { handleFollowUpdated, handleFollowCreated, handleFollowDeleted, handleCommentAdded, handleCommentDeleted, handleCommentUpdated, handleBookmarkDeleted, handleBookmarkUpdated, handleActivityAdded, addActivitiesToState, shouldApplyActivityAdded, handleActivityUpdated, handleFeedMemberAdded, handleFeedMemberRemoved, handleFeedMemberUpdated, handleBookmarkAdded, handleActivityDeleted, handleActivityRemovedFromFeed, handleFeedDeleted, handleFeedUpdated, handleNotificationFeedUpdated, handleActivityReactionAdded, handleActivityReactionDeleted, handleActivityReactionUpdated, handleCommentReactionAdded, handleCommentReactionDeleted, handleCommentReactionUpdated, addAggregatedActivitiesToState, updateNotificationStatus, handleStoriesFeedUpdated, handleActivityPinned, handleActivityUnpinned, } from './event-handlers'; import { capitalize } from '../common/utils'; import type { ActivityIdOrCommentId, ConnectedUser, GetCommentsRepliesRequest, GetCommentsRequest, LoadingStates, OnNewActivityCallback, OnNewActivityResult, PagerResponseWithLoadingStates, } from '../types'; import { activityFilter } from './activity-filter'; import { checkHasAnotherPage, Constants, feedsLoggerSystem, uniqueArrayMerge, } from '../utils'; import { withRetry } from '../utils/retry'; import { handleActivityFeedback } from './event-handlers/activity/handle-activity-feedback'; import { deepEqual } from '../utils/deep-equal'; import { getOrCreateActiveFeed } from '../feeds-client/get-or-create-active-feed'; import { queueBatchedOwnFields } from '../utils/throttling'; export type FeedState = Omit< Partial, 'feed' | 'duration' > & { /** * True when loading state using `getOrCreate` */ is_loading: boolean; /** * True when loading activities using `getOrCreate` or `getNextPage` */ is_loading_activities: boolean; comments_by_entity_id: Record< ActivityIdOrCommentId, | { pagination?: PagerResponseWithLoadingStates & { // registered on first pagination attempt and then used for real-time updates & subsequent pagination calls sort?: QueryCommentsRequest['sort'] | (string & {}); }; /** * Id of the "store" where the actual parent is stored in the comments array. * * Example: * ``` * // top-level comment: * const comment1 = { * id: 'comment-1', * object_id: 'activity-1', * } * // child comment: * const comment2 = { * id: 'comment-2', * object_id: 'activity-1', * parent_id: 'comment-1', * } * ``` * When these comments are loaded, they're stored in the state like this: * ``` * { * comments_by_entity_id: { * 'activity-1': { * comments: [comment1], * entity_parent_id: undefined, * }, * 'comment-1': { * comments: [comment2], * entity_parent_id: 'activity-1', // parent store where "comment-1" is located in "comments" array * } * } * } * ``` */ entity_parent_id?: ActivityIdOrCommentId; comments?: CommentResponse[]; } | undefined >; followers_pagination?: LoadingStates & { sort?: SortParamRequest[] }; following_pagination?: LoadingStates & { sort?: SortParamRequest[] }; member_pagination?: LoadingStates & { sort?: SortParamRequest[] }; last_get_or_create_request_config?: GetOrCreateFeedRequest; /** * `true` if the feed is receiving real-time updates via WebSocket */ watch: boolean; }; type EventHandlerByEventType = { [Key in NonNullable]: Key extends Extract< WSEvent, { type: Key } >['type'] ? ((event: Extract) => void) | undefined : never; }; export class Feed extends FeedApi { readonly state: StateStore; private static readonly noop = () => {}; protected indexedActivityIds: Set = new Set(); protected readonly stateUpdateQueue: Set = new Set(); private readonly eventHandlers: EventHandlerByEventType = { 'feeds.activity.added': handleActivityAdded.bind(this), 'feeds.activity.deleted': handleActivityDeleted.bind(this), 'feeds.activity.reaction.added': handleActivityReactionAdded.bind(this), 'feeds.activity.reaction.deleted': handleActivityReactionDeleted.bind(this), 'feeds.activity.reaction.updated': handleActivityReactionUpdated.bind(this), 'feeds.activity.removed_from_feed': handleActivityRemovedFromFeed.bind(this), 'feeds.activity.updated': handleActivityUpdated.bind(this), 'feeds.bookmark.added': handleBookmarkAdded.bind(this), 'feeds.bookmark.deleted': handleBookmarkDeleted.bind(this), 'feeds.bookmark.updated': handleBookmarkUpdated.bind(this), 'feeds.bookmark_folder.deleted': Feed.noop, 'feeds.bookmark_folder.updated': Feed.noop, 'feeds.comment.added': handleCommentAdded.bind(this), 'feeds.comment.deleted': handleCommentDeleted.bind(this), 'feeds.comment.updated': handleCommentUpdated.bind(this), 'feeds.comment.restored': Feed.noop, 'feeds.feed.created': Feed.noop, 'feeds.feed.deleted': handleFeedDeleted.bind(this), 'feeds.feed.updated': handleFeedUpdated.bind(this), 'feeds.feed_group.changed': Feed.noop, 'feeds.feed_group.deleted': Feed.noop, 'feeds.feed_group.restored': Feed.noop, 'feeds.follow.created': handleFollowCreated.bind(this), 'feeds.follow.deleted': handleFollowDeleted.bind(this), 'feeds.follow.updated': handleFollowUpdated.bind(this), 'feeds.comment.reaction.added': handleCommentReactionAdded.bind(this), 'feeds.comment.reaction.deleted': handleCommentReactionDeleted.bind(this), 'feeds.comment.reaction.updated': handleCommentReactionUpdated.bind(this), 'feeds.feed_member.added': handleFeedMemberAdded.bind(this), 'feeds.feed_member.removed': handleFeedMemberRemoved.bind(this), 'feeds.feed_member.updated': handleFeedMemberUpdated.bind(this), 'feeds.notification_feed.updated': handleNotificationFeedUpdated.bind(this), 'feeds.stories_feed.updated': handleStoriesFeedUpdated.bind(this), // the poll events should be removed from here 'feeds.poll.closed': Feed.noop, 'feeds.poll.deleted': Feed.noop, 'feeds.poll.updated': Feed.noop, 'feeds.poll.vote_casted': Feed.noop, 'feeds.poll.vote_changed': Feed.noop, 'feeds.poll.vote_removed': Feed.noop, 'feeds.activity.pinned': handleActivityPinned.bind(this), 'feeds.activity.unpinned': handleActivityUnpinned.bind(this), 'feeds.activity.marked': Feed.noop, 'moderation.custom_action': Feed.noop, 'moderation.flagged': Feed.noop, 'moderation.mark_reviewed': Feed.noop, 'health.check': Feed.noop, 'app.updated': Feed.noop, 'user.banned': Feed.noop, 'user.deactivated': Feed.noop, 'user.reactivated': Feed.noop, 'user.updated': Feed.noop, 'feeds.activity.feedback': handleActivityFeedback.bind(this), 'feeds.activity.restored': Feed.noop, 'user.unbanned': Feed.noop, 'feeds.scheduled_activity.created': Feed.noop, 'feeds.scheduled_activity.deleted': Feed.noop, 'feeds.scheduled_activity.failed': Feed.noop, 'feeds.scheduled_activity.published': Feed.noop, 'feeds.scheduled_activity.updated': Feed.noop, }; protected eventDispatcher: EventDispatcher = new EventDispatcher(); private inProgressGetOrCreate?: { request?: GetOrCreateFeedRequest; promise: Promise>; }; constructor( client: FeedsClient, groupId: 'user' | 'timeline' | (string & {}), id: string, data?: FeedResponse, watch = false, public onNewActivity?: OnNewActivityCallback, ) { super(client, groupId, id); this.state = new StateStore({ feed: `${groupId}:${id}`, group_id: groupId, id, ...(data ?? {}), is_loading: false, is_loading_activities: false, comments_by_entity_id: {}, watch, }); this.client = client; this.state.subscribeWithSelector( (nextState) => ({ activities: nextState.activities }), (nextState) => { const { activities: nextActivities = [] } = nextState; if (this.indexedActivityIds.size !== nextActivities?.length) { this.indexedActivityIds = new Set( nextActivities.map((activity) => activity.id), ); } }, ); } protected readonly client: FeedsClient; get feed() { return `${this.group}:${this.id}`; } get currentState() { return this.state.getLatestValue(); } hasActivity(activityId: string) { return this.indexedActivityIds.has(activityId); } hasPinnedActivity(activityId: string) { return this.currentState.pinned_activities?.some( (pinnedActivity) => pinnedActivity.activity.id === activityId, ); } /** * Resolves how to handle a new activity (WS or HTTP): ignore, add-to-start, or add-to-end. * Uses onNewActivity if set; else default (current user + filter match) adds to start. */ protected resolveNewActivityDecision( activity: ActivityResponse, currentUser: ConnectedUser | undefined, _fromHttp: boolean, ): OnNewActivityResult { if (this.onNewActivity) { return this.onNewActivity({ activity, currentUser }); } if (!currentUser) return 'ignore'; if (activity.user?.id !== currentUser.id) return 'ignore'; if ( !activityFilter( activity, this.currentState.last_get_or_create_request_config, ) ) { return 'ignore'; } return 'add-to-start'; } async synchronize() { const { last_get_or_create_request_config } = this.state.getLatestValue(); if (last_get_or_create_request_config?.watch) { this.inProgressGetOrCreate = undefined; await withRetry(() => this.getOrCreate(last_get_or_create_request_config), ); } } async getOrCreate(request?: GetOrCreateFeedRequest) { if ( !request?.next && this.inProgressGetOrCreate && deepEqual(request, this.inProgressGetOrCreate.request) ) { return this.inProgressGetOrCreate.promise; } if (this.currentState.is_loading_activities) { throw new Error('Only one getOrCreate call is allowed at a time'); } this.state.partialNext({ is_loading: !request?.next, is_loading_activities: true, }); // TODO: pull comments/comment_pagination from activities and comment_sort from request // and pre-populate comments_by_entity_id (once comment_sort and comment_limit are supported) try { const responsePromise = super.getOrCreate(request); if (!request?.next) { this.inProgressGetOrCreate = { request, promise: responsePromise }; } const response = await responsePromise; const currentActivityFeeds = []; for (const activity of response.activities) { if (activity.current_feed) { currentActivityFeeds.push(activity.current_feed); } } if (request?.next) { const { activities: currentActivities = [] } = this.currentState; const result = addActivitiesToState.bind(this)( response.activities, currentActivities, 'end', { hasOwnFields: true, backfillOwnFields: false }, ); const aggregatedActivitiesResult = addAggregatedActivitiesToState( response.aggregated_activities, this.currentState.aggregated_activities, 'end', ); const notificationStatusResult = updateNotificationStatus( response.notification_status, this.currentState.notification_status, ); if ( result.changed || aggregatedActivitiesResult.changed || notificationStatusResult.changed ) { this.state.partialNext({ activities: result.activities, aggregated_activities: aggregatedActivitiesResult.aggregated_activities, notification_status: notificationStatusResult.notification_status, next: response.next, prev: response.prev, }); } } else { // Empty queue when reinitializing the state this.stateUpdateQueue.clear(); const responseCopy: Partial< StreamResponse['feed'] & StreamResponse> > = { ...response, ...response.feed, }; delete responseCopy.feed; delete responseCopy.metadata; delete responseCopy.duration; // recreate the caches so that they are updated on the next state update this.indexedActivityIds = new Set(); // TODO: lazy-load comments from activities when comment_sort and comment_pagination are supported this.state.next((currentState) => { const nextState: FeedState = { ...currentState, ...responseCopy, }; if (!request?.followers_pagination?.limit) { delete nextState.followers; } if (!request?.following_pagination?.limit) { delete nextState.following; } if (response.members.length === 0 && response.feed.member_count > 0) { delete nextState.members; } nextState.last_get_or_create_request_config = request; nextState.watch = request?.watch ? request.watch : currentState.watch; return nextState; }); } this.activitiesAddedOrUpdated(response.activities); return response; } finally { this.state.partialNext({ is_loading: false, is_loading_activities: false, }); if (!request?.next) { this.inProgressGetOrCreate = undefined; } } } /** * Returns index of the provided comment object. */ protected getCommentIndex( comment: Pick, state?: FeedState, ) { const { comments_by_entity_id = {} } = state ?? this.currentState; const currentComments = comments_by_entity_id[comment.parent_id ?? comment.object_id]?.comments; if (!currentComments?.length) { return -1; } // @ts-expect-error this will just fail if the comment is not object from state let commentIndex = currentComments.indexOf(comment); // fast lookup failed, try slower approach if (commentIndex === -1) { commentIndex = currentComments.findIndex( (comment_) => comment_.id === comment.id, ); } return commentIndex; } /** * Load child comments of entity (activity or comment) into the state, if the target entity is comment, * `entityParentId` should be provided (`CommentResponse.parent_id ?? CommentResponse.object_id`). */ private loadCommentsIntoState(data: { entityParentId?: string; entityId: string; comments: Array; next?: string; sort: string; }) { // add initial (top level) object for processing const traverseArray = [ { entityId: data.entityId, entityParentId: data.entityParentId, comments: data.comments, next: data.next, }, ]; this.state.next((currentState) => { const newCommentsByEntityId = { ...currentState.comments_by_entity_id, }; while (traverseArray.length) { const item = traverseArray.pop()!; const entityId = item.entityId; // go over entity comments and generate new objects // for further processing if there are any replies item.comments.forEach((comment) => { if (!comment.replies?.length) return; traverseArray.push({ entityId: comment.id, entityParentId: entityId, comments: comment.replies, next: comment.meta?.next_cursor, }); }); // omit replies & meta from the comments (transform ThreadedCommentResponse to CommentResponse) // this is somehow faster than copying the whole // object and deleting the desired properties const newComments: CommentResponse[] = item.comments.map( ({ replies: _r, meta: _m, ...restOfTheCommentResponse }) => restOfTheCommentResponse, ); const existingComments = newCommentsByEntityId[entityId]?.comments; let comments: CommentResponse[] = existingComments ? uniqueArrayMerge( existingComments, newComments, (comment) => comment.id, ) : newComments; // Only sort when merging pages (existing + new); initial load order comes from API if ( data.sort === 'first' && existingComments && existingComments.length > 0 ) { comments = [...comments].sort( (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(), ); } newCommentsByEntityId[entityId] = { ...newCommentsByEntityId[entityId], entity_parent_id: item.entityParentId, pagination: { ...newCommentsByEntityId[entityId]?.pagination, next: item.next, sort: data.sort, }, comments, }; } return { ...currentState, comments_by_entity_id: newCommentsByEntityId, }; }); } private async loadNextPageComments({ entityId, base, sort, entityParentId, }: { entityParentId?: string; entityId: string; sort: string; base: () => Promise< PagerResponse & { comments: Array; } >; }) { let error: unknown; try { this.state.next((currentState) => ({ ...currentState, comments_by_entity_id: { ...currentState.comments_by_entity_id, [entityId]: { ...currentState.comments_by_entity_id[entityId], pagination: { ...currentState.comments_by_entity_id[entityId]?.pagination, loading_next_page: true, }, }, }, })); const { next, comments } = await base(); this.loadCommentsIntoState({ entityId, comments, entityParentId, next, sort, }); } catch (e) { error = e; } finally { this.state.next((currentState) => ({ ...currentState, comments_by_entity_id: { ...currentState.comments_by_entity_id, [entityId]: { ...currentState.comments_by_entity_id[entityId], pagination: { ...currentState.comments_by_entity_id[entityId]?.pagination, loading_next_page: false, }, }, }, })); } if (error) { throw error; } } public async loadNextPageActivityComments( activity: ActivityResponse | string, request?: Partial< Omit >, ) { const currentEntityState = this.currentState.comments_by_entity_id[ typeof activity === 'string' ? activity : activity.id ]; const currentPagination = currentEntityState?.pagination; const currentNextCursor = currentPagination?.next; const currentSort = currentPagination?.sort; const isLoading = currentPagination?.loading_next_page; const sort = currentSort ?? request?.sort ?? Constants.DEFAULT_COMMENT_PAGINATION; if ( isLoading || !checkHasAnotherPage(currentEntityState?.comments, currentNextCursor) ) { return; } const entityId = typeof activity === 'string' ? activity : activity.id; await this.loadNextPageComments({ entityId: entityId, base: () => this.client.getComments({ ...request, sort, object_id: entityId, object_type: 'activity', next: currentNextCursor, }), sort, }); } public async loadNextPageCommentReplies( comment: CommentResponse, request?: Partial>, ) { const currentEntityState = this.currentState.comments_by_entity_id[comment.id]; const currentPagination = currentEntityState?.pagination; const currentNextCursor = currentPagination?.next; const currentSort = currentPagination?.sort; const isLoading = currentPagination?.loading_next_page; const sort = currentSort ?? request?.sort ?? Constants.DEFAULT_COMMENT_PAGINATION; if ( isLoading || !checkHasAnotherPage(currentEntityState?.comments, currentNextCursor) ) { return; } await this.loadNextPageComments({ entityId: comment.id, base: () => this.client.getCommentReplies({ ...request, id: comment.id, // use known sort first (prevents broken pagination) sort, next: currentNextCursor, }), entityParentId: comment.parent_id ?? comment.object_id, sort, }); } private async loadNextPageFollows( type: 'followers' | 'following', request: Pick, ) { const paginationKey = `${type}_pagination` as const; const method = `query${capitalize(type)}` as const; const currentFollows = this.currentState[type]; const currentNextCursor = this.currentState[paginationKey]?.next; const isLoading = this.currentState[paginationKey]?.loading_next_page; const sort = this.currentState[paginationKey]?.sort ?? request.sort; let error: unknown; if (isLoading || !checkHasAnotherPage(currentFollows, currentNextCursor)) { return; } try { this.state.next((currentState) => { return { ...currentState, [paginationKey]: { ...currentState[paginationKey], loading_next_page: true, }, }; }); const { next: newNextCursor, follows } = await this[method]({ ...request, next: currentNextCursor, sort, }); this.state.next((currentState) => { return { ...currentState, [type]: currentState[type] === undefined ? follows : uniqueArrayMerge( currentState[type], follows, (follow) => `${follow.source_feed.feed}-${follow.target_feed.feed}`, ), [paginationKey]: { ...currentState[paginationKey], next: newNextCursor, sort, }, }; }); } catch (e) { error = e; } finally { this.state.next((currentState) => { return { ...currentState, [paginationKey]: { ...currentState[paginationKey], loading_next_page: false, }, }; }); } if (error) { throw error; } } async loadNextPageFollowers( request: Pick, ) { await this.loadNextPageFollows('followers', request); } async loadNextPageFollowing( request: Pick, ) { await this.loadNextPageFollows('following', request); } async loadNextPageMembers( request: Omit, ) { const currentMembers = this.currentState.members; const currentNextCursor = this.currentState.member_pagination?.next; const isLoading = this.currentState.member_pagination?.loading_next_page; const sort = this.currentState.member_pagination?.sort ?? request.sort; let error: unknown; if (isLoading || !checkHasAnotherPage(currentMembers, currentNextCursor)) { return; } try { this.state.next((currentState) => ({ ...currentState, member_pagination: { ...currentState.member_pagination, loading_next_page: true, }, })); const { next: newNextCursor, members } = await this.client.queryFeedMembers({ ...request, sort, feed_id: this.id, feed_group_id: this.group, next: currentNextCursor, }); this.state.next((currentState) => ({ ...currentState, members: currentState.members ? uniqueArrayMerge( currentState.members, members, ({ user }) => user.id, ) : members, member_pagination: { ...currentState.member_pagination, next: newNextCursor, // set sort if not defined yet sort: currentState.member_pagination?.sort ?? request.sort, }, })); } catch (e) { error = e; } finally { this.state.next((currentState) => ({ ...currentState, member_pagination: { ...currentState.member_pagination, loading_next_page: false, }, })); } if (error) { throw error; } } /** * Method which queries followers of this feed (feeds which target this feed). * * _Note: Useful only for feeds with `groupId` of `user` value._ */ async queryFollowers(request: Omit) { const filter: QueryFollowsRequest['filter'] = { target_feed: this.feed, }; const response = await this.client.queryFollows({ filter, ...request, }); return response; } /** * Method which queries following of this feed (target feeds of this feed). * * _Note: Useful only for feeds with `groupId` of `timeline` value._ */ async queryFollowing(request: Omit) { const filter: QueryFollowsRequest['filter'] = { source_feed: this.feed, }; const response = await this.client.queryFollows({ filter, ...request, }); return response; } async follow( feedOrFid: Feed | string, options?: Omit, ) { const fid = typeof feedOrFid === 'string' ? feedOrFid : feedOrFid.feed; const response = await this.client.follow({ ...options, source: this.feed, target: fid, }); return response; } async unfollow( feedOrFid: Feed | string, options?: Omit< Parameters[0], 'source' | 'target' > & { delete_notification_activity?: boolean; }, enrichOwnFields?: boolean, ) { const fid = typeof feedOrFid === 'string' ? feedOrFid : feedOrFid.feed; const response = await this.client.unfollow({ source: this.feed, target: fid, enrich_own_fields: enrichOwnFields, ...options, }); return response; } /** * Fetches the next page of activities for the feed. * @returns The response from the API or `undefined` if there is no next page. */ async getNextPage() { const currentState = this.currentState; if (!currentState.next) { return; } return await this.getOrCreate({ ...currentState.last_get_or_create_request_config, member_pagination: { limit: 0, }, followers_pagination: { limit: 0, }, following_pagination: { limit: 0, }, watch: undefined, next: currentState.next, }); } /** * Applies a new activity to this feed's state (decision + add to activities). * Used when the activity was added via this feed's addActivity or via client.addActivity. */ protected addActivityFromHTTPResponse(activity: ActivityResponse): void { if (!shouldApplyActivityAdded.call(this, activity, false)) { return; } const currentUser = this.client.state.getLatestValue().connected_user; const decision = this.resolveNewActivityDecision( activity, currentUser, true, ); if (decision !== 'ignore') { const position = decision === 'add-to-end' ? 'end' : 'start'; const currentActivities = this.currentState.activities; const result = addActivitiesToState.bind(this)( [activity], currentActivities, position, { hasOwnFields: activity.current_feed?.own_capabilities !== undefined, backfillOwnFields: false, }, ); if (result.changed) { this.client.hydratePollCache([activity]); this.state.partialNext({ activities: result.activities }); } } } async addActivity(request: Omit) { const response = await this.client.addActivity({ ...request, feeds: [this.feed], }); this.addActivityFromHTTPResponse(response.activity); return response; } on = this.eventDispatcher.on; off = this.eventDispatcher.off; handleWSEvent(event: WSEvent) { const eventHandler = this.eventHandlers[event.type]; // no need to run noop function if (eventHandler !== Feed.noop) { // Backfill current_feed if activity is posted to multiple feeds if ( 'activity' in event && event.activity.feeds.length > 1 && this.hasActivity(event.activity.id) ) { const currentActivity = this.currentState.activities?.find( (a) => a.id === event.activity.id, ); if (!event.activity.current_feed && currentActivity?.current_feed) { event.activity.current_feed = currentActivity.current_feed; } } // @ts-expect-error intersection of handler arguments results to never eventHandler?.(event); } if (typeof eventHandler === 'undefined') { feedsLoggerSystem .getLogger('event-dispatcher') .warn(`Received unknown feed event, type: ${event.type}`, event); } this.eventDispatcher.dispatch(event); } protected activitiesAddedOrUpdated( activities: ActivityResponse[], options: { hasOwnFields: boolean; backfillOwnFields: boolean; } = { hasOwnFields: true, backfillOwnFields: true }, ) { this.client.hydratePollCache(activities); this.getOrCreateFeeds(activities, options); } private getOrCreateFeeds( activities: ActivityResponse[], options: { hasOwnFields: boolean; backfillOwnFields: boolean; }, ) { const enrichmentOptions = this.currentState.last_get_or_create_request_config?.enrichment_options; if (this.shouldAddToActiveFeeds(enrichmentOptions)) { const feedsToGetOrCreate = new Map(); activities.forEach((activity) => { if ( activity.current_feed && !feedsToGetOrCreate.has(activity.current_feed.feed) ) { feedsToGetOrCreate.set( activity.current_feed.feed, activity.current_feed, ); } }); const newFeeds = Array.from(feedsToGetOrCreate.values()); const fieldsToUpdate: Array< 'own_capabilities' | 'own_follows' | 'own_followings' | 'own_membership' > = []; if (options.hasOwnFields) { fieldsToUpdate.push('own_membership'); if (!enrichmentOptions?.skip_own_capabilities) { fieldsToUpdate.push('own_capabilities'); } if (!enrichmentOptions?.skip_own_follows) { fieldsToUpdate.push('own_follows'); } if (enrichmentOptions?.enrich_own_followings) { fieldsToUpdate.push('own_followings'); } } newFeeds.forEach((feed) => { getOrCreateActiveFeed.bind(this.client)({ group: feed.group_id, id: feed.id, data: feed, fieldsToUpdate, }); }); if (!options.hasOwnFields && options.backfillOwnFields) { const uninitializedFeeds = newFeeds.filter((feedResponse) => { const feed = this.client.feed(feedResponse.group_id, feedResponse.id); // own_capabilities can only be undefined if we haven't fetched it yet return feed.currentState.own_capabilities === undefined; }); if (uninitializedFeeds.length > 0) { queueBatchedOwnFields.bind(this.client)({ feeds: uninitializedFeeds.map((feed) => feed.feed), }); } } } } private shouldAddToActiveFeeds(enrichmentOptions?: EnrichmentOptions) { if (!enrichmentOptions) { return true; } return ( !enrichmentOptions?.skip_activity && !enrichmentOptions?.skip_activity_current_feed && !enrichmentOptions?.skip_all ); } }