@kiva/kv-shop 2.1.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/_virtual/_commonjs-dynamic-modules.js +6 -0
  2. package/dist/_virtual/_commonjsHelpers.js +8 -0
  3. package/dist/_virtual/_plugin-vue_export-helper.js +9 -0
  4. package/dist/_virtual/dropin.js +11 -0
  5. package/dist/_virtual/dropin2.js +4 -0
  6. package/dist/basket.js +35 -12
  7. package/dist/basketCredits.js +78 -14
  8. package/dist/basketItems.js +27 -8
  9. package/dist/basketTotals.js +38 -10
  10. package/dist/basketVerification.js +6 -6
  11. package/dist/checkoutStatus.js +52 -8
  12. package/dist/components/KvPaymentSelect.css +1 -0
  13. package/dist/components/KvPaymentSelect.js +23 -0
  14. package/dist/components/KvPaymentSelect2.js +110 -0
  15. package/dist/index.d.ts +321 -20
  16. package/dist/index.js +49 -96
  17. package/dist/managedAccount.js +62 -8
  18. package/dist/oneTimeCheckout.js +156 -12
  19. package/dist/receipt.js +143 -12
  20. package/dist/shopError.js +41 -6
  21. package/dist/shopQueries.js +82 -11
  22. package/dist/subscriptionCheckout.js +88 -7
  23. package/dist/useBraintreeDropIn.js +145 -9
  24. package/dist/util/cookie.js +11 -0
  25. package/dist/util/poll.js +17 -0
  26. package/dist/util/redirect.js +8 -0
  27. package/dist/util/visitorId.js +7 -0
  28. package/dist/validatePreCheckout.js +44 -11
  29. package/dist/vendor/braintree-web-drop-in/dist/browser/dropin.js +12223 -0
  30. package/package.json +28 -26
  31. package/dist/basket.cjs +0 -141
  32. package/dist/basket.d.ts +0 -8
  33. package/dist/basketCredits.cjs +0 -250
  34. package/dist/basketCredits.d.ts +0 -32
  35. package/dist/basketItems.cjs +0 -205
  36. package/dist/basketItems.d.ts +0 -26
  37. package/dist/basketTotals.cjs +0 -228
  38. package/dist/basketTotals.d.ts +0 -37
  39. package/dist/basketVerification.cjs +0 -41
  40. package/dist/basketVerification.d.ts +0 -10
  41. package/dist/checkoutStatus.cjs +0 -111
  42. package/dist/checkoutStatus.d.ts +0 -20
  43. package/dist/chunk-4ODZGLWK.js +0 -64
  44. package/dist/chunk-ASZJVUQ7.js +0 -72
  45. package/dist/chunk-FBF4WMN6.js +0 -49
  46. package/dist/chunk-FC4QW6QA.js +0 -106
  47. package/dist/chunk-FCAOCO7O.js +0 -17
  48. package/dist/chunk-GVVI7X2R.js +0 -196
  49. package/dist/chunk-IIN37LC7.js +0 -45
  50. package/dist/chunk-IOZ5ERDX.js +0 -121
  51. package/dist/chunk-KCUOMCSN.js +0 -58
  52. package/dist/chunk-LZ4UMRCV.js +0 -16
  53. package/dist/chunk-RQNRQ2E5.js +0 -155
  54. package/dist/chunk-SRGYGDAX.js +0 -80
  55. package/dist/chunk-TPJPGUO7.js +0 -12
  56. package/dist/chunk-UJXHTR43.js +0 -86
  57. package/dist/chunk-VZ3VDRRP.js +0 -167
  58. package/dist/chunk-Z7JRY3QE.js +0 -34
  59. package/dist/components/KvPaymentSelect.vue +0 -380
  60. package/dist/index.cjs +0 -1227
  61. package/dist/managedAccount.cjs +0 -231
  62. package/dist/managedAccount.d.ts +0 -59
  63. package/dist/oneTimeCheckout.cjs +0 -636
  64. package/dist/oneTimeCheckout.d.ts +0 -21
  65. package/dist/receipt.cjs +0 -191
  66. package/dist/receipt.d.ts +0 -16
  67. package/dist/shopError.cjs +0 -88
  68. package/dist/shopError.d.ts +0 -14
  69. package/dist/shopQueries.cjs +0 -248
  70. package/dist/shopQueries.d.ts +0 -8
  71. package/dist/subscriptionCheckout.cjs +0 -187
  72. package/dist/subscriptionCheckout.d.ts +0 -13
  73. package/dist/useBraintreeDropIn.cjs +0 -258
  74. package/dist/useBraintreeDropIn.d.ts +0 -25
  75. package/dist/validatePreCheckout.cjs +0 -218
  76. package/dist/validatePreCheckout.d.ts +0 -28
