UNPKG

@amityco/ts-sdk-react-native

Version:

Amity Social Cloud Typescript SDK

92 lines (76 loc) 2.96 kB
import hash from 'object-hash'; import { pullFromCache, pushToCache } from '~/cache/api'; import { GlobalFeedPaginationController } from './PaginationController'; import { GlobalFeedQueryStreamController } from './QueryStreamController'; import { LiveCollectionController } from '~/core/liveCollection/LiveCollectionController'; import { isNonNullable } from '~/utils'; import { LinkedObject } from '~/utils/linkedObject'; import { preparePostPayload } from '~/postRepository/utils/payload'; import { getGlobalFeedSubscriptions } from '../utils'; export class GlobalFeedLiveCollectionController extends LiveCollectionController< 'post', Amity.GlobalFeedLiveCollection, Amity.Post, GlobalFeedPaginationController > { private queryStreamController: GlobalFeedQueryStreamController; private query: Amity.GlobalFeedLiveCollection; constructor( query: Amity.GlobalFeedLiveCollection, callback: Amity.LiveCollectionCallback<Amity.Post>, ) { const queryStreamId = hash(query); const cacheKey = ['globalFeed', 'collection', queryStreamId]; const paginationController = new GlobalFeedPaginationController(query); super(paginationController, queryStreamId, cacheKey, callback); this.query = query; this.queryStreamController = new GlobalFeedQueryStreamController( this.query, this.cacheKey, this.notifyChange.bind(this), preparePostPayload, ); this.callback = callback.bind(this); this.loadPage({ initial: true }); } protected setup() { const collection = pullFromCache<Amity.GlobalFeedLiveCollectionCache>(this.cacheKey)?.data; if (!collection) { pushToCache(this.cacheKey, { data: [], params: {}, }); } } protected async persistModel(queryPayload: Amity.PostPayload & Amity.Pagination) { await this.queryStreamController.saveToMainDB(queryPayload); } protected persistQueryStream({ response, direction, refresh, }: Amity.LiveCollectionPersistQueryStreamParams<'post'>) { this.queryStreamController.appendToQueryStream(response, direction, refresh); } startSubscription() { return this.queryStreamController.subscribeRTE(getGlobalFeedSubscriptions(this.cacheKey)); } notifyChange({ origin, loading, error }: Amity.LiveCollectionNotifyParams) { const collection = pullFromCache<Amity.GlobalFeedLiveCollectionCache>(this.cacheKey)?.data; if (!collection) return; const data = ( collection.data .map(id => pullFromCache<Amity.InternalPost>(['post', 'get', id])!) .filter(isNonNullable) .map(({ data }) => data) ?? [] ).map(LinkedObject.post); if (!this.shouldNotify(data) && origin === 'event') return; this.callback({ onNextPage: () => this.loadPage({ direction: Amity.LiveCollectionPageDirection.NEXT }), data, hasNextPage: !!this.paginationController.getNextToken(), loading, error, }); } }