category.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. } else if(!req.body.name.length) {
  36. validationErrors.push(Errors.parameterLengthTooSmall('name', '0'))
  37. }
  38. if(validationErrors.length) throw Errors.VALIDAITON_ERROR
  39. let category = await Category.create({
  40. name: req.body.name
  41. })
  42. res.json(category.toJSON())
  43. } catch (e) {
  44. if(e === Errors.VALIDAITON_ERROR) {
  45. res.status(400)
  46. res.json({
  47. errors: validationErrors
  48. })
  49. } else if(e.name === 'SequelizeUniqueConstraintError') {
  50. res.status(400)
  51. res.json({
  52. errors: [Errors.categoryAlreadyExists]
  53. })
  54. } else {
  55. res.status(500)
  56. res.json({
  57. errors: [Errors.unknown]
  58. })
  59. }
  60. }
  61. })
  62. module.exports = router