All files / src/helpers/commercetoolsLink linkHandlers.ts

100% Statements 43/43
100% Branches 16/16
100% Functions 4/4
100% Lines 31/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 502x 2x 2x   4x 4x 4x 4x   7x 1x   1x 1x 1x   1x     3x     4x 6x 2x 2x   2x 2x 2x   2x     2x     4x 3x 1x     2x 1x 1x 1x   1x    
import { Logger } from '@vue-storefront/core';
import { isAnonymousSession, isUserSession, getAccessToken } from '../utils';
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 handleRetry = ({ tokenProvider }) => (count, operation, error) => {
  if (count > 3) {
    return false;
  }
 
  if (error.result.message === 'invalid_token') {
    Logger.debug(`Apollo retry-link, the operation (${operation.operationName}) sent with wrong token, creating a new one... (attempt: ${count})`);
    tokenProvider.invalidateTokenInfo();
    return true;
  }
  return false;
};