import { Observable, Subject } from 'rxjs'; import { takeWhile, takeUntil, filter, distinctUntilKeyChanged, map, share, } from 'rxjs/operators'; import { constants } from '../common'; import { GraphqlEvent, GraphqlNetworkEvent } from './types'; import { onError, ApolloLink } from './libs'; const { IS_BROWSER } = constants; export { GraphqlEvent, GraphqlNetworkEvent }; export interface IGraphqlEvents { events$: Observable; network$: Observable; errorLink: ApolloLink; next: (e: GraphqlEvent) => void; dispose: () => void; createId: (prefix: string) => string; } let count = 0; /** * Initializes events for a graphql connection. */ export function init(): IGraphqlEvents { const disposed$ = new Subject(); const subject$ = new Subject(); const events$ = subject$.pipe( takeWhile(() => IS_BROWSER), takeUntil(disposed$), ); const errorLink: any = onError(payload => api.next({ id: api.createId('error'), type: 'ERROR', payload }), ); const api = { events$, network$: monitorNetwork(events$), errorLink, createId(prefix: string) { count++; return `${prefix}:${count}`; }, next: (e: GraphqlEvent) => subject$.next(e), dispose: () => disposed$.next(), }; return api; } /** * INTERNAL */ function monitorNetwork(events$: Observable) { let count = 0; const networkCount$ = new Subject<{ count: number }>(); events$ // Monitor network activity. .pipe(filter(e => e.type !== 'ERROR')) .subscribe(e => { if (e.type.endsWith('START')) { count++; } if (e.type.endsWith('COMPLETE')) { count--; } networkCount$.next({ count }); }); return networkCount$.pipe( map(({ count }) => ({ isActive: count > 0, count })), distinctUntilKeyChanged('isActive'), share(), ); }