category.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors')
  4. let { Category } = require('../models')
  5. router.get('/', async (req, res) => {
  6. try {
  7. let categories = await Category.findAll({
  8. attributes: { exclude: ['id'] }
  9. })
  10. res.json(categories)
  11. } catch (e) {
  12. res.status(500)
  13. res.json({
  14. errors: [Errors.unknown]
  15. })
  16. }
  17. })
  18. router.all('*', (req, res, next) => {
  19. if(!req.session.loggedIn || !req.session.admin) {
  20. res.status(401)
  21. res.json({
  22. errors: [Errors.requestNotAuthorized]
  23. })
  24. } else {
  25. next()
  26. }
  27. })
  28. router.post('/', async (req, res) => {
  29. let validationErrors = []
  30. try {
  31. if(req.body.name === undefined) {
  32. validationErrors.push(Errors.missingParameter('name'))
  33. } else if(typeof req.body.name !== 'string') {
  34. validationErrors.push(Errors.invalidParameterType('name', 'string'))
  35. }
  36. if(validationErrors.length) throw Errors.VALIDAITON_ERROR
  37. let category = await Category.create({
  38. name: req.body.name
  39. })
  40. res.json(category.toJSON())
  41. } catch (e) {
  42. if(e === Errors.VALIDAITON_ERROR) {
  43. res.status(400)
  44. res.json({
  45. errors: [validationErrors]
  46. })
  47. } else if(e.name === 'SequelizeUniqueConstraintError') {
  48. res.status(400)
  49. res.json({
  50. errors: [Errors.categoryAlreadyExists]
  51. })
  52. } else {
  53. res.status(500)
  54. res.json({
  55. errors: [Errors.unknown]
  56. })
  57. }
  58. }
  59. })
  60. module.exports = router