File

src/services/apollo.service.ts

Index

Properties
Methods

Constructor

constructor(apollo: Apollo, httpLink: HttpLink, config: GapiApolloClientOptions)
Parameters :
Name Type Optional Description
apollo Apollo
httpLink HttpLink
config GapiApolloClientOptions

Methods

createClientWithSubscriptions
createClientWithSubscriptions()
Returns : void
createHttpClient
createHttpClient()
Returns : void
importQuery
importQuery(search: )
Parameters :
Name Type Optional Description
search
Returns : any
init
init()
Returns : void
mutation
mutation(options: MutationOptions | string, variables?: )
Parameters :
Name Type Optional Description
options MutationOptions | string
variables true
Returns : Observable<literal type>
query
query(options: WatchQueryOptions | string, variables?: )
Parameters :
Name Type Optional Description
options WatchQueryOptions | string
variables true
Returns : Observable<literal type>
resetStore
resetStore()
Returns : Promise<[]>
setAuthorizationToken
setAuthorizationToken(token: string)
Parameters :
Name Type Optional Description
token string
Returns : void
subscription
subscription(options: SubscriptionOptions | string)
Parameters :
Name Type Optional Description
options SubscriptionOptions | string
Returns : Observable<literal type>

Properties

graphqlDocs
graphqlDocs:
http
http: HttpLinkHandler
Type : HttpLinkHandler
webSocketLink
webSocketLink: WebSocketLink
Type : WebSocketLink
import { Injectable, Inject } from '@angular/core';
import { ApolloModule, Apollo, QueryRef } from 'apollo-angular';
import { HttpLinkModule, HttpLink, HttpLinkHandler } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { GapiApolloClientOptions, GAPI_APOLLO_MODULE_CONFIG } from '../config';
import { Observable } from 'rxjs/Observable';
import { WatchQueryOptions, ApolloQueryResult, SubscribeToMoreOptions, SubscriptionOptions, MutationOptions } from 'apollo-client';
import { HttpHeaders } from '@angular/common/http';
import { ApolloLink, concat, split } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';

@Injectable()
export class GapiApolloService {
    http: HttpLinkHandler = this.httpLink.create({ uri: this.config.uri });
    graphqlDocs;
    webSocketLink: WebSocketLink;
    constructor(
        private apollo: Apollo,
        private httpLink: HttpLink,
        @Inject(GAPI_APOLLO_MODULE_CONFIG) private config: GapiApolloClientOptions
    ) {
        if (!this.config.documents) {
            throw new Error('You must declare variable DOCUMENTS');
        }
        this.graphqlDocs = this.config.documents;
    }

    init() {
        if (this.config.subscriptionsUri) {
            this.createClientWithSubscriptions();
        } else {
            this.createHttpClient();
        }
    }

    importQuery(search) {
        let result;
        Object.keys(this.graphqlDocs)
            .filter(doc => {
                if (doc.indexOf(search) !== -1) {
                    result = this.graphqlDocs[doc];
                }
            });
        if (!result) {
            throw new Error(`Missing query: ${search}`);
        }
        return result;
    }

    createHttpClient() {
        this.apollo.create({
            link: concat(new ApolloLink((operation, forward) => {
                operation.setContext({
                    headers: new HttpHeaders().set('Authorization', this.config.authorization)
                });
                return forward(operation);
            }), this.http),
            cache: new InMemoryCache()
        });

    }

    setAuthorizationToken(token: string) {
        this.config.authorization = token;
    }

    createClientWithSubscriptions() {
        this.webSocketLink = new WebSocketLink({
            uri: this.config.subscriptionsUri,
            options: {
                reconnect: true,
                connectionParams: {
                    token: this.config.authorization,
                },
            }
        });

        this.apollo.create({
            link: concat(new ApolloLink((operation, forward) => {
                operation.setContext({
                    // tslint:disable-next-line:max-line-length
                    headers: new HttpHeaders().set('Authorization', this.config.authorization)
                });
                return forward(operation);
            }), split(
                // split based on operation type
                ({ query }) => {
                    const { kind, operation } = <any>getMainDefinition(query);
                    return kind === 'OperationDefinition' && operation === 'subscription';
                },
                this.webSocketLink,
                this.http,
                )),
            cache: new InMemoryCache()
        });
    }

    mutation<T>(options: MutationOptions | string, variables?): Observable<{ data: T }> {
        if (options.constructor === String) {
            options = { mutation: this.importQuery(options), variables };
        }
        return this.apollo.mutate(<any>options)
    }

    query<T>(options: WatchQueryOptions | string, variables?): Observable<{ data: T }> {
        if (options.constructor === String) {
            options = { query: this.importQuery(options), variables };
        }
        return Observable.create((observer) => {
            const subscription = this.apollo.watchQuery(<any>options)
                .valueChanges
                .subscribe(
                    (data) => observer.next(data),
                    (e) => {
                        observer.error(e);
                        subscription.unsubscribe();
                    }
                );
        });
    }

    subscription<T>(options: SubscriptionOptions | string): Observable<{ data: T }> {
        if (options.constructor === String) {
            options = { query: this.importQuery(options) };
        }
        return this.apollo.subscribe(<any>options);
    }

    resetStore(): Promise<ApolloQueryResult<any>[]> {
        this.webSocketLink['subscriptionClient'].close();
        return this.apollo.getClient().resetStore();
    }
}

results matching ""

    No results matching ""