All files / src/helpers/comemrcetoolsLink index.ts

62.26% Statements 33/53
50% Branches 1/2
26.67% Functions 4/15
69.77% Lines 30/43

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 913x 3x 3x 3x 3x 3x 3x 3x   3x 3x   3x   3x 1x                     3x 1x                         3x             3x 1x 1x   1x 1x 1x   1x       1x               1x                 1x   1x               3x 3x 3x    
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { ApolloLink } from 'apollo-link';
import fetch from 'isomorphic-fetch';
import SdkAuth, { TokenProvider } from '@commercetools/sdk-auth';
import { asyncMap } from '@apollo/client/utilities';
import { Logger } from '@vue-storefront/core';
import { onError } from 'apollo-link-error';
import { Config, ApiConfig } from './../../types/setup';
import { handleBeforeAuth, handleAfterAuth, handleErrors } from './linkHandlers';
import { isAnonymousSession, isUserSession } from './helpers';
 
const getAccessToken = (token) => token ? token.access_token : null;
 
const createAuthClient = (config: ApiConfig): SdkAuth =>
  new SdkAuth({
    host: config.authHost,
    projectKey: config.projectKey,
    disableRefreshToken: false,
    credentials: {
      clientId: config.clientId,
      clientSecret: config.clientSecret
    },
    scopes: config.scopes
  });
 
const createTokenProvider = (settings: Config, { sdkAuth, currentToken }) =>
  new TokenProvider({
    sdkAuth,
    fetchTokenInfo: (sdkAuthInstance) => sdkAuthInstance.clientCredentialsFlow(),
    onTokenInfoChanged: (tokenInfo) => {
      Logger.debug('TokenProvider.onTokenInfoChanged', getAccessToken(tokenInfo));
      settings.auth.onTokenChange(tokenInfo);
    },
    onTokenInfoRefreshed: (tokenInfo) => {
      Logger.debug('TokenProvider.onTokenInfoRefreshed', getAccessToken(tokenInfo));
 
    }
  }, currentToken);
 
const createHeaders = (currentHeaders, token) => ({
  headers: {
    ...currentHeaders,
    authorization: `Bearer ${token.access_token}`
  }
});
 
const createCommerceToolsConnection = (settings: Config): any => {
  let currentToken: any = settings.auth.onTokenRead();
  Logger.debug('createCommerceToolsConnection', getAccessToken(currentToken));
 
  const sdkAuth = createAuthClient(settings.api);
  const tokenProvider = createTokenProvider(settings, { sdkAuth, currentToken });
  const httpLink = createHttpLink({ uri: settings.api.uri, fetch });
 
  const onErrorLink = onError(({ graphQLErrors, networkError }) => {
    handleErrors({ graphQLErrors, networkError });
  });
 
  const authLinkBefore = setContext(async (apolloReq, { headers }) => {
    Logger.debug('Apollo authLinkBefore', apolloReq.operationName);
    currentToken = await handleBeforeAuth({ sdkAuth, tokenProvider, apolloReq, currentToken });
    Logger.debug('Apollo authLinkBefore, finished, generated token: ', getAccessToken(currentToken));
 
    return createHeaders(headers, currentToken);
  });
 
  const authLinkAfter = new ApolloLink((apolloReq, forward): any => {
    return asyncMap(forward(apolloReq) as any, async (response) => {
      Logger.debug('Apollo authLinkAfter', apolloReq.operationName);
      currentToken = await handleAfterAuth({ sdkAuth, tokenProvider, apolloReq, currentToken });
 
      return response;
    });
  });
 
  const apolloLink = ApolloLink.from([onErrorLink, authLinkBefore, authLinkAfter.concat(httpLink)]);
 
  return {
    apolloLink,
    sdkAuth,
    tokenProvider
  };
};
 
export {
  isAnonymousSession,
  isUserSession,
  createCommerceToolsConnection
};