-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
addToCart.js
32 lines (29 loc) · 928 Bytes
/
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
'use strict';
const { Cart } = require('../models');
const handler = async(event) => {
try {
if (event.body.cartId) {
// get the document containing the specified cartId
const cart = await Cart.findOne({ _id: event.body.cartId });
for (const product of event.body.product) {
const exists = cart.items.find(item =>
item.productId.toString() === product.productId.toString()
);
if (!exists) {
cart.items.push(product);
} else {
exists.quantity += product.quantity;
}
}
await cart.save();
return { statusCode: 200, body: cart };
} else {
// If no cartId, create a new cart
const cart = await Cart.create({ items: event.body.product });
return { statusCode: 200, body: cart };
}
} catch (error) {
return { statusCode: 500, body: error.toString() };
}
};
module.exports = { handler };