import { NgModule } from '@angular/core'; import { ApolloLink } from 'apollo-link'; import { onError } from 'apollo-link-error'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { Apollo, ApolloModule } from 'apollo-angular'; import { HttpClientModule } from '@angular/common/http'; import { HttpLink, HttpLinkModule } from 'apollo-angular-link-http'; import { GqlService } from './services'; import { colorsEnum } from '../../shared/enums'; import { environment } from '../../../environments/environment'; import { ToastModule, toastPositionEnum, ToastService } from '../../elements/toast'; @NgModule({ imports: [ ApolloModule, HttpLinkModule, HttpClientModule, ToastModule, ], providers: [ GqlService, ], }) export class GqlModule { constructor( private readonly apollo: Apollo, private readonly httpLink: HttpLink, private readonly toastService: ToastService, ) { const errorLink = this.handleOnError(); const httpLinked = this.httpLink.create({ uri: environment.uri }); const httpLinkWithErrorHandling = ApolloLink.from([ errorLink, httpLinked, ]); this.apollo.create({ cache: new InMemoryCache(), link: httpLinkWithErrorHandling, }); } private handleOnError() { return onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) { graphQLErrors.map(({ message }) => this.errorMessage(message)); } if (networkError) { this.errorMessage(networkError.message); } }); } private errorMessage(message): void { if (environment.production) { message = 'Error: Cable crossing'; } this.openToast(message); } private openToast(message: string): void { this.toastService.open({ message, dismissible: false, type: colorsEnum.error, position: toastPositionEnum.topCenter, }); } }