@@ -1,64 +0,0 @@
1
- // src/shopError.ts
2
- var ShopError = class extends Error {
3
- constructor({ code, original }, ...params) {
4
- super(...params);
5
- if (Error.captureStackTrace) {
6
- Error.captureStackTrace(this, ShopError);
7
- }
8
- this.name = "ShopError";
9
- this.code = code;
10
- this.original = original;
11
- }
12
- aggregateErrors(errors) {
13
- this.errors = errors;
14
- }
15
- };
16
- function parseShopError(error) {
17
- if (error instanceof ShopError) {
18
- return error;
19
- }
20
- const errorCode = error?.code ?? error?.extensions?.code ?? error?.name ?? "";
21
- const errorMessage = typeof error === "string" ? error : error?.message ?? "";
22
- if (errorCode === "invalidMethodParameter" && errorMessage.includes("paymentMethod.create")) {
23
- return new ShopError({
24
- code: "paymentMethod.create.invalidMethodParameter",
25
- original: error
26
- }, "There was a problem validating your payment information. Please double-check the details and try again.");
27
- }
28
- if (errorMessage.includes("Invalid request: ")) {
29
- const finalError = errorMessage.split("Invalid request: ")[1].split("., ").map((e) => e.matchAll(/[A-Z_]+: (.*)/g))[0];
30
- const finalCode = finalError[1];
31
- const finalMessage = finalError[2];
32
- return new ShopError({
33
- code: `paymentMethod.${finalCode}`,
34
- original: error
35
- }, finalMessage);
36
- }
37
- if (errorCode === "insufficientFunds" || errorMessage.includes("There is not enough credit")) {
38
- return new ShopError({
39
- code: "shop.insufficientFunds",
40
- original: error
41
- }, "There is not enough money to complete the checkout. Please double-check the details and try again.");
42
- }
43
- if (errorCode === "shop.invalidBasketId" || errorCode === "shop.basketRequired" || errorCode === "shop.alreadyCheckedOut") {
44
- return new ShopError({
45
- code: errorCode,
46
- original: error
47
- }, "There was a problem with your basket. Please, refresh the page and try again.");
48
- }
49
- if (errorCode === "donationAmountTooLarge") {
50
- return new ShopError({
51
- code: errorCode,
52
- original: error
53
- }, errorMessage);
54
- }
55
- return new ShopError({
56
- code: "shop.unknown",
57
- original: error
58
- }, "An unknown error occurred.");
59
- }
60
-
61
- export {
62
- ShopError,
63
- parseShopError
64
- };
@@ -1,72 +0,0 @@
1
- import {
2
- callShopQuery
3
- } from "./chunk-IOZ5ERDX.js";
4
-
5
- // src/managedAccount.ts
6
- import { gql } from "@apollo/client/core/core.cjs";
7
- async function getPromoFromBasket(apollo, options) {
8
- if (!options?.variables?.promoFundId && !options?.variables?.basketId) {
9
- return Promise.resolve({ error: "promoFundId or basketId variable required" });
10
- }
11
- const data = await callShopQuery(apollo, {
12
- variables: { ...options?.variables },
13
- query: gql`
14
- query promoCampaign($basketId: String, $promoFundId: String) {
15
- shop (basketId: $basketId) {
16
- id
17
- promoCampaign (promoFundId: $promoFundId) {
18
- promoFund {
19
- id
20
- displayName
21
- displayDescription
22
- promoPrice
23
- }
24
- promoGroup {
25
- id
26
- type
27
- teamId
28
- }
29
- managedAccount {
30
- managementType
31
- audience
32
- allowDonations
33
- sendKivaNewsletter
34
- id
35
- isEmployee
36
- formId
37
- pageId
38
- loanSearchCriteria {
39
- filters {
40
- cityState
41
- country
42
- currencyLossPossible
43
- dafEligible
44
- distributionModel
45
- status
46
- excludeNonRated
47
- expiringSoon
48
- gender
49
- hasResearchScore
50
- isGroup
51
- lenderFavorite
52
- loanLimit
53
- isMatched
54
- sector
55
- loanTags
56
- theme
57
- }
58
- sortBy
59
- }
60
- }
61
- }
62
- }
63
- }
64
- `,
65
- fetchPolicy: options?.fetchPolicy ?? "network-only"
66
- }, 0);
67
- return data;
68
- }
69
-
70
- export {
71
- getPromoFromBasket
72
- };
@@ -1,49 +0,0 @@
1
- import {
2
- parseShopError
3
- } from "./chunk-4ODZGLWK.js";
4
- import {
5
- getCookieValue,
6
- setCookieValue
7
- } from "./chunk-LZ4UMRCV.js";
8
-
9
- // src/basket.ts
10
- import { gql } from "@apollo/client/core/core.cjs";
11
- function getBasketID() {
12
- return getCookieValue("kvbskt");
13
- }
14
- function setBasketID(basketId) {
15
- setCookieValue("kvbskt", basketId, "path=/;secure;");
16
- }
17
- async function createBasketHelper(apollo) {
18
- try {
19
- return apollo.mutate({
20
- mutation: gql`mutation createNewBasketForUser { shop { id createBasket } }`
21
- }).then(({ data }) => {
22
- const newBasketId = data.shop?.createBasket ?? null;
23
- if (newBasketId) {
24
- setBasketID(newBasketId);
25
- }
26
- });
27
- } catch (error) {
28
- throw parseShopError(error);
29
- }
30
- }
31
- var activeBasketCreationQuery = null;
32
- async function createBasket(apollo) {
33
- if (activeBasketCreationQuery) {
34
- return activeBasketCreationQuery;
35
- }
36
- activeBasketCreationQuery = createBasketHelper(apollo);
37
- return activeBasketCreationQuery;
38
- }
39
- function hasBasketExpired(error) {
40
- const errorCode = error?.code ?? error?.extensions?.code ?? error?.name ?? "";
41
- return ["shop.invalidBasketId", "shop.basketRequired", "shop.alreadyCheckedOut"].includes(errorCode);
42
- }
43
-
44
- export {
45
- getBasketID,
46
- setBasketID,
47
- createBasket,
48
- hasBasketExpired
49
- };
@@ -1,106 +0,0 @@
1
- import {
2
- ShopError,
3
- parseShopError
4
- } from "./chunk-4ODZGLWK.js";
5
-
6
- // src/subscriptionCheckout.ts
7
- import { gql } from "@apollo/client/core/core.cjs";
8
- async function checkSubscriptionStatus(apollo) {
9
- const { data: subsData } = await apollo.query({
10
- query: gql`query subscriptionStatus{
11
- my {
12
- id
13
- subscriptions {
14
- totalCount
15
- }
16
- autoDeposit {
17
- id
18
- isSubscriber
19
- }
20
- }
21
- }`
22
- });
23
- if (!subsData?.my?.id) {
24
- throw new ShopError({ code: "api.authenticationRequired" }, "You must be logged in to continue.");
25
- }
26
- if ((subsData?.my?.subscriptions?.totalCount ?? 0) > 0 || subsData?.my?.autoDeposit?.isSubscriber) {
27
- throw new ShopError({ code: "shop.subscriptionExists" }, "You already have an existing Monthly Good subscription. Changes can be made in your subscription settings.");
28
- }
29
- if (subsData?.my?.autoDeposit?.id) {
30
- throw new ShopError({ code: "shop.autoDepositExists" }, "You already have existing Auto Deposit settings. Changes can be made in your subscription settings.");
31
- }
32
- return true;
33
- }
34
- async function executeNewSubscriptionCheckout({
35
- amount,
36
- apollo,
37
- dayOfMonth = (/* @__PURE__ */ new Date()).getDate(),
38
- donateAmount,
39
- paymentMethod
40
- }) {
41
- const amountRegex = new RegExp(/^\d+\.\d{2}$/);
42
- if (!amountRegex.test(amount) || !amountRegex.test(donateAmount)) {
43
- throw new ShopError({
44
- code: "api.invalidMethodParameter"
45
- }, "Please check that the amount is correct and try again.");
46
- }
47
- await checkSubscriptionStatus(apollo);
48
- const { deviceData, nonce } = paymentMethod;
49
- let data;
50
- let error;
51
- try {
52
- const result = await apollo.mutate({
53
- variables: {
54
- nonce,
55
- deviceData,
56
- amount,
57
- donateAmount,
58
- dayOfMonth
59
- },
60
- mutation: gql`mutation createAutoDepositSubscription(
61
- $nonce: String!,
62
- $deviceData: String,
63
- $amount: Money!,
64
- $donateAmount: Money!,
65
- $dayOfMonth: Int!
66
- ) {
67
- my {
68
- createAutoDeposit (
69
- autoDeposit: {
70
- amount: $amount,
71
- donateAmount: $donateAmount,
72
- dayOfMonth: $dayOfMonth,
73
- },
74
- deviceData: $deviceData,
75
- paymentMethodNonce: $nonce
76
- ) {
77
- id amount donateAmount dayOfMonth status
78
- }
79
- }
80
- }`
81
- });
82
- if (result?.error || result?.errors?.length) {
83
- error = result?.error ?? result?.errors?.[0];
84
- } else {
85
- data = result?.data;
86
- }
87
- } catch (e) {
88
- error = e;
89
- }
90
- if (error) {
91
- const parsed = parseShopError(error);
92
- if (parsed?.code === "shop.unknown") {
93
- throw new ShopError({
94
- code: "shop.createAutoDepositError",
95
- original: parsed
96
- }, "There was a problem trying to setup your monthly deposit.");
97
- }
98
- throw parsed;
99
- }
100
- return data?.my?.createAutoDeposit;
101
- }
102
-
103
- export {
104
- checkSubscriptionStatus,
105
- executeNewSubscriptionCheckout
106
- };
@@ -1,17 +0,0 @@
1
- // src/basketVerification.ts
2
- var VerificationState = /* @__PURE__ */ ((VerificationState2) => {
3
- VerificationState2["VERIFIED"] = "verified";
4
- VerificationState2["PENDING"] = "pending";
5
- VerificationState2["REQUIRED"] = "required";
6
- VerificationState2["MAY_BE_NEEDED"] = "may_be_needed";
7
- VerificationState2["NOT_NEEDED"] = "not_needed";
8
- return VerificationState2;
9
- })(VerificationState || {});
10
- function isBasketVerified(state) {
11
- return state === "verified" /* VERIFIED */ || state === "not_needed" /* NOT_NEEDED */;
12
- }
13
-
14
- export {
15
- VerificationState,
16
- isBasketVerified
17
- };
@@ -1,196 +0,0 @@
1
- import {
2
- getCheckoutTrackingData
3
- } from "./chunk-RQNRQ2E5.js";
4
- import {
5
- validatePreCheckout
6
- } from "./chunk-KCUOMCSN.js";
7
- import {
8
- pollForFinishedCheckout,
9
- wait
10
- } from "./chunk-SRGYGDAX.js";
11
- import {
12
- getVisitorID
13
- } from "./chunk-TPJPGUO7.js";
14
- import {
15
- callShopMutation,
16
- callShopQuery
17
- } from "./chunk-IOZ5ERDX.js";
18
- import {
19
- ShopError,
20
- parseShopError
21
- } from "./chunk-4ODZGLWK.js";
22
-
23
- // src/oneTimeCheckout.ts
24
- import { gql } from "@apollo/client/core/core.cjs";
25
- import { trackTransaction } from "@kiva/kv-analytics";
26
- import numeral from "numeral";
27
-
28
- // src/util/redirect.ts
29
- function redirectTo(href) {
30
- return new Promise(() => {
31
- window.location.href = href;
32
- });
33
- }
34
-
35
- // src/oneTimeCheckout.ts
36
- async function creditAmountNeeded(apollo) {
37
- const data = await callShopQuery(apollo, {
38
- query: gql`
39
- query creditAmountNeeded($basketId: String) {
40
- shop (basketId: $basketId) {
41
- id
42
- basket {
43
- id
44
- totals {
45
- creditAmountNeeded
46
- }
47
- }
48
- }
49
- }
50
- `,
51
- fetchPolicy: "network-only"
52
- }, 0);
53
- return data?.shop?.basket?.totals?.creditAmountNeeded;
54
- }
55
- var creditCheckoutMutation = gql`
56
- mutation creditCheckout(
57
- $basketId: String,
58
- $visitorId: String
59
- ) {
60
- shop (basketId: $basketId) {
61
- id
62
- transactionId: checkoutAsync (visitorId: $visitorId)
63
- }
64
- }
65
- `;
66
- var depositCheckoutMutation = gql`
67
- mutation depositCheckout(
68
- $basketId: String,
69
- $amount: Money!,
70
- $nonce: String!,
71
- $savePaymentMethod: Boolean,
72
- $deviceData: String,
73
- $visitorId: String
74
- ) {
75
- shop (basketId: $basketId) {
76
- id
77
- transactionId: doNoncePaymentDepositAndCheckoutAsync(
78
- amount: $amount,
79
- nonce: $nonce,
80
- savePaymentMethod: $savePaymentMethod,
81
- deviceData: $deviceData,
82
- visitorId: $visitorId
83
- )
84
- }
85
- }
86
- `;
87
- function creditCheckout(apollo) {
88
- return callShopMutation(apollo, {
89
- mutation: creditCheckoutMutation,
90
- variables: {
91
- visitorId: getVisitorID()
92
- }
93
- }, 0);
94
- }
95
- async function depositCheckout({
96
- apollo,
97
- braintree,
98
- amount
99
- }) {
100
- try {
101
- const paymentMethod = await braintree.requestPaymentMethod();
102
- if (!paymentMethod) {
103
- throw new ShopError(
104
- { code: "shop.dropinNoPaymentMethod" },
105
- "No payment method returned from braintree dropin"
106
- );
107
- }
108
- const { nonce, deviceData, type } = paymentMethod;
109
- return {
110
- paymentType: type,
111
- mutation: callShopMutation(apollo, {
112
- mutation: depositCheckoutMutation,
113
- variables: {
114
- nonce,
115
- amount,
116
- savePaymentMethod: false,
117
- // save payment methods handled by braintree drop in UI
118
- deviceData,
119
- visitorId: getVisitorID()
120
- }
121
- }, 0)
122
- };
123
- } catch (e) {
124
- throw parseShopError(e);
125
- }
126
- }
127
- async function trackSuccess(apollo, checkoutId, paymentType) {
128
- try {
129
- const transactionData = await getCheckoutTrackingData(
130
- apollo,
131
- checkoutId,
132
- paymentType
133
- );
134
- trackTransaction(transactionData);
135
- await wait(800);
136
- } catch (e) {
137
- console.error("Error tracking transaction", e);
138
- }
139
- }
140
- async function executeOneTimeCheckout({
141
- apollo,
142
- braintree,
143
- emailAddress,
144
- emailOptIn,
145
- valetInviter,
146
- deactivateRedirect
147
- }) {
148
- await validatePreCheckout({
149
- apollo,
150
- emailAddress,
151
- emailOptIn,
152
- valetInviter
153
- });
154
- const creditNeeded = await creditAmountNeeded(apollo);
155
- const creditRequired = numeral(creditNeeded).value() > 0;
156
- if (creditRequired && !braintree) {
157
- throw new ShopError({ code: "shop.dropinRequired" }, "Braintree dropin required for credit deposit checkout");
158
- }
159
- let data;
160
- let paymentType = "";
161
- if (creditRequired) {
162
- const checkoutResult = await depositCheckout({
163
- apollo,
164
- braintree,
165
- amount: creditNeeded
166
- });
167
- paymentType = checkoutResult.paymentType;
168
- data = await checkoutResult.mutation;
169
- } else {
170
- data = await creditCheckout(apollo);
171
- }
172
- const transactionId = data?.shop?.transactionId;
173
- const result = await pollForFinishedCheckout({
174
- apollo,
175
- transactionSagaId: transactionId,
176
- timeout: 3e5
177
- // five minutes
178
- });
179
- if (result.errors?.length) {
180
- throw parseShopError(result.errors[0]);
181
- }
182
- const checkoutId = result.data?.checkoutStatus?.receipt?.checkoutId;
183
- await trackSuccess(apollo, checkoutId, paymentType);
184
- if (deactivateRedirect) {
185
- return result;
186
- }
187
- let redirectUrl = `/checkout/post-purchase?kiva_transaction_id=${checkoutId}`;
188
- if (valetInviter?.inviterId) {
189
- redirectUrl += `&valet_inviter=${valetInviter.inviterId}`;
190
- }
191
- await redirectTo(redirectUrl);
192
- }
193
-
194
- export {
195
- executeOneTimeCheckout
196
- };
@@ -1,45 +0,0 @@
1
- import {
2
- watchShopQuery
3
- } from "./chunk-IOZ5ERDX.js";
4
-
5
- // src/basketTotals.ts
6
- import { gql } from "@apollo/client/core/core.cjs";
7
- var basketTotalsQuery = gql`query basketTotals($basketId: String) {
8
- shop (basketId: $basketId) {
9
- id
10
- basket {
11
- id
12
- totals {
13
- bonusAppliedTotal
14
- bonusAvailableTotal
15
- creditAmountNeeded
16
- creditAppliedTotal
17
- creditAvailableTotal
18
- donationTotal
19
- itemTotal
20
- freeTrialAppliedTotal
21
- freeTrialAvailableTotal
22
- loanReservationTotal
23
- kivaCardTotal
24
- kivaCreditAppliedTotal
25
- kivaCreditAvailableTotal
26
- kivaCreditRemaining
27
- kivaCreditToReapply
28
- redemptionCodeAppliedTotal
29
- redemptionCodeAvailableTotal
30
- universalCodeAppliedTotal
31
- universalCodeAvailableTotal
32
- }
33
- }
34
- }
35
- }`;
36
- function watchBasketTotals(apollo) {
37
- return watchShopQuery(apollo, {
38
- query: basketTotalsQuery
39
- });
40
- }
41
-
42
- export {
43
- basketTotalsQuery,
44
- watchBasketTotals
45
- };
@@ -1,121 +0,0 @@
1
- import {
2
- createBasket,
3
- getBasketID,
4
- hasBasketExpired
5
- } from "./chunk-FBF4WMN6.js";
6
- import {
7
- parseShopError
8
- } from "./chunk-4ODZGLWK.js";
9
-
10
- // src/shopQueries.ts
11
- var watchQueries = /* @__PURE__ */ new Set();
12
- async function callShopMutation(apollo, options, maxretries = 2) {
13
- try {
14
- const result = await apollo.mutate({
15
- ...options,
16
- variables: {
17
- ...options.variables,
18
- basketId: getBasketID()
19
- },
20
- refetchQueries: options.awaitRefetchQueries ? Array.from(watchQueries) : []
21
- });
22
- if (result?.errors?.length) {
23
- const basketErrors = result?.errors.filter((err) => hasBasketExpired(err));
24
- if (basketErrors.length) {
25
- if (maxretries > 0) {
26
- await createBasket(apollo);
27
- return callShopMutation(apollo, options, maxretries - 1);
28
- }
29
- throw basketErrors[0];
30
- }
31
- if (result?.errors?.length) {
32
- throw result.errors[0];
33
- }
34
- }
35
- return result?.data;
36
- } catch (e) {
37
- throw parseShopError(e);
38
- }
39
- }
40
- async function callShopQuery(apollo, options, maxretries = 2) {
41
- try {
42
- const result = await apollo.query({
43
- ...options,
44
- variables: {
45
- ...options.variables,
46
- basketId: getBasketID()
47
- }
48
- });
49
- if (result?.errors?.length) {
50
- const basketErrors = result?.errors.filter((err) => hasBasketExpired(err));
51
- if (basketErrors.length) {
52
- if (maxretries > 0) {
53
- await createBasket(apollo);
54
- return callShopQuery(apollo, options, maxretries - 1);
55
- }
56
- throw basketErrors[0];
57
- }
58
- if (result?.errors?.length) {
59
- throw result.errors[0];
60
- }
61
- }
62
- return result?.data;
63
- } catch (e) {
64
- throw parseShopError(e);
65
- }
66
- }
67
- function watchShopQuery(apollo, options, maxretries = 2) {
68
- let retries = 0;
69
- watchQueries.add(options.query);
70
- const observable = apollo.watchQuery({
71
- ...options,
72
- variables: {
73
- ...options.variables,
74
- basketId: getBasketID()
75
- }
76
- });
77
- const oldSubscribe = observable.subscribe.bind(observable);
78
- observable.subscribe = (...args) => {
79
- let nextFn;
80
- let errorFn;
81
- let completeFn;
82
- if (typeof args[0] === "function") {
83
- [nextFn, errorFn, completeFn] = args;
84
- } else {
85
- nextFn = args[0]?.next;
86
- errorFn = args[0]?.error;
87
- completeFn = args[0]?.complete;
88
- }
89
- const newErrorFn = (err) => {
90
- const basketErrors = err?.graphQLErrors?.filter((e) => hasBasketExpired(e));
91
- if (basketErrors.length) {
92
- if (retries < maxretries) {
93
- createBasket(apollo).then(() => {
94
- retries += 1;
95
- observable.refetch({
96
- ...observable.variables,
97
- basketId: getBasketID()
98
- });
99
- });
100
- } else {
101
- errorFn(parseShopError(basketErrors[0]));
102
- }
103
- } else {
104
- if (err?.graphQLErrors?.length) {
105
- errorFn(parseShopError(err.graphQLErrors[0]));
106
- }
107
- if (err?.networkError) {
108
- errorFn(parseShopError(err.networkError));
109
- }
110
- }
111
- };
112
- return oldSubscribe(nextFn, newErrorFn, completeFn);
113
- };
114
- return observable;
115
- }
116
-
117
- export {
118
- callShopMutation,
119
- callShopQuery,
120
- watchShopQuery
121
- };