@searchspring/snap-platforms 0.56.4 → 0.56.6

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.
@@ -3,6 +3,6 @@ type BigCommerceAddToCartConfig = {
3
3
  redirect?: boolean | string;
4
4
  idFieldName?: string;
5
5
  };
6
- export declare const addToCart: (items: Product[], config?: BigCommerceAddToCartConfig) => Promise<void>;
6
+ export declare const addToCart: (items: Product[], config?: BigCommerceAddToCartConfig) => Promise<any>;
7
7
  export {};
8
8
  //# sourceMappingURL=addToCart.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"addToCart.d.ts","sourceRoot":"","sources":["../../../../bigcommerce/src/addToCart.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAE7D,KAAK,0BAA0B,GAAG;IACjC,QAAQ,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAWF,eAAO,MAAM,SAAS,UAAiB,OAAO,EAAE,WAAW,0BAA0B,kBAkDpF,CAAC"}
1
+ {"version":3,"file":"addToCart.d.ts","sourceRoot":"","sources":["../../../../bigcommerce/src/addToCart.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAE7D,KAAK,0BAA0B,GAAG;IACjC,QAAQ,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAQF,eAAO,MAAM,SAAS,UAAiB,OAAO,EAAE,WAAW,0BAA0B,iBA+DpF,CAAC"}
@@ -1,15 +1,4 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -49,7 +38,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
49
38
  Object.defineProperty(exports, "__esModule", { value: true });
50
39
  exports.addToCart = void 0;
51
40
  var addToCart = function (items, config) { return __awaiter(void 0, void 0, void 0, function () {
52
- var formData, i;
41
+ var lineItems, addToCartResponse;
53
42
  return __generator(this, function (_a) {
54
43
  switch (_a.label) {
55
44
  case 0:
@@ -57,21 +46,21 @@ var addToCart = function (items, config) { return __awaiter(void 0, void 0, void
57
46
  console.error('Error: no products to add');
58
47
  return [2 /*return*/];
59
48
  }
60
- formData = {
61
- line_items: [],
62
- };
49
+ lineItems = [];
63
50
  items.map(function (item) {
64
- var _a, _b, _c;
51
+ var _a, _b, _c, _d, _e;
65
52
  var id = (_c = (_b = (_a = item === null || item === void 0 ? void 0 : item.display) === null || _a === void 0 ? void 0 : _a.mappings) === null || _b === void 0 ? void 0 : _b.core) === null || _c === void 0 ? void 0 : _c.uid;
66
53
  // try to find custom field in data
67
54
  if (config === null || config === void 0 ? void 0 : config.idFieldName) {
68
55
  var level_1 = item;
69
56
  config.idFieldName.split('.').map(function (field) {
70
- if (level_1[field]) {
57
+ if (level_1 && level_1[field]) {
71
58
  level_1 = level_1[field];
72
59
  }
73
60
  else {
74
- console.error('Error: couldnt find column in item data. please check your idFieldName is correct in the config.');
61
+ console.error("Error: couldnt find column in item data. please verify 'idFieldName' in the config.");
62
+ level_1 = undefined;
63
+ id = undefined;
75
64
  return;
76
65
  }
77
66
  });
@@ -80,77 +69,112 @@ var addToCart = function (items, config) { return __awaiter(void 0, void 0, void
80
69
  }
81
70
  }
82
71
  if (id && item.quantity) {
83
- var obj = {
72
+ var productDetails_1 = {
84
73
  product_id: id,
85
74
  quantity: item.quantity,
86
75
  };
87
- formData.line_items.push(obj);
76
+ var options_1 = (_e = (_d = item.variants) === null || _d === void 0 ? void 0 : _d.active) === null || _e === void 0 ? void 0 : _e.options;
77
+ if (options_1) {
78
+ productDetails_1.optionSelections = [];
79
+ Object.keys(options_1).forEach(function (option) {
80
+ var _a;
81
+ var optionId = options_1[option].optionId;
82
+ var optionValue = options_1[option].optionValue;
83
+ if (optionId && optionValue) {
84
+ (_a = productDetails_1.optionSelections) === null || _a === void 0 ? void 0 : _a.push({ optionId: optionId, optionValue: optionValue });
85
+ }
86
+ });
87
+ }
88
+ lineItems.push(productDetails_1);
88
89
  }
89
90
  });
90
- if (!formData.line_items.length) return [3 /*break*/, 4];
91
- i = 0;
92
- _a.label = 1;
91
+ if (!lineItems.length) return [3 /*break*/, 2];
92
+ return [4 /*yield*/, addLineItemsToCart(lineItems)];
93
93
  case 1:
94
- if (!(i < formData.line_items.length)) return [3 /*break*/, 4];
95
- return [4 /*yield*/, addSingleProductv1(formData.line_items[i])];
96
- case 2:
97
- _a.sent();
98
- _a.label = 3;
99
- case 3:
100
- i++;
101
- return [3 /*break*/, 1];
102
- case 4:
94
+ addToCartResponse = _a.sent();
103
95
  // do redirect (or not)
104
96
  if ((config === null || config === void 0 ? void 0 : config.redirect) !== false) {
105
97
  setTimeout(function () { return (window.location.href = typeof (config === null || config === void 0 ? void 0 : config.redirect) == 'string' ? config === null || config === void 0 ? void 0 : config.redirect : '/cart.php'); });
106
98
  }
107
- return [2 /*return*/];
99
+ return [2 /*return*/, addToCartResponse];
100
+ case 2: return [2 /*return*/];
108
101
  }
109
102
  });
110
103
  }); };
111
104
  exports.addToCart = addToCart;
112
- var addSingleProductv1 = function (item) { return __awaiter(void 0, void 0, void 0, function () {
113
- var endpoint, payload, init, response, err_1;
114
- return __generator(this, function (_a) {
115
- switch (_a.label) {
116
- case 0:
117
- if (!item) {
118
- console.error('Error: no product to add');
119
- return [2 /*return*/];
120
- }
121
- endpoint = {
122
- route: "/remote/v1/cart/add",
123
- method: 'POST',
124
- accept: 'application/json',
125
- content: 'application/json',
126
- success: 200,
127
- };
128
- _a.label = 1;
129
- case 1:
130
- _a.trys.push([1, 3, , 4]);
131
- payload = JSON.stringify(__assign(__assign({}, item), { action: 'add' }));
132
- init = {
133
- method: endpoint.method,
134
- credentials: 'same-origin',
135
- headers: {
136
- // note: no authorization
137
- Accept: endpoint.accept,
138
- 'Content-Type': endpoint.content,
139
- },
140
- body: payload,
141
- };
142
- return [4 /*yield*/, fetch(endpoint.route, init)];
143
- case 2:
144
- response = _a.sent();
145
- if (response.status !== endpoint.success) {
146
- throw new Error("Error: addToCart responded with ".concat(response.status, ", ").concat(response));
147
- }
148
- return [3 /*break*/, 4];
149
- case 3:
150
- err_1 = _a.sent();
151
- console.error(err_1);
152
- return [3 /*break*/, 4];
153
- case 4: return [2 /*return*/];
154
- }
105
+ function addLineItemsToCart(lineItems) {
106
+ return __awaiter(this, void 0, void 0, function () {
107
+ var cartId, addToCartUrl, body, response, responseData, err_1;
108
+ return __generator(this, function (_a) {
109
+ switch (_a.label) {
110
+ case 0:
111
+ _a.trys.push([0, 4, , 5]);
112
+ return [4 /*yield*/, getExistingCartId()];
113
+ case 1:
114
+ cartId = _a.sent();
115
+ addToCartUrl = '/api/storefront/carts';
116
+ if (cartId) {
117
+ addToCartUrl = "/api/storefront/carts/".concat(cartId, "/items");
118
+ }
119
+ body = JSON.stringify({ lineItems: lineItems });
120
+ return [4 /*yield*/, fetch(addToCartUrl, {
121
+ method: 'POST',
122
+ headers: {
123
+ Accept: 'application/json',
124
+ 'Content-Type': 'application/json',
125
+ },
126
+ body: body,
127
+ })];
128
+ case 2:
129
+ response = _a.sent();
130
+ if (response.status !== 200) {
131
+ throw new Error("API rejected addToCart: ".concat(response.status));
132
+ }
133
+ return [4 /*yield*/, response.json()];
134
+ case 3:
135
+ responseData = _a.sent();
136
+ if (responseData === null || responseData === void 0 ? void 0 : responseData.id) {
137
+ // cart Id should exist now.
138
+ return [2 /*return*/, responseData];
139
+ }
140
+ return [3 /*break*/, 5];
141
+ case 4:
142
+ err_1 = _a.sent();
143
+ console.error("Error: could not add to cart.", err_1);
144
+ return [3 /*break*/, 5];
145
+ case 5: return [2 /*return*/];
146
+ }
147
+ });
155
148
  });
156
- }); };
149
+ }
150
+ function getExistingCartId() {
151
+ return __awaiter(this, void 0, void 0, function () {
152
+ var response, responseData, err_2;
153
+ return __generator(this, function (_a) {
154
+ switch (_a.label) {
155
+ case 0:
156
+ _a.trys.push([0, 3, , 4]);
157
+ return [4 /*yield*/, fetch('/api/storefront/carts', {
158
+ method: 'GET',
159
+ headers: {
160
+ Accept: 'application/json',
161
+ 'Content-Type': 'application/json',
162
+ },
163
+ })];
164
+ case 1:
165
+ response = _a.sent();
166
+ return [4 /*yield*/, response.json()];
167
+ case 2:
168
+ responseData = _a.sent();
169
+ if (Array.isArray(responseData) && responseData.length) {
170
+ return [2 /*return*/, responseData[0].id];
171
+ }
172
+ return [3 /*break*/, 4];
173
+ case 3:
174
+ err_2 = _a.sent();
175
+ return [3 /*break*/, 4];
176
+ case 4: return [2 /*return*/];
177
+ }
178
+ });
179
+ });
180
+ }
@@ -3,6 +3,6 @@ type BigCommerceAddToCartConfig = {
3
3
  redirect?: boolean | string;
4
4
  idFieldName?: string;
5
5
  };
6
- export declare const addToCart: (items: Product[], config?: BigCommerceAddToCartConfig) => Promise<void>;
6
+ export declare const addToCart: (items: Product[], config?: BigCommerceAddToCartConfig) => Promise<any>;
7
7
  export {};
8
8
  //# sourceMappingURL=addToCart.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"addToCart.d.ts","sourceRoot":"","sources":["../../../../bigcommerce/src/addToCart.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAE7D,KAAK,0BAA0B,GAAG;IACjC,QAAQ,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAWF,eAAO,MAAM,SAAS,UAAiB,OAAO,EAAE,WAAW,0BAA0B,kBAkDpF,CAAC"}
1
+ {"version":3,"file":"addToCart.d.ts","sourceRoot":"","sources":["../../../../bigcommerce/src/addToCart.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAE7D,KAAK,0BAA0B,GAAG;IACjC,QAAQ,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAQF,eAAO,MAAM,SAAS,UAAiB,OAAO,EAAE,WAAW,0BAA0B,iBA+DpF,CAAC"}
@@ -3,20 +3,20 @@ export const addToCart = async (items, config) => {
3
3
  console.error('Error: no products to add');
4
4
  return;
5
5
  }
6
- const formData = {
7
- line_items: [],
8
- };
6
+ const lineItems = [];
9
7
  items.map((item) => {
10
8
  let id = item?.display?.mappings?.core?.uid;
11
9
  // try to find custom field in data
12
10
  if (config?.idFieldName) {
13
11
  let level = item;
14
12
  config.idFieldName.split('.').map((field) => {
15
- if (level[field]) {
13
+ if (level && level[field]) {
16
14
  level = level[field];
17
15
  }
18
16
  else {
19
- console.error('Error: couldnt find column in item data. please check your idFieldName is correct in the config.');
17
+ console.error(`Error: couldnt find column in item data. please verify 'idFieldName' in the config.`);
18
+ level = undefined;
19
+ id = undefined;
20
20
  return;
21
21
  }
22
22
  });
@@ -25,57 +25,78 @@ export const addToCart = async (items, config) => {
25
25
  }
26
26
  }
27
27
  if (id && item.quantity) {
28
- const obj = {
28
+ const productDetails = {
29
29
  product_id: id,
30
30
  quantity: item.quantity,
31
31
  };
32
- formData.line_items.push(obj);
32
+ const options = item.variants?.active?.options;
33
+ if (options) {
34
+ productDetails.optionSelections = [];
35
+ Object.keys(options).forEach((option) => {
36
+ const optionId = options[option].optionId;
37
+ const optionValue = options[option].optionValue;
38
+ if (optionId && optionValue) {
39
+ productDetails.optionSelections?.push({ optionId, optionValue });
40
+ }
41
+ });
42
+ }
43
+ lineItems.push(productDetails);
33
44
  }
34
45
  });
35
- // first check how many products we are adding
36
- if (formData.line_items.length) {
37
- for (let i = 0; i < formData.line_items.length; i++) {
38
- await addSingleProductv1(formData.line_items[i]);
46
+ if (lineItems.length) {
47
+ const addToCartResponse = await addLineItemsToCart(lineItems);
48
+ // do redirect (or not)
49
+ if (config?.redirect !== false) {
50
+ setTimeout(() => (window.location.href = typeof config?.redirect == 'string' ? config?.redirect : '/cart.php'));
39
51
  }
40
- }
41
- // do redirect (or not)
42
- if (config?.redirect !== false) {
43
- setTimeout(() => (window.location.href = typeof config?.redirect == 'string' ? config?.redirect : '/cart.php'));
52
+ return addToCartResponse;
44
53
  }
45
54
  };
46
- const addSingleProductv1 = async (item) => {
47
- if (!item) {
48
- console.error('Error: no product to add');
49
- return;
50
- }
51
- const endpoint = {
52
- route: `/remote/v1/cart/add`,
53
- method: 'POST',
54
- accept: 'application/json',
55
- content: 'application/json',
56
- success: 200,
57
- };
55
+ async function addLineItemsToCart(lineItems) {
58
56
  try {
59
- const payload = JSON.stringify({
60
- ...item,
61
- action: 'add',
57
+ const cartId = await getExistingCartId();
58
+ // if existing cartId use it, otherwise create new cart with items
59
+ let addToCartUrl = '/api/storefront/carts';
60
+ if (cartId) {
61
+ addToCartUrl = `/api/storefront/carts/${cartId}/items`;
62
+ }
63
+ const body = JSON.stringify({ lineItems });
64
+ const response = await fetch(addToCartUrl, {
65
+ method: 'POST',
66
+ headers: {
67
+ Accept: 'application/json',
68
+ 'Content-Type': 'application/json',
69
+ },
70
+ body,
62
71
  });
63
- const init = {
64
- method: endpoint.method,
65
- credentials: 'same-origin',
72
+ if (response.status !== 200) {
73
+ throw new Error(`API rejected addToCart: ${response.status}`);
74
+ }
75
+ const responseData = await response.json();
76
+ if (responseData?.id) {
77
+ // cart Id should exist now.
78
+ return responseData;
79
+ }
80
+ }
81
+ catch (err) {
82
+ console.error(`Error: could not add to cart.`, err);
83
+ }
84
+ }
85
+ async function getExistingCartId() {
86
+ try {
87
+ const response = await fetch('/api/storefront/carts', {
88
+ method: 'GET',
66
89
  headers: {
67
- // note: no authorization
68
- Accept: endpoint.accept,
69
- 'Content-Type': endpoint.content,
90
+ Accept: 'application/json',
91
+ 'Content-Type': 'application/json',
70
92
  },
71
- body: payload,
72
- };
73
- const response = await fetch(endpoint.route, init);
74
- if (response.status !== endpoint.success) {
75
- throw new Error(`Error: addToCart responded with ${response.status}, ${response}`);
93
+ });
94
+ const responseData = await response.json();
95
+ if (Array.isArray(responseData) && responseData.length) {
96
+ return responseData[0].id;
76
97
  }
77
98
  }
78
99
  catch (err) {
79
- console.error(err);
100
+ // error...
80
101
  }
81
- };
102
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@searchspring/snap-platforms",
3
- "version": "0.56.4",
3
+ "version": "0.56.6",
4
4
  "description": "Snap Platforms Library",
5
5
  "author": "Searchspring",
6
6
  "license": "MIT",
@@ -18,10 +18,10 @@
18
18
  "test:watch": "jest --watch"
19
19
  },
20
20
  "dependencies": {
21
- "@searchspring/snap-toolbox": "^0.56.4"
21
+ "@searchspring/snap-toolbox": "^0.56.6"
22
22
  },
23
23
  "devDependencies": {
24
- "@searchspring/snap-store-mobx": "^0.56.4"
24
+ "@searchspring/snap-store-mobx": "^0.56.6"
25
25
  },
26
26
  "sideEffects": false,
27
27
  "files": [
@@ -44,5 +44,5 @@
44
44
  "require": "./dist/cjs/bigcommerce/src/index.js"
45
45
  }
46
46
  },
47
- "gitHead": "7321bec220286736c9fae5c2810cb26452894a04"
47
+ "gitHead": "6ce15ae24b23acedd8f5970e3d34a0bfa977c11e"
48
48
  }