All files / src/helpers/comemrcetoolsLink linkHandlers.ts

12.24% Statements 6/49
0% Branches 0/18
0% Functions 0/5
19.35% Lines 6/31

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  3x 3x 3x   3x                                   3x                             3x                              
 
import { Logger } from '@vue-storefront/core';
import { isAnonymousSession, isUserSession, getAccessToken } from './helpers';
import { isAnonymousOperation, isUserOperation } from './restrictedOperations';
 
export const handleBeforeAuth = async ({ sdkAuth, tokenProvider, apolloReq, currentToken }) => {
  const isAnonymous = isAnonymousSession(currentToken);
  const isUser = isUserSession(currentToken);
  const isGuest = !isAnonymous && !isUser;
 
  if (isGuest && isAnonymousOperation(apolloReq.operationName)) {
    Logger.debug('Apollo authLinkBefore, anonymousFlow', apolloReq.operationName);
 
    const token = await sdkAuth.anonymousFlow();
    tokenProvider.setTokenInfo(token);
    Logger.debug('Apollo authLinkBefore, anonymousFlow, generated token: ', getAccessToken(token));
 
    return token;
  }
 
  return tokenProvider.getTokenInfo();
};
 
export const handleAfterAuth = async ({ sdkAuth, tokenProvider, apolloReq, currentToken }) => {
  if (!isUserSession(currentToken) && isUserOperation(apolloReq.operationName)) {
    const { email, password } = apolloReq.variables.draft;
    Logger.debug('Apollo authLinkAfter, customerPasswordFlow', apolloReq.operationName);
 
    const token = await sdkAuth.customerPasswordFlow({ username: email, password });
    tokenProvider.setTokenInfo(token);
    Logger.debug('Apollo authLinkAfter, customerPasswordFlow, generated token: ', getAccessToken(token));
 
    return token;
  }
 
  return currentToken;
};
 
export const handleErrors = ({ 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')) {
        Logger.error(`[GraphQL error]: Message: ${message}, Location: ${parsedLocations.join(', ')}, Path: ${path}`);
      }
    });
  }
 
  if (networkError) {
    Logger.error(`[Network error]: ${networkError}`);
  }
};