Created
February 8, 2020 03:40
-
-
Save waiholiu/b3c7c3f77106f64cebe3769298496f85 to your computer and use it in GitHub Desktop.
graphql.module.ts (local)
This file contains 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 { LocalStorageService } from 'angular-2-local-storage'; | |
import { NgModule } from '@angular/core'; | |
import { ApolloModule, APOLLO_OPTIONS, Apollo } from 'apollo-angular'; | |
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http'; | |
import { InMemoryCache } from 'apollo-cache-inmemory'; | |
import { ApolloLink } from 'apollo-link'; | |
import { environment } from 'src/environments/environment'; | |
// const uri = 'https://o5x5jzoo7z.sse.codesandbox.io/graphql'; //our test Graphql Server which returns rates | |
const uri = environment.serverUrl + '/graphql'; | |
export function createApollo(httpLink: HttpLink, localStorage: LocalStorageService) { | |
const http = httpLink.create({ uri }); | |
const authLink = new ApolloLink((operation, forward) => { | |
// Get the authentication token from local storage if it exists | |
const token = localStorage.get('loginToken'); | |
// Use the setContext method to set the HTTP headers. | |
operation.setContext({ | |
headers: { | |
'Authorization': token ? `Bearer ${token}` : '' | |
} | |
}); | |
// Call the next link in the middleware chain. | |
return forward(operation); | |
}); | |
return { | |
link: authLink.concat(http), | |
cache: new InMemoryCache() | |
}; | |
} | |
@NgModule({ | |
exports: [ApolloModule, HttpLinkModule], | |
providers: [ | |
{ | |
provide: APOLLO_OPTIONS, | |
useFactory: createApollo, | |
deps: [HttpLink, LocalStorageService], | |
}, | |
], | |
}) | |
export class GraphQLModule {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment