import { Store , createStore } from "./store.js" ; import { Connection } from "./connection.js" ; import { UnsubscribeFunc } from "./types.js" ; export type Collection < State > = { state : State ; refresh ( ) : Promise < void > ; subscribe ( subscriber ) : UnsubscribeFunc ; } ; export const getCollection = < State > ( conn , key , fetchCollection , subscribeUpdates ? ) : Collection < State > => { if ( conn [ key ] ) { return conn [ key ] ; } let active = 0 ; let unsubProm ; let store = createStore < State > ( ) ; const refresh = ( ) => fetchCollection ( conn ) . then ( ( state ) => store . setState ( state , true ) ) ; const refreshSwallow = ( ) => refresh ( ) . catch ( ( err ) => { if ( conn . connected ) { throw err ; } } ) ; conn [ key ] = { get state ( ) { return store . state ; } , refresh , subscribe ( subscriber ) { active ++ ; if ( active === 1 ) { if ( subscribeUpdates ) { unsubProm = subscribeUpdates ( conn , store ) ; } conn . addEventListener ( "ready" , refreshSwallow ) ; refreshSwallow ( ) ; } const unsub = store . subscribe ( subscriber ) ; if ( store . state !== undefined ) { setTimeout ( ( ) => subscriber ( store . state ! ) , 0 ) ; } return ( ) => { unsub ( ) ; active -- ; if ( ! active ) { if ( unsubProm ) unsubProm . then ( ( unsub ) => { unsub ( ) ; } ) ; conn . removeEventListener ( "ready" , refresh ) ; } } ; } , } ; return conn [ key ] ; } ; export const createCollection = < State > ( key , fetchCollection , subscribeUpdates , conn , onChange ) : UnsubscribeFunc => getCollection ( conn , key , fetchCollection , subscribeUpdates ) . subscribe ( onChange ) ;