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.

66 lines
1.6 KiB
JavaScript

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 items = await db.item.findAll()
res.json(items)
})
const newItemValidators = [
validate.validUrlSlug('urlslug'),
validate.publishedBool,
validate.positiveInteger('price_cents'),
validate.requiredString('name'),
validate.requiredString('description'),
validate.handleApiError
]
router.post('/', parseJSON, newItemValidators, 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.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))
})