Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept Apollo/graphql requests

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.

like image 936
ezay Avatar asked May 23 '18 06:05

ezay


2 Answers

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.

like image 151
kctang Avatar answered Oct 19 '22 22:10

kctang


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
    });
  }
}
like image 45
ALGDB Avatar answered Oct 19 '22 22:10

ALGDB