const router = module.exports = require('express-promise-router')() const parseJSON = require('body-parser').json() const db = require('../db') const validate = require('./middleware/validators') router.use(require('./middleware/ensureCart')) router.put('/', async (req, res) => { const order = await db.order.create(req.cart.uuid); res.json(order) }) router.get('/current', async (req, res) => { const order = await db.order.findForCart(req.cart.uuid); res.json(order) }) router.post('/current/address', parseJSON, validate.address, validate.handleApiError, async (req, res) => { const origOrder = await db.order.findForCart(req.cart.uuid); if(!origOrder) throw new Error("Unable to find current order"); const currentTransaction = origOrder .transactions.find(transaction => ( transaction.payment_state === 'started' )) const {name, street1, street2, city, state, zip, country} = req.body; // Create address, update order const address = await db.address.create(name, street1, street2, city, state, zip, country) const order = await db.order.addAddress(currentTransaction, address) res.json(order) }) router.post('/current/coupon', parseJSON, validate.coupon, validate.handleApiError, async (req, res) => { const origOrder = await db.order.findForCart(req.cart.uuid); if(!origOrder) throw new Error("Unable to find current order"); const coupon = await db.coupon.find(req.body.code) const currentTransaction = origOrder .transactions.find(transaction => ( transaction.payment_state === 'started' )) const order = await db.order.addCoupon(currentTransaction, coupon) res.json(order) })