|
|
|
const router = module.exports = require('express-promise-router')()
|
|
|
|
const parseJSON = require('body-parser').json()
|
|
|
|
const db = require('../db')
|
|
|
|
|
|
|
|
const validate = require('./middleware/validators')
|
|
|
|
|
|
|
|
router.get('/', async (req, res) => {
|
|
|
|
const categories = await db.category.findAll()
|
|
|
|
|
|
|
|
res.json(categories)
|
|
|
|
})
|
|
|
|
|
|
|
|
router.get('/by-slug/:slug', async (req, res) => {
|
|
|
|
const category = await db.category.findBySlug(req.params.slug)
|
|
|
|
|
|
|
|
res.json(category)
|
|
|
|
})
|
|
|
|
|
|
|
|
const newCategoryValidators = [
|
|
|
|
validate.validUrlSlug('urlslug'),
|
|
|
|
validate.requiredString('name'),
|
|
|
|
validate.requiredString('description'),
|
|
|
|
validate.handleApiError
|
|
|
|
]
|
|
|
|
router.post('/', parseJSON, newCategoryValidators, async (req, res) => {
|
|
|
|
const category = await db.category.create(
|
|
|
|
req.body.name,
|
|
|
|
req.body.urlslug,
|
|
|
|
req.body.description
|
|
|
|
)
|
|
|
|
|
|
|
|
res.json(category)
|
|
|
|
})
|
|
|
|
|
|
|
|
router.post('/:uuid', parseJSON, newCategoryValidators, async (req, res) => {
|
|
|
|
const category = await db.category.update(
|
|
|
|
req.params.uuid,
|
|
|
|
req.body.name,
|
|
|
|
req.body.urlslug,
|
|
|
|
req.body.description
|
|
|
|
)
|
|
|
|
|
|
|
|
res.json(category)
|
|
|
|
})
|
|
|
|
|
|
|
|
router.put('/:category_uuid/items/:item_uuid', async (req, res) => {
|
|
|
|
const category = await db.category.addItem(req.params.category_uuid, req.params.item_uuid);
|
|
|
|
res.json(category)
|
|
|
|
})
|
|
|
|
|
|
|
|
router.delete('/:category_uuid/items/:item_uuid', async (req, res) => {
|
|
|
|
const category = await db.category.removeItem(req.params.category_uuid, req.params.item_uuid);
|
|
|
|
res.json(category)
|
|
|
|
})
|
|
|
|
|
|
|
|
router.put('/:parent_uuid/children/:child_uuid', async (req, res) => {
|
|
|
|
const category = await db.category.addCategory(req.params.parent_uuid, req.params.child_uuid);
|
|
|
|
res.json(category)
|
|
|
|
})
|