Created
December 9, 2019 13:06
-
-
Save Supamiu/354030d8fc09b93437985cdefe88d345 to your computer and use it in GitHub Desktop.
Example interceptor for apollo-angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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