@amityco/ts-sdk-react-native
Version:
Amity Social Cloud Typescript SDK
96 lines (80 loc) • 3.15 kB
text/typescript
import hash from 'object-hash';
import { pullFromCache, pushToCache } from '~/cache/api';
import { CustomRankingGlobalFeedPaginationController } from './PaginationController';
import { CustomRankingGlobalFeedQueryStreamController } 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 CustomRankingGlobalFeedLiveCollectionController extends LiveCollectionController<
'post',
Amity.CustomRankingGlobalFeedLiveCollection,
Amity.Post,
CustomRankingGlobalFeedPaginationController
> {
private queryStreamController: CustomRankingGlobalFeedQueryStreamController;
private query: Amity.CustomRankingGlobalFeedLiveCollection;
constructor(
query: Amity.CustomRankingGlobalFeedLiveCollection,
callback: Amity.LiveCollectionCallback<Amity.Post>,
) {
const queryStreamId = hash(query);
const cacheKey = ['customRankingGlobalFeed', 'collection', queryStreamId];
const paginationController = new CustomRankingGlobalFeedPaginationController(query);
super(paginationController, queryStreamId, cacheKey, callback);
this.query = query;
this.queryStreamController = new CustomRankingGlobalFeedQueryStreamController(
this.query,
this.cacheKey,
this.notifyChange.bind(this),
preparePostPayload,
);
this.callback = callback.bind(this);
this.loadPage({ initial: true });
}
protected setup() {
const collection = pullFromCache<Amity.CustomRankingGlobalFeedLiveCollectionCache>(
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.CustomRankingGlobalFeedLiveCollectionCache>(
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,
});
}
}