/
addToCart.js
41 lines (36 loc) · 1.35 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
'use strict';
const { Cart, Product } = require('../../models');
const connect = require('../../index');
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 });
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 };