post.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors')
  4. let { User, Thread, Post, Notification } = require('../models')
  5. router.get('/:post_id', async (req, res) => {
  6. try {
  7. let post = await Post.findById(req.params.post_id, { include: Post.includeOptions() })
  8. if(!post) throw Errors.invalidParameter('id', 'post does not exist')
  9. res.json(post.toJSON())
  10. } catch (e) {
  11. if(e.name === 'invalidParameter') {
  12. res.status(400)
  13. res.json({
  14. errors: [e]
  15. })
  16. } else {
  17. res.status(500)
  18. res.json({
  19. errors: [Errors.unknown]
  20. })
  21. }
  22. }
  23. })
  24. router.all('*', (req, res, next) => {
  25. if(req.session.loggedIn) {
  26. next()
  27. } else {
  28. res.status(401)
  29. res.json({
  30. errors: [Errors.requestNotAuthorized]
  31. })
  32. }
  33. })
  34. router.put('/:post_id/like', async (req, res) => {
  35. try {
  36. let post = await Post.findById(req.params.post_id)
  37. let user = await User.findOne({ where: { username: req.session.username }})
  38. if(!post) throw Errors.invalidParameter('id', 'post does not exist')
  39. if(post.UserId === user.id) throw Errors.cannotLikeOwnPost
  40. await post.addLikes(user)
  41. res.json({ success: true })
  42. } catch (e) {
  43. if(['invalidParameter', 'cannotLikeOwnPost'].includes(e.name)) {
  44. res.status(400)
  45. res.json({
  46. errors: [e]
  47. })
  48. } else{
  49. console.log(e)
  50. res.status(500)
  51. res.json({
  52. errors: [Errors.unknown]
  53. })
  54. }
  55. }
  56. })
  57. router.delete('/:post_id/like', async (req, res) => {
  58. try {
  59. let post = await Post.findById(req.params.post_id)
  60. let user = await User.findOne({ where: { username: req.session.username }})
  61. if(!post) throw Errors.invalidParameter('id', 'post does not exist')
  62. await post.removeLikes(user)
  63. res.json({ success: true })
  64. } catch (e) {
  65. if(e.name === 'invalidParameter') {
  66. res.status(400)
  67. res.json({
  68. errors: [e]
  69. })
  70. } else{
  71. console.log(e)
  72. res.status(500)
  73. res.json({
  74. errors: [Errors.unknown]
  75. })
  76. }
  77. }
  78. })
  79. router.post('/', async (req, res) => {
  80. let validationErrors = []
  81. let thread, replyingToPost, post
  82. try {
  83. if(req.body.content === undefined) {
  84. validationErrors.push(Errors.missingParameter('content'))
  85. } else if(typeof req.body.content !== 'string') {
  86. validationErrors.push(Errors.invalidParameterType('content', 'string'))
  87. } if (req.body.threadId === undefined) {
  88. validationErrors.push(Errors.missingParameter('threadId'))
  89. } else if(!Number.isInteger(req.body.threadId)) {
  90. validationErrors.push(Errors.invalidParameterType('threadId', 'integer'))
  91. } if(req.body.replyingToId !== undefined && !Number.isInteger(req.body.replyingToId)) {
  92. validationErrors.push(Errors.invalidParameterType('replyingToId', 'integer'))
  93. } if(req.body.mentions !== undefined) {
  94. if(Array.isArray(req.body.mentions)) {
  95. if(req.body.mentions.some(m => typeof m !== 'string')) {
  96. validationErrors.push(Errors.invalidParameterType('mention', 'string'))
  97. }
  98. } else {
  99. validationErrors.push(Errors.invalidParameterType('mentions', 'array'))
  100. }
  101. }
  102. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  103. thread = await Thread.findOne({ where: {
  104. id: req.body.threadId
  105. }})
  106. user = await User.findOne({ where: {
  107. username: req.session.username
  108. }})
  109. if(!thread) throw Errors.invalidParameter('threadId', 'thread does not exist')
  110. if(req.body.replyingToId) {
  111. replyingToPost = await Post.findById(
  112. req.body.replyingToId,
  113. { include: [Thread, { model: User, attributes: ['username'] }] }
  114. )
  115. if(!replyingToPost) {
  116. throw Errors.invalidParameter('replyingToId', 'post does not exist')
  117. } else if(replyingToPost.Thread.id !== thread.id) {
  118. throw Errors.invalidParameter('replyingToId', 'replies must be in same thread')
  119. } else {
  120. post = await Post.create({ content: req.body.content, postNumber: thread.postsCount })
  121. await post.setReplyingTo(replyingToPost)
  122. await replyingToPost.addReplies(post)
  123. let replyNotification = await Notification.createPostNotification({
  124. usernameTo: replyingToPost.User.username,
  125. userFrom: user,
  126. type: 'reply',
  127. post: post
  128. })
  129. let ioUsers = req.app.get('io-users')
  130. if(ioUsers[replyingToPost.User.username]) {
  131. req.app
  132. .get('io')
  133. .to(ioUsers[replyingToPost.User.username])
  134. .emit('notification', replyNotification.toJSON())
  135. }
  136. }
  137. } else {
  138. post = await Post.create({ content: req.body.content, postNumber: thread.postsCount })
  139. }
  140. await post.setUser(user)
  141. await post.setThread(thread)
  142. await thread.increment('postsCount')
  143. if(req.body.mentions) {
  144. for(var i = 0; i < req.body.mentions.length; i++) {
  145. let mention = req.body.mentions[i]
  146. let ioUsers = req.app.get('io-users')
  147. let mentionNotification = await Notification.createPostNotification({
  148. usernameTo: mention,
  149. userFrom: user,
  150. type: 'mention',
  151. post
  152. })
  153. if(ioUsers[mention]) {
  154. req.app.get('io').to(ioUsers[mention]).emit('notification', mentionNotification.toJSON())
  155. }
  156. }
  157. }
  158. res.json(await post.reload({
  159. include: Post.includeOptions()
  160. }))
  161. req.app.get('io').to('thread/' + thread.id).emit('new post', {
  162. postNumber: thread.postsCount
  163. })
  164. } catch (e) {
  165. if(e === Errors.VALIDATION_ERROR) {
  166. res.status(400)
  167. res.json({
  168. errors: validationErrors
  169. })
  170. } else if(e.name === 'invalidParameter') {
  171. res.status(400)
  172. res.json({
  173. errors: [e]
  174. })
  175. } else {
  176. console.log(e)
  177. res.status(500)
  178. res.json({
  179. errors: [Errors.unknown]
  180. })
  181. }
  182. }
  183. })
  184. module.exports = router