category.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. include: Category.includeOptions(1)
  10. })
  11. res.json(categories)
  12. } catch (e) {
  13. res.status(500)
  14. res.json({
  15. errors: [Errors.unknown]
  16. })
  17. }
  18. })
  19. router.get('/:category', async (req, res) => {
  20. try {
  21. let threads
  22. if(req.params.category === 'ALL') {
  23. threads = await Category.findAll({ include: Category.includeOptions() })
  24. } else {
  25. threads = await Category.findOne({
  26. where: { name: req.params.category },
  27. include: Category.includeOptions()
  28. })
  29. }
  30. if(!threads) throw Errors.invalidParameter('id', 'thread does not exist')
  31. res.json(threads.toJSON())
  32. } catch (e) {
  33. if(e.name === 'invalidParameter') {
  34. res.status(400)
  35. res.json({
  36. errors: [e]
  37. })
  38. } else {
  39. console.log(e)
  40. res.status(500)
  41. res.json({
  42. errors: [Errors.unknown]
  43. })
  44. }
  45. }
  46. })
  47. router.all('*', (req, res, next) => {
  48. if(!req.session.loggedIn || !req.session.admin) {
  49. res.status(401)
  50. res.json({
  51. errors: [Errors.requestNotAuthorized]
  52. })
  53. } else {
  54. next()
  55. }
  56. })
  57. router.post('/', async (req, res) => {
  58. let validationErrors = []
  59. try {
  60. if(req.body.name === undefined) {
  61. validationErrors.push(Errors.missingParameter('name'))
  62. } else if(typeof req.body.name !== 'string') {
  63. validationErrors.push(Errors.invalidParameterType('name', 'string'))
  64. } else if(!req.body.name.length) {
  65. validationErrors.push(Errors.parameterLengthTooSmall('name', '0'))
  66. }
  67. if(validationErrors.length) throw Errors.VALIDAITON_ERROR
  68. let category = await Category.create({
  69. name: req.body.name
  70. })
  71. res.json(category.toJSON())
  72. } catch (e) {
  73. if(e === Errors.VALIDAITON_ERROR) {
  74. res.status(400)
  75. res.json({
  76. errors: validationErrors
  77. })
  78. } else if(e.name === 'SequelizeUniqueConstraintError') {
  79. res.status(400)
  80. res.json({
  81. errors: [Errors.categoryAlreadyExists]
  82. })
  83. } else {
  84. res.status(500)
  85. res.json({
  86. errors: [Errors.unknown]
  87. })
  88. }
  89. }
  90. })
  91. module.exports = router