const router = module.exports = require('express-promise-router')() const parseJSON = require('body-parser').json() const db = require('../db') const validate = require('./middleware/validators') const upload = require('multer')({ storage: require('multer').memoryStorage(), limits: { files: 1, fileSize: 3000000 } }) router.get('/', async (req, res) => { const showUnpublished = // Only respect query parameter if user is admin (req.user && req.user.is_admin) ? req.query.showUnpublished : false const items = await db.item.findAll(showUnpublished) res.json(items) }) const itemValidators = [ validate.validUrlSlug('urlslug'), validate.publishedBool, validate.positiveInteger('price_cents'), validate.requiredString('name'), validate.requiredString('description'), validate.handleApiError ] router.post('/', parseJSON, itemValidators, async (req, res) => { const item = await db.item.create( req.body.name, req.body.urlslug, req.body.description, req.body.price_cents, req.body.published ) res.json(item) }) router.get('/by-slug/:slug', async (req, res) => { const item = await db.item.findBySlug(req.params.slug); res.json(item) }) router.post('/:uuid', parseJSON, itemValidators, async (req, res) => { const item = await db.item.update( req.params.uuid, req.body.name, req.body.urlslug, req.body.description, req.body.price_cents, req.body.published ) res.json(item) }) router.post('/:uuid/images', upload.single('image'), async (req, res) => { // Handle either image upload body or JSON body try { if(req.file) await db.item.addImage(req.params.uuid, req.file.buffer, req.user.uuid) else await db.item.addImage(req.params.uuid, await b64.decode(req.body.image.split(',')[1]), req.user.uuid) } catch (error) { error.status = 500 throw error } res.json(await db.item.findById(req.params.uuid)) }) router.post('/:uuid/publish', async (req, res) => { const item = await db.item.publish(req.params.uuid) res.json(item) }) router.post('/:uuid/unpublish', async (req, res) => { const item = await db.item.unpublish(req.params.uuid) res.json(item) })