can't call apollo in/from modules #1706
Unanswered
gerhardavon
asked this question in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
We've got a good working application but we can't get a refreshtoken because apollo is undefined.
This happens with 3.0.0-alpha.1 with ApolloModule in GraphQLModule.
But it happens also when we provide APOLLO_OPTIONS in the the root module(AppModule).
And it happens also on staging/production builds. I tested that because i thought it could have something to do with our webpack config that's generation the code.
It also happens when refreshtoken is called in a service
Anyone have any idea what's going on?
`import { ComponentFactoryResolver, NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { ApolloLink, InMemoryCache, DefaultOptions } from '@apollo/client/core';
import { setContext } from "@apollo/client/link/context";
import { environment } from '@environments/environment';
import { onError } from '@apollo/client/link/error';
import { AuthenticationService } from '@services/authentication.service';
import { CookieService } from '@services/cookie.service';
import { RouterModule, Router, Routes, RouterState } from '@angular/router';
import { Apollo, ApolloModule } from 'apollo-angular';
import { RestLink } from "apollo-link-rest";
import { snakeCase } from 'snake-case';
import * as Sentry from "@sentry/angular";
import refresh from '@graphql/webuserPre/refresh.mutation.graphql';
const uri = environment.c_graphQLUrl;
const defaultOptions: DefaultOptions = {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all'
},
mutate: {
errorPolicy: 'all'
}
};
export function provideApollo(
httpLink: HttpLink,
authenticationService: AuthenticationService,
cookieService: CookieService,
router: Router,
apollo: Apollo,
) {
const auth = setContext((_, { headers, ...context }) => {
let jwt = null;
let cookies = document.cookie;
this.cookieStore = {};
if (!!cookies === true) {
const cookiesArr = cookies.split(';');
for (const cookie of cookiesArr) {
const cookieArr = cookie.split('=');
this.cookieStore[cookieArr[0].trim()] = cookieArr[1];
}
jwt = this.cookieStore['jwt'];
}
return {
headers: {
...(jwt ? { authorization: Bearer ${jwt} } : {}),
}
};
});
const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
switch (err.extensions.statusCode) {
case 429:
console.log("Er is een 429 error");
break;
case 401:
// authenticationService.removeJwtCookie();
// sessionStorage.removeItem('user');
// router.navigate(['401']);
// break;
let queryParams: any;
let refreshToken = authenticationService.getRefreshTokenCookie();
apollo.mutate({
mutation: refresh,
variables: {
refreshToken: refreshToken
}
}).toPromise().then(({ data, errors }) => {
if (!errors) {
authenticationService.setJwtCookie(data['refresh'].jwtToken);
authenticationService.setRefreshTokenCookie(data['refresh'].refreshToken);
} else {
authenticationService.removeJwtCookie();
localStorage.removeItem('user');
queryParams = { queryParams: { returnUrl: router.routerState.snapshot.url } };
router.navigate(['/customer/login'], queryParams);
}
return forward(operation);
});
break;
}
if (!environment.production) {
console.log('Response Status: ' + err.extensions.statusCode + ' ' + err.message);
console.log('For operation: ', operation);
}
}
// Broadcast graphQL Error to Sentry:
graphQLErrors.map(({ message, locations, path }) => {
Sentry.captureException(message);
})
}
// Broadcast Network Error to Sentry:
if (networkError) {
console.log([Network error]: ${networkError});
Sentry.captureException(networkError);
}
});
const restLink = new RestLink({
uri: environment.c_apiBaseUrl,
credentials: 'same-origin',
fieldNameDenormalizer: (key: string) => snakeCase(key),
bodySerializers: {
fileEncode: (data: any, headers: Headers) => {
const formData = new FormData();
Object.keys(data).forEach(key => formData.append(key, data[key]));
//
let fileInputs = document.querySelectorAll('input[type=file]');
Array.from(fileInputs).forEach(fileInput => {
// @ts-expect-error: Let's ignore this
let files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
let name = fileInputs[i].getAttribute('id');
formData.append(name, file);
}
});
return { body: formData, headers }
}
}
});
const link = ApolloLink.from([
errorLink,
auth,
restLink,
httpLink.create({ uri })
]);
return {
cache: new InMemoryCache({
addTypename: false
}),
defaultOptions: defaultOptions,
connectToDevTools: true,
link: link
};
}
@NgModule({
imports: [
ApolloModule
],
exports: [
HttpClientModule
],
providers: [{
provide: APOLLO_OPTIONS,
useFactory: provideApollo,
deps: [HttpLink, AuthenticationService, CookieService, Router]
}]
})
export class GraphQLModule {}`
Beta Was this translation helpful? Give feedback.
All reactions