You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.1 KiB
JavaScript

const router = module.exports = require('express-promise-router')()
const parseJSON = require('body-parser').json()
const db = require('../db')
const {validationResult} = require('express-validator')
const validate = require('./middleware/validators')
router.get('/', async (req, res)=>{
res.json(req.cart);
})
const cartAddValidators = [validate.countInt]
router.post('/add/:item_uuid', parseJSON, cartAddValidators, async (req, res) => {
// Check form input
const errors = validationResult(req)
if(!errors.isEmpty())
return res.status(422).json({errors: errors.array()})
// Ensure session
if(!req.session.uuid)
await db.session.create(req)
// Ensure cart
if(!req.cart)
req.cart = await db.cart.create(req.session.uuid)
// Add item
const cart = await db.cart.addItemToCart(req.cart.uuid, req.params.item_uuid, req.body.count)
res.json(cart)
})
router.post('/remove/:item_uuid', async (req, res) => {
if(!req.cart) return res.json(null)
const cart = await db.cart.removeItemFromCart(req.cart.uuid, req.params.item_uuid);
res.json(cart)
})