forked from Automattic/mongoose
/
removeFromCart.js
34 lines (31 loc) · 970 Bytes
/
removeFromCart.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
'use strict';
const { Cart } = require('../../models');
const connect = require('../../connect');
const handler = async(event) => {
try {
event.body = JSON.parse(event.body || {});
await connect();
const cart = await Cart.findOne({ _id: event.body.cartId });
const index = cart.items.findIndex((item) =>
item.productId.toString() == event.body.item.productId.toString()
);
if (index == -1) {
return { statusCode: 200, body: cart };
}
if (event.body?.item?.quantity) {
cart.items[index].quantity -= event.body.item.quantity;
if (cart.items[index].quantity <= 0) {
cart.items.splice(index, 1);
}
await cart.save();
} else {
cart.items.splice(index, 1);
await cart.save();
}
return { statusCode: 200, body: JSON.stringify(cart) };
} catch (error) {
console.log(error);
return { statusCode: 500, body: error.toString() };
}
};
module.exports = { handler };