All files / src/api/updateCart index.ts

68.18% Statements 15/22
25% Branches 3/12
100% Functions 2/2
68.42% Lines 13/19

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 5510x 10x     10x 10x 10x   10x                 10x 9x 9x               9x     9x           9x                                 10x  
import { Logger } from '@vue-storefront/core';
import getMe from '../getMe';
import { CartUpdateAction, MyCartUpdateAction } from '../../types/GraphQL';
import { CustomQueryFn } from './../../types/Api';
import defaultQuery from './defaultMutation';
import gql from 'graphql-tag';
import { getCustomQuery } from './../../helpers/queries';
 
const VERSION_MISSMATCH_STRING = 'different version than expected';
 
interface UpdateCart {
  id: string;
  version: number;
  actions: CartUpdateAction[] | MyCartUpdateAction[];
  versionFallback?: boolean;
}
 
const updateCart = async (context, params: UpdateCart, 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 retry = params.versionFallback ?? true;
    if (!(error.toString().includes(VERSION_MISSMATCH_STRING) && retry)) {
      throw error;
    }
 
    Logger.debug('Cart version missmatch. Fetching new version and retrying.');
 
    const { data } = await getMe(context, { customer: false });
    return updateCart(context, {
      ...params,
      version: data.me.activeCart.version
    });
  }
};
 
export default updateCart;