Skip to content

Instantly share code, notes, and snippets.

@Supamiu
Created December 9, 2019 13:06
Show Gist options
  • Save Supamiu/354030d8fc09b93437985cdefe88d345 to your computer and use it in GitHub Desktop.
Save Supamiu/354030d8fc09b93437985cdefe88d345 to your computer and use it in GitHub Desktop.
Example interceptor for apollo-angular
import { Injectable } from '@angular/core';
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { filter, switchMap } from 'rxjs/operators';
@Injectable()
export class ApolloInterceptor implements HttpInterceptor {
constructor(private myAuthService: AuthService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler) {
// Filter your endpoint in order to only edit the graphql-related requests
if (req.url.indexOf('/graphql') > -1) {
// Get your jwt from your usual source, can be a facade, a service, or even sync data like localStorage
return this.myAuthService.jwt$
.pipe(
// Make sure the request won't replay when your token gets updated
first(),
switchMap(idToken => {
// Simply add the Authorization header to the request
const clone = req.clone({
setHeaders: {
Authorization: `Bearer ${idToken.token}`
}
});
// And you're done !
return next.handle(clone);
})
);
}
// If it's not a graphql request, just give it to the next handler.
return next.handle(req);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment