Apollo GraphQL - watchQuery and networkErrors issue

Viewed 1018

TL;DR;

When the graphQL server is not available, watchQuery loading flag never changes to false, thus the error handling should be done with apollo-link-error.

Is there any way to fix the issue with watchQuery?


I've developed a small Angular GraphQL app. One of the features is triggering a simple query like this one:

  this.apollo
    .watchQuery<any>({
      query: this.BookingByID,
      variables: {
        bookingCode: id
      }
    })
    .valueChanges.subscribe(result => {
      this.booking = result.data.booking;
      this.loading = result.loading;
      this.error = result.errors;
    });

I wanted to test the app behavior when the network or the Graphql server are failing. These are the scenarios that I tried.

  • No Internet Connection
  • GraphQL Server unreachable.

No Internet Connection

Without internet connection this.error works fine. I'm able to detect the error and to display the proper message.

GraphQL Server unreachable

When the GraphQL server is not available I'm experiencing an issue. The query loading status remains "true" even when I get a network error. (Apollo Error. Code 0. Unknown error).

After doing some research I read that apollo-link-error module allows you to handle the networkErrors in a better way. So I've implemented something like this.

import { NgModule } from '@angular/core';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache} from 'apollo-cache-inmemory';
import { onError } from 'apollo-link-error';

const uri = 'http://localhost:4000'; // <-- add the URL of the GraphQL server here

export function createApollo( httpLink: HttpLink ) {
  const http = httpLink.create({uri});
  const error = onError(({networkError}) => {
    console.log(networkError);
  });

  return {
    link: error.concat(http),
    cache: new InMemoryCache(),
    defaultOptions: {
      watchQuery: {
        errorPolicy: 'all'
      }
    }
  };
}

@NgModule({
  exports: [ApolloModule, HttpLinkModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

After implementing apollo-link-error, I'm able to see the error in the browser console. But I'm still wondering why does watchQuery loading status indicator not change from loading=true to loading=false.

template.html

<p *ngIf="loading">Loading...</p>
<p *ngIf="error">{{ error | json }}</p>

If the solution is to move on with the apollo-link-error approach, what is the proper way of doing it? How should I notify the view about the error? Parameter? Route? Is there any best practice? Am I missing something here?

Thanks in advance,

Guillermo

0 Answers
Related