import { Observable, Subject } from 'rxjs'; import { share, take } from 'rxjs/operators'; import { IGraphqlEvents } from '../events'; import { ApolloClient, NormalizedCacheObject } from '../libs'; import { GraphqlEvent, GraphqlMutationOptions, GraphqlMutationResult, GraphqlNetworkEvent, GraphqlQueryResult, GraphqlWatchQueryOptions, IGraphqlClient, } from '../types'; /** * Thin wrapper around Apollo client. */ export class GraphqlClient implements IGraphqlClient { private client: ApolloClient; private events: IGraphqlEvents; public events$: Observable; public network$: Observable; public constructor( client: ApolloClient, events: IGraphqlEvents, ) { this.client = client; this.events = events; this.events$ = events.events$; this.network$ = events.network$; } /** * Queries the GraphQL API */ public async query( options: GraphqlWatchQueryOptions, ): Promise> { // Fire pre-event. const id = this.events.createId('query'); this.events.next({ id, type: 'QUERY_START', payload: { options } }); // Invoke query. const result = await this.client.query(options); // Fire post-event. this.events.next({ id, type: 'QUERY_COMPLETE', payload: { options, result }, }); return result; } /** * Queries the GraphQL API returning an observable * that fires once with the result. */ public query$( options: GraphqlWatchQueryOptions, ): Observable> { const subject = new Subject>(); this.query(options) .then(response => { subject.next(response); subject.complete(); }) .catch(error => subject.error(error)); return subject.pipe( take(1), share(), ); } /** * Sends a mutation to the GraphQL API. */ public async mutate( options: GraphqlMutationOptions, ): Promise> { // Fire pre-event. const id = this.events.createId('mutate'); this.events.next({ id, type: 'MUTATION_START', payload: { options } }); // Invoke mutation. const result = (await this.client.mutate( options, )) as GraphqlMutationResult; // Fire post-event. this.events.next({ id, type: 'MUTATION_COMPLETE', payload: { options, result }, }); return result; } }