-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
addToCart.js
48 lines (42 loc) · 1.63 KB
/
addToCart.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
'use strict';
const { Cart, Product } = require('../../models');
const connect = require('../../connect');
const handler = async(event) => {
try {
event.body = JSON.parse(event.body || {});
await connect();
const products = await Product.find();
if (event.body.cartId) {
// get the document containing the specified cartId
const cart = await Cart.findOne({ _id: event.body.cartId }).setOptions({ sanitizeFilter: true });
if (cart == null) {
return { statusCode: 404, body: JSON.stringify({ message: 'Cart not found' }) };
}
if(!Array.isArray(event.body.items)) {
return { statusCode: 500, body: JSON.stringify({ error: 'items is not an array' }) };
}
for (const product of event.body.items) {
const exists = cart.items.find(item => item?.productId?.toString() === product?.productId?.toString());
if (!exists && products.find(p => product?.productId?.toString() === p?._id?.toString())) {
cart.items.push(product);
await cart.save();
} else {
exists.quantity += product.quantity;
await cart.save();
}
}
if (!cart.items.length) {
return { statusCode: 200, body: JSON.stringify({ cart: null }) };
}
await cart.save();
return { statusCode: 200, body: JSON.stringify(cart) };
} else {
// If no cartId, create a new cart
const cart = await Cart.create({ items: event.body.items });
return { statusCode: 200, body: JSON.stringify(cart) };
}
} catch (error) {
return { statusCode: 500, body: error.toString() };
}
};
module.exports = { handler };