thread.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors.js')
  4. let { User, Thread, Category, Post } = require('../models')
  5. let pagination = require('../lib/pagination.js')
  6. router.get('/:thread_id', async (req, res) => {
  7. try {
  8. let { lastId, limit, previousId } = pagination.getPaginationProps(req.query)
  9. let thread, resThread
  10. if(+req.query.postId) {
  11. let findObj = {
  12. limit: Math.floor(limit / 2),
  13. order: [['id', 'ASC']],
  14. include: Post.includeOptions()
  15. }
  16. thread = await Thread.findById(req.params.thread_id, {
  17. include: [
  18. { model: User, attributes: ['username', 'createdAt', 'color', 'updatedAt', 'id'] },
  19. Category,
  20. ]
  21. })
  22. if(!thread) throw Errors.invalidParameter('id', 'thread does not exist')
  23. resThread = thread.toJSON()
  24. let postsAfter = await Post.findAll(Object.assign({}, findObj, {
  25. where: {
  26. id: { $gt: +req.query.postId },
  27. threadId: req.params.thread_id,
  28. },
  29. }))
  30. let postsBefore = await Post.findAll(Object.assign({}, findObj, {
  31. where: {
  32. id: { $lte: +req.query.postId },
  33. threadId: req.params.thread_id,
  34. },
  35. order: [['id', 'DESC']],
  36. }))
  37. resThread.Posts = postsBefore
  38. .concat(postsAfter)
  39. .map(p => p.toJSON())
  40. .sort((a, b) => a.id - b.id)
  41. } else {
  42. thread = await Thread.findById(req.params.thread_id, {
  43. include: Thread.includeOptions(lastId, limit, previousId)
  44. })
  45. if(!thread) throw Errors.invalidParameter('id', 'thread does not exist')
  46. resThread = thread.toJSON()
  47. if(previousId) {
  48. resThread.Posts = resThread.Posts.sort((a, b) => a.id - b.id)
  49. }
  50. }
  51. resThread.meta = {}
  52. let nextId = await pagination.getNextId(
  53. Post,
  54. { threadId: +req.params.thread_id },
  55. resThread.Posts
  56. )
  57. let beforeId = await pagination.getPreviousId(
  58. Post,
  59. { threadId: +req.params.thread_id },
  60. resThread.Posts,
  61. limit
  62. )
  63. if(nextId) {
  64. resThread.meta.nextURL =
  65. `/api/v1/thread/${thread.id}?limit=${limit}&lastId=${nextId}`
  66. } else {
  67. resThread.meta.nextURL = null
  68. }
  69. if(beforeId) {
  70. resThread.meta.previousURL =
  71. `/api/v1/thread/${thread.id}?limit=${limit}&previousId=${beforeId}`
  72. } else {
  73. resThread.meta.previousURL = null
  74. }
  75. res.json(resThread)
  76. } catch (e) {
  77. if(e.name === 'invalidParameter') {
  78. res.status(400)
  79. res.json({
  80. errors: [e]
  81. })
  82. } else {
  83. console.log(e)
  84. res.status(500)
  85. res.json({
  86. errors: [Errors.unknown]
  87. })
  88. }
  89. }
  90. })
  91. router.all('*', (req, res, next) => {
  92. if(req.session.loggedIn) {
  93. next()
  94. } else {
  95. res.status(401)
  96. res.json({
  97. errors: [Errors.requestNotAuthorized]
  98. })
  99. }
  100. })
  101. router.post('/', async (req, res) => {
  102. let validationErrors = []
  103. try {
  104. if(req.body.name === undefined) {
  105. validationErrors.push(Errors.missingParameter('name'))
  106. } else if(typeof req.body.name !== 'string') {
  107. validationErrors.push(Errors.invalidParameterType('name', 'string'))
  108. }
  109. if(req.body.category === undefined) {
  110. validationErrors.push(Errors.missingParameter('category'))
  111. } else if(typeof req.body.category !== 'string') {
  112. validationErrors.push(Errors.invalidParameterType('category', 'string'))
  113. }
  114. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  115. let category = await Category.findOne({ where: {
  116. name: req.body.category
  117. }})
  118. if(!category) throw Errors.invalidCategory
  119. let user = await User.findOne({ where: {
  120. username: req.session.username
  121. }})
  122. let thread = await Thread.create({
  123. name: req.body.name
  124. })
  125. await thread.setCategory(category)
  126. await thread.setUser(user)
  127. res.json(await thread.reload({
  128. include: [
  129. { model: User, attributes: ['username', 'createdAt', 'updatedAt', 'id'] },
  130. Category
  131. ]
  132. }))
  133. } catch (e) {
  134. if(e === Errors.VALIDATION_ERROR) {
  135. res.status(400)
  136. res.json({
  137. errors: validationErrors
  138. })
  139. } else if(e === Errors.invalidCategory) {
  140. res.status(400)
  141. res.json({
  142. errors: [Errors.invalidCategory]
  143. })
  144. } else {
  145. console.log(e)
  146. res.status(500)
  147. res.json({
  148. errors: [Errors.unknown]
  149. })
  150. }
  151. }
  152. })
  153. module.exports = router