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.

113 lines
2.8 KiB
JavaScript

const router = module.exports = require('express-promise-router')()
const bodyParser = require('body-parser')
const parseJSON = bodyParser.json()
const b64 = require('base64-async')
const db = require('../db')
const ensureAdmin = require('./middleware/ensureAdmin')
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 = (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('/', ensureAdmin, 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,
req.body.hs_tariff_number,
req.body.customs_description,
req.body.origin_country,
req.body.weight
)
res.json(item)
})
router.get('/by-slug/:slug', async (req, res) => {
const item = await db.item.findBySlug(req.params.slug);
if(!item.published)
return res.json(null)
res.json(item)
})
router.post('/:uuid', ensureAdmin, 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', ensureAdmin, upload.single('image'), bodyParser.json({limit: '5MB'}), 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', ensureAdmin, async (req, res) => {
const item = await db.item.publish(req.params.uuid)
res.json(item)
})
router.post('/:uuid/unpublish', ensureAdmin, async (req, res) => {
const item = await db.item.unpublish(req.params.uuid)
res.json(item)
})
router.get('/:uuid/preorder/count', ensureAdmin, async (req, res) => {
const count = await db.item.getPreorderCount(req.params.uuid);
res.json(count)
})
router.post('/:uuid/preorder', ensureAdmin, parseJSON, async (req, res) => {
const item = await db.item.setPreorder(
req.params.uuid,
req.body.availability_date,
req.body.preorder_maximum
)
res.json(item);
})