6
votes

we are using Apollo/Graphql in our application, and we are facing an issue.

The application is developed in Angular 5, and NodeJS as backend with graphql server that will respond to the front end. To intercept Http request in angular, we implement the 'HttpInterceptor' so we can handle the errors in our customized way. But, Apollo request do not pass thru this intercepter.

To handle the errors correctly, we are using 'apollo-link-error'.

But we would like to know if it's possible to intercept apollo requests in a similar way as HttpInterceptor.

3

3 Answers

2
votes

I think the official way to intercept Apollo Client requests is through Apollo Links.

However, if you are using Angular, it is also possible to do it via HttpInterceptor. You can take a look at this article I published on how to manage access/refresh tokens using Angular's HttpInterceptor when working with Apollo Client.

Hope this helps.

1
votes

Hi I had the same issue,

a red that:

Apollo Links make creating middlewares that lets you modify requests before they are sent to the server

Apollo Middleware

Apollo 2.0 Auth

here is the example:

import { HttpHeaders } from '@angular/common/http';
import { Apollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

@NgModule({ ... })
class AppModule {
  constructor(
    apollo: Apollo,
    httpLink, HttpLink
  ) {
    const http = httpLink.create({uri: '/graphql'});

    const auth = setContext((_, { headers }) => {
      // get the authentication token from local storage if it exists
      const token = localStorage.getItem('token');
      // return the headers to the context so httpLink can read them
      // in this example we assume headers property exists
      // and it is an instance of HttpHeaders
      if (!token) {
        return {};
      } else {
        return {
          headers: headers.append('Authorization', `Bearer ${token}`)
        };
      }
    });

    apollo.create({
      link: auth.concat(http),
      // other options like cache
    });
  }
}
0
votes

I recently came across the same problem and was able to solve it by capturing the response and modifying it.

import { asyncMap } from '@apollo/client/utilities';
import {
  concat
} from '@apollo/client';    


return asyncMap(forward(operation), async (response) => {
        let data: any = response.data;
        
        // modify anything you want here
    
        return response;
      });
    });

const client = new ApolloClient({


 link: concat(authMiddleware, httpLink),
  cache: new InMemoryCache(),
});

Its a different library, but you could try something like this.