thread.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors.js')
  4. let { User, Thread, Category } = require('../models')
  5. router.get('/:thread_id', async (req, res) => {
  6. try {
  7. let thread = await Thread.findById(req.params.thread_id, { include: Thread.includeOptions() })
  8. if(!thread) throw Errors.invalidParameter('id', 'thread does not exist')
  9. res.json(thread.toJSON())
  10. } catch (e) {
  11. if(e.name === 'invalidParameter') {
  12. res.status(400)
  13. res.json({
  14. errors: [e]
  15. })
  16. } else {
  17. console.log(e)
  18. res.status(500)
  19. res.json({
  20. errors: [Errors.unknown]
  21. })
  22. }
  23. }
  24. })
  25. router.all('*', (req, res, next) => {
  26. if(req.session.loggedIn) {
  27. next()
  28. } else {
  29. res.status(401)
  30. res.json({
  31. errors: [Errors.requestNotAuthorized]
  32. })
  33. }
  34. })
  35. router.post('/', async (req, res) => {
  36. let validationErrors = []
  37. try {
  38. if(req.body.name === undefined) {
  39. validationErrors.push(Errors.missingParameter('name'))
  40. } else if(typeof req.body.name !== 'string') {
  41. validationErrors.push(Errors.invalidParameterType('name', 'string'))
  42. }
  43. if(req.body.category === undefined) {
  44. validationErrors.push(Errors.missingParameter('category'))
  45. } else if(typeof req.body.category !== 'string') {
  46. validationErrors.push(Errors.invalidParameterType('category', 'string'))
  47. }
  48. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  49. let category = await Category.findOne({ where: {
  50. name: req.body.category
  51. }})
  52. if(!category) throw Errors.invalidCategory
  53. let user = await User.findOne({ where: {
  54. username: req.session.username
  55. }})
  56. let thread = await Thread.create({
  57. name: req.body.name
  58. })
  59. await thread.setCategory(category)
  60. await thread.setUser(user)
  61. res.json(await thread.reload({
  62. include: [
  63. { model: User, attributes: ['username', 'createdAt', 'updatedAt', 'id'] },
  64. Category
  65. ]
  66. }))
  67. } catch (e) {
  68. if(e === Errors.VALIDATION_ERROR) {
  69. res.status(400)
  70. res.json({
  71. errors: validationErrors
  72. })
  73. } else if(e === Errors.invalidCategory) {
  74. res.status(400)
  75. res.json({
  76. errors: [Errors.invalidCategory]
  77. })
  78. } else {
  79. console.log(e)
  80. res.status(500)
  81. res.json({
  82. errors: [Errors.unknown]
  83. })
  84. }
  85. }
  86. })
  87. module.exports = router