40 lines
1.2 KiB
JavaScript
40 lines
1.2 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const Cart = require('../models/Cart');
|
|
const auth = require('../middleware/auth');
|
|
|
|
// Получить корзину пользователя
|
|
router.get('/', auth, async (req, res) => {
|
|
try {
|
|
let cart = await Cart.findOne({ userId: req.userId }).populate('userId');
|
|
if (!cart) {
|
|
cart = new Cart({ userId: req.userId, items: [] });
|
|
await cart.save();
|
|
}
|
|
res.json(cart);
|
|
} catch (error) {
|
|
res.status(500).json({ message: 'Something went wrong' });
|
|
}
|
|
});
|
|
|
|
// Обновить корзину
|
|
router.post('/', auth, async (req, res) => {
|
|
try {
|
|
const { items } = req.body;
|
|
|
|
let cart = await Cart.findOne({ userId: req.userId });
|
|
if (!cart) {
|
|
cart = new Cart({ userId: req.userId, items });
|
|
} else {
|
|
cart.items = items;
|
|
cart.updatedAt = Date.now();
|
|
}
|
|
|
|
await cart.save();
|
|
res.json(cart);
|
|
} catch (error) {
|
|
res.status(500).json({ message: 'Something went wrong' });
|
|
}
|
|
});
|
|
|
|
module.exports = router; |