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) })