All files / src/helpers/createCommerceToolsLink index.ts

92.11% Statements 35/38
100% Branches 7/7
80% Functions 4/5
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 5328x 28x 28x 28x 28x 28x 28x   28x         28x 5x 5x 5x 5x         5x   5x               5x 4x 3x 2x   2x 1x         4x 1x       5x     28x  
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { ApolloLink } from 'apollo-link';
import fetch from 'isomorphic-fetch';
import createAccessToken from './../createAccessToken';
import { getSettings } from './../../index';
import { onError } from 'apollo-link-error';
 
const restrictedOperations = [
  'getMe',
  'createCart'
];
 
const createCommerceToolsLink = (): ApolloLink => {
  const { api, currentToken, auth } = getSettings();
  const httpLink = createHttpLink({ uri: api.uri, fetch });
  const authLink = setContext(async (req, { headers }) => {
    const token = await createAccessToken({
      currentToken,
      requireUserSession: restrictedOperations.includes(req.operationName)
    });
 
    auth.onTokenChange(token);
 
    return {
      headers: {
        ...headers,
        authorization: `Bearer ${token.access_token}`
      }
    };
  });
 
  const onErrorLink = onError(({ graphQLErrors, networkError }) => {
    if (graphQLErrors) {
      graphQLErrors.map(({ message, locations, path }) => {
        const parsedLocations = locations.map(({ column, line }) => `[column: ${column}, line: ${line}]`);
 
        if (!message.includes('Resource Owner Password Credentials Grant')) {
          console.error(`[GraphQL error]: Message: ${message}, Location: ${parsedLocations.join(', ')}, Path: ${path}`);
        }
      });
    }
 
    if (networkError) {
      console.error(`[Network error]: ${networkError}`);
    }
  });
 
  return ApolloLink.from([onErrorLink, authLink, httpLink]);
};
 
export default createCommerceToolsLink;