import { DocMetaMutation , DocMetaSnapshotEvent , DocMetaSnapshotEventListener } from './Datastore' ; import { DocMetaComparisonIndex } from './DocMetaComparisonIndex' ; import { IDocInfo } from 'polar-shared/src/metadata/IDocInfo' ; export class DocMetaSnapshotEventListeners { /**
     * Create a new listener that takes inputs and creates a de-duplicated
     * listener that only emits new or updated documents by the UUID or deleted
     * documents.
     *
     * This work with one ore more listeners which enables us to have
     * existing listeners that sends from IPC as well the firebase listeners
     * and we will just get the earliest one.
     *
     */ public static createDeduplicatedListener ( outputListener , docMetaComparisonIndex = new DocMetaComparisonIndex ( ) ) { if ( ! docMetaComparisonIndex ) { docMetaComparisonIndex = new DocMetaComparisonIndex ( ) ; } const listener = async ( docMetaSnapshotEvent ) => { const acceptedDocMetaMutations = [ ] ; for ( const docMetaMutation of docMetaSnapshotEvent . docMetaMutations ) { const docInfo = await docMetaMutation . docInfoProvider ( ) ; if ( docMetaComparisonIndex . handleDocMetaMutation ( docMetaMutation , docInfo ) ) { acceptedDocMetaMutations . push ( docMetaMutation ) ; } } await outputListener ( { ... docMetaSnapshotEvent , docMetaMutations : acceptedDocMetaMutations , } ) ; } ; return { handleDocMetaMutation : docMetaComparisonIndex . handleDocMetaMutation . bind ( docMetaComparisonIndex ) , listener , } ; } } export interface EventDeduplicator { handleDocMetaMutation ( docMetaMutation , docInfo ) : boolean ; listener : DocMetaSnapshotEventListener ; }