UNPKG

@amityco/ts-sdk-react-native

Version:

Amity Social Cloud Typescript SDK

60 lines (50 loc) 1.75 kB
import { ASCError } from '~/core/errors'; import { onLiveReactionCreated } from '../events'; import { getActiveClient, getActiveUser } from '~/client'; import { onLiveReactionCreatedLocal } from '../events/onLiveReactionCreatedLocal'; /** * * ```js * import { getReactions } from '@amityco/ts-sdk'; * * const unsubscribe = getReactions(response => { * reactions = response.data * }); * ``` * * Observe live reactions {@link_Amity.LiveReaction} that have been created in a post linked with a stream * * @param callback the function to call when new data are available * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the events * * @category Live Reaction Observable */ // TODO: confirm return type for this observable property export const getReactions = ( postId: string, callback: Amity.Listener<Amity.LiveReaction[]>, ): Amity.Unsubscriber => { const { _id: userId } = getActiveUser(); if (!userId) throw new ASCError( 'The _id has not been defined in ActiveUser', Amity.ClientError.UNKNOWN_ERROR, Amity.ErrorLevel.ERROR, ); const { log } = getActiveClient(); const timestamp = Date.now(); log(`getReactions(tmpid: ${timestamp}) > listen`); const disposers: Amity.Unsubscriber[] = []; const dispatcher = (data: Amity.LiveReaction[]) => { callback(data); }; const realtimeRouter = (data: Amity.LiveReaction[]) => { const relevantReactions = data.filter(({ referenceId }) => referenceId === postId); dispatcher(relevantReactions); }; disposers.push(onLiveReactionCreated(realtimeRouter)); disposers.push(onLiveReactionCreatedLocal(realtimeRouter)); return () => { disposers.forEach(fn => fn()); }; };