49 lines
1.6 KiB
JavaScript
49 lines
1.6 KiB
JavaScript
import { execute, makePromise, ApolloLink } from 'apollo-link';
|
|
import { HttpLink } from 'apollo-link-http';
|
|
import gql from 'graphql-tag';
|
|
const { includeCredentials } = require('./middleware');
|
|
import { onError } from 'apollo-link-error';
|
|
import { default as webAuth} from '../auth';
|
|
|
|
const defaultGraphUri = '/graph/';
|
|
const httpLink = new HttpLink({ uri: defaultGraphUri, fetch: includeCredentials, credentials: 'same-origin' });
|
|
const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
|
|
if (graphQLErrors) {
|
|
console.log('GraphQL errors:', graphQLErrors);
|
|
// for (let err of graphQLErrors) {
|
|
// switch (err.extensions.code) {
|
|
// case 'UNAUTHENTICATED':
|
|
// // error code is set to UNAUTHENTICATED
|
|
// // when AuthenticationError thrown in resolver
|
|
//
|
|
// // modify the operation context with a new token
|
|
// }
|
|
// }
|
|
}
|
|
if (networkError) {
|
|
if (networkError.statusCode === 401) {
|
|
webAuth.checkSession((response) => {
|
|
const oldHeaders = operation.getContext().headers;
|
|
operation.setContext({
|
|
headers: {
|
|
...oldHeaders,
|
|
authorization: webAuth.idToken(),
|
|
},
|
|
});
|
|
return forward(operation);
|
|
}, (err) => {
|
|
console.log(err);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
);
|
|
|
|
export const createQuery = (query, variables) => { // eslint-disable-line
|
|
const operation = {
|
|
query: gql(query),
|
|
variables: variables
|
|
};
|
|
return makePromise(execute(ApolloLink.from([errorLink, httpLink]), operation));
|
|
};
|