category.js 2.0 KB

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