All files / src/api/updateCart index.ts

100% Statements 20/20
83.33% Branches 20/24
100% Functions 2/2
100% Lines 18/18

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 558x 8x 8x   8x     8x                 13x 13x 13x               13x     13x           10x   3x 3x   3x 2x     1x   1x             8x  
import gql from 'graphql-tag';
import { Logger } from '@vue-storefront/core';
import defaultQuery from './defaultMutation';
import { CustomQueryFn } from './../../types/Api';
import { getCustomQuery } from './../../helpers/queries';
import { CartUpdateAction, MyCartUpdateAction } from '../../types/GraphQL';
 
const VERSION_MISSMATCH_CODE = 'ConcurrentModification';
 
export interface UpdateCartParams {
  id: string;
  version: number;
  actions: CartUpdateAction[] | MyCartUpdateAction[];
  versionFallback?: boolean;
}
 
const updateCart = async (context, params: UpdateCartParams, customQueryFn?: CustomQueryFn) => {
  const { locale, acceptLanguage } = context.config;
  const defaultVariables = params
    ? {
      locale,
      acceptLanguage,
      ...params
    }
    : { acceptLanguage };
 
  const { query, variables } = getCustomQuery(customQueryFn, { defaultQuery, defaultVariables });
 
  try {
    const request = await context.client.mutate({
      mutation: gql`${query}`,
      variables,
      fetchPolicy: 'no-cache'
    });
 
    return request;
  } catch (error) {
    const canRetry = params.versionFallback ?? true;
    const causedByMissmatch = error.graphQLErrors?.[0]?.code?.includes(VERSION_MISSMATCH_CODE);
 
    if (!causedByMissmatch || !canRetry) {
      throw error;
    }
 
    Logger.debug('Cart version missmatch. Retrying with current version.');
 
    return updateCart(context, {
      ...params,
      version: error.graphQLErrors[0].currentVersion
    });
  }
};
 
export default updateCart;