-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathcart.js
305 lines (279 loc) · 7.82 KB
/
cart.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
const FoxySDK = require("@foxy.io/sdk");
const dotenv = require("dotenv");
const bodyParser = require("body-parser");
const { config } = require("../../../config.js");
const cors = require("cors");
const createError = require("http-errors");
const express = require("express");
const serverless = require("serverless-http");
const app = express();
dotenv.config();
const messageCartNotFound = 'Cart not found.';
app.use(cors({
origin: 'http://127.0.0.1:8080',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}));
/**
* Validate configuration requirements
*
* @returns {boolean} the configuration is valid
*/
function validateConfig() {
return !!(config.foxy.api.clientId &&
config.foxy.api.clientSecret &&
config.foxy.api.refreshToken)
;
}
/**
* Validate the cart has the proper attributes.
*
* @param {Object} cart to be validated.
* @returns {boolean} the cart attributes are valid.
*/
function validateCart(cart) {
return cart &&
cart._embedded &&
Array.isArray(cart._embedded["fx:items"]);
}
/**
* Initialize Foxy API
*
* @param {Object} app to be assigned a Foxy Backend API.
* @returns {Object} foxy api instance
*/
function setFoxyAPI(app) {
if (!app.foxy) {
if (validateConfig()) {
app.foxy = new FoxySDK.Backend.API(
{
clientId: config.foxy.api.clientId,
clientSecret: config.foxy.api.clientSecret,
refreshToken: config.foxy.api.refreshToken,
}
);
}
}
return app.foxy;
}
/** Functions and Variables */
/** Default values */
const defaultSubFrequency = config.default.autoshipFrequency || "1m";
/**
* @typedef {import(@foxy/sdk).Backend.API} API
*/
/**
* Retrieves a `cart` resource by ID.
*
* @param {Object} foxy API instance to use.
* @param {number} id - The ID of the cart to retrieve.
* @returns {Object} first cart.
*/
const getCart = async (foxy, id) => {
if (!id && !Number.isInteger(id)) {
return {};
}
const store = await foxy.follow('fx:store');
const cartsFollow = await store.follow("fx:carts");
const carts = await cartsFollow
.get({
filters: [`id=${id}`],
zoom: [
"items",
"items:item_options",
"items:item_options:discount_details",
],
});
return (
await carts.json()
)._embedded["fx:carts"][0] || {};
};
/**
* Updates the cart and its contents
*
* @param {Object} cart with modifications to be.
* @returns {Promise} that resolves to the api response.
*/
const patchCart = async (cart) => {
const selfCart = cart._links.self;
const cartData = {...cart};
delete cartData._links;
return selfCart.patch(cartData);
};
/**
* Strips all `sub_` parameters from all cart items.
*
* @param {number} id
* @param {Object} cart
*/
const convertCartToOneOff = async (id, cart) => {
// Remove any non-subscription products, as we don't need to modify them.
const cartOriginal = JSON.parse(JSON.stringify(cart));
cart._embedded["fx:items"] = cart._embedded["fx:items"].filter(
(item) => item.subscription_frequency
);
for (const item of cart._embedded["fx:items"]) {
item.subscription_frequency = "";
delete item.subscription_start_date;
delete item.subscription_end_date;
delete item.subscription_next_transaction_date;
}
if (cart._embedded["fx:items"].length > 0) {
return (await patchCart(cart)).json();
} else {
return cartOriginal;
}
};
/**
* Converts a cart into a subscription
*
* @param {number} id
* @param {Object} cart
* @param {string} frequency
* @param {string[]} allowList
* @param {string[]} ignoreList
*/
const convertCartToSubscription = async (
id,
cart,
frequency = defaultSubFrequency,
allowList,
ignoreList
) => {
// Remove any existing subscription items in the cart, as we don't need to modify them
const cartOriginal = JSON.parse(JSON.stringify(cart));
cart._embedded["fx:items"] = cart._embedded["fx:items"]
.filter(item => !item.subscription_frequency)
.map(item => {
item.subscription_frequency = frequency;
delete item.subscription_start_date;
delete item.subscription_end_date;
delete item.subscription_next_transaction_date;
return item
});
if (cart._embedded["fx:items"].length > 0) {
const patchResponse = await patchCart(cart);
const patchResult = await patchResponse.json();
return patchResult;
} else {
return cartOriginal;
}
};
/** Express Routing */
const cartRouter = express.Router();
cartRouter.get("/", (req, res) => {
res.status(400).json({ error: "true", message: "Invalid request." });
});
// TODO: Make it POST
cartRouter.get(
"/:cartId(\\d+)/convert/recurring/:frequency",
async (req, res) => {
let err;
if (!validateConfig()) {
res.status(500).json("FOXY_API_CLIENT_ID is not configured;");
} else {
setFoxyAPI(app);
if (app.foxy) {
try {
const cart = await getCart(app.foxy, req.params.cartId);
if (!validateCart(cart)) {
throw createError(404, messageCartNotFound);
}
const subsCart = await convertCartToSubscription(
req.params.cartId,
cart,
req.params.frequency
);
res.json(subsCart);
return;
} catch(e) {
err = e;
if (err.message === 'Error getting cart.') {
err.status = 404;
err.message = "Cart not found.";
}
console.log("Error: ", err.code, err.message);
}
} else {
err.status = 500;
err.message = "Could not instantiate Foxy SDK";
}
if (err.status) {
res.status(err.status).json(err.message);
} else {
res.status(500).json("Error fetching or modifying cart.");
}
}
}
);
// TODO: Make it POST
cartRouter.get(
"/:cartId(\\d+)/convert/nonrecurring",
async (req, res) => {
if (!validateConfig()) {
res.status(500).json("FOXY_API_CLIENT_ID is not configured.");
} else {
setFoxyAPI(app);
try {
const cart = await getCart(app.foxy, req.params.cartId);
if (!validateCart(cart)) {
throw createError(404, messageCartNotFound);
}
const data = await convertCartToOneOff(req.params.cartId, cart);
res.json(data);
} catch(err) {
if (err.status) {
res.status(err.status).json(err.message);
} else {
res.status(500).json("Error fetching or modifying cart.");
}
}
}
}
);
app.use(bodyParser.json());
// Override the `res.json` to tweak and sanitize the data a bit.
// TODO: Enable this once the FoxyAPI.sanitize.removePrivateAttributes method is fixed.
// app.use((req, res, next) => {
// const { json } = res;
// res.json = function modifyPortalResponseJson(obj) {
// console.log("MODIFY RESPONSE?");
// console.log(JSON.stringify(obj));
// const transformedResponse = traverse(obj).map(
// FoxyApi.sanitize.all(
// FoxyApi.sanitize.removePrivateAttributes,
// FoxyApi.sanitize.removeProperties("third_party_id")
// )
// );
// json.call(this, transformedResponse);
// };
// next();
// });
app.use("/.netlify/functions/cart", cartRouter); // path must route to lambda
//// CORS error
//app.use((err, req, res, next) => {
// if (err.message && err.message === "CORS_ERROR") {
// res.status(401).json({
// type: "cors",
// code: "401",
// message: "Invalid origin header.",
// });
// } else {
// next();
// }
//});
// Unknown Error Handler
// Without the `next` this barfs the whole stack trace, and says res.status isn't defined?
// Probably need to improve this.
app.use((err, req, res, next) => {
console.error("Final error:", err);
res.status(502).json({
type: "unknown",
code: "0",
message: "Unknown error.",
});
});
const handler = serverless(app);
module.exports = {
app,
handler,
}