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.

71 lines
1.7 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')
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) => {
// TODO: Use the real user when we have authentication
req.user = {
uuid: '56881ad0-8d80-496a-b036-aed03d0895ce'
}
// 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))
})