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') const upload = require('multer')({ storage: require('multer').memoryStorage(), limits: { files: 1, fileSize: 3000000 } }) router.get('/', async (req, res) => { const items = await db.item.findAll() res.json(items) }) const newItemValidators = [ validate.urlSlugRestrictions, validate.publishedBool, validate.priceCentsInt, validate.nameRestrictions, validate.descriptionRestrictions ] router.post('/', parseJSON, newItemValidators, async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) return res.status(422).json({errors: errors.array()}) 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.delete('/:uuid', async (req, res) => { const result = await db.item.removeItem(req.params.uuid) res.json({deleted: true}) }) 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)) })