Skip to content

Commit b3f3f8c

Browse files
authored
Merge pull request #3 from danilo04/fix-get-car-items
Retornar 404 cuando el carrito de compras no existe
2 parents f62e4c3 + 2c9ff46 commit b3f3f8c

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

routes/cart.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,12 @@ router.post('/:cartId/items', async (req, res) => {
2727
router.get('/:cartId/items', async (req, res) => {
2828
try {
2929
const items = await CartService.getCartItems(req.params.cartId);
30-
res.json(items);
30+
if (items) {
31+
res.json(items);
32+
} else {
33+
res.status(404).json({ error: "Cart doesn't exist" });
34+
}
35+
3136
} catch (error) {
3237
res.status(400).json({ error: error.message });
3338
}

services/cartService.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,15 @@ class CartService {
3636
}
3737

3838
static async getCartItems(cartId) {
39+
if (isNaN(cartId)) {
40+
throw new Error('Cart ID should be a number');
41+
}
42+
43+
const cart = await Cart.findByPk(cartId)
44+
if (!cart) {
45+
return null;
46+
}
47+
3948
const items = await CartItem.findAll({
4049
where: { cartId },
4150
include: Product,

tests/routes/cart.test.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,16 @@ describe('Cart Routes', () => {
5353
});
5454

5555
describe('GET /api/carts/:cartId/items', () => {
56-
it('should return cart items with totals', async () => {
56+
it('should return 404 when cart does not exist', async () => {
57+
const response = await request(app)
58+
.get('/api/carts/1/items')
59+
.expect(404);
60+
});
5761

62+
it('should return 400 when cart id wrong format', async () => {
63+
const response = await request(app)
64+
.get('/api/carts/nonidad123/items')
65+
.expect(400);
5866
});
5967
});
6068
});

0 commit comments

Comments
 (0)