notification.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors')
  4. let { Notification, User, Post, MentionNotification } = require('../models')
  5. router.all('*', (req, res, next) => {
  6. if(req.session.loggedIn) {
  7. next()
  8. } else {
  9. res.status(401)
  10. res.json({
  11. errors: [Errors.requestNotAuthorized]
  12. })
  13. }
  14. })
  15. router.get('/', async (req, res) => {
  16. try {
  17. let Notifications = await Notification.findAll({
  18. where: {
  19. 'UserId': req.session.UserId
  20. },
  21. include: [{
  22. model: MentionNotification,
  23. include: [Post, { model: User, attributes: ['createdAt', 'username', 'color'] }]
  24. }]
  25. })
  26. let unreadCount = Notifications.reduce((acc, val) => {
  27. return val.read ? acc : acc+1
  28. }, 0)
  29. res.json({ Notifications, unreadCount })
  30. } catch (e) {
  31. console.log(e)
  32. res.status(500)
  33. res.json({
  34. errors: [Errors.unknown]
  35. })
  36. }
  37. })
  38. router.put('/', async (req, res) => {
  39. try {
  40. await Notification.update({ read: true }, {
  41. where: {
  42. 'UserId': req.session.UserId,
  43. 'read': false
  44. }
  45. })
  46. res.json({ success: true })
  47. } catch (e) {
  48. console.log(e)
  49. res.status(500)
  50. res.json({
  51. errors: [Errors.unknown]
  52. })
  53. }
  54. })
  55. router.put('/:id', async (req, res) => {
  56. try {
  57. let updatedRows = await Notification.update({ interacted: true, read: true }, {
  58. where: {
  59. 'UserId': req.session.UserId,
  60. id: req.params.id
  61. }
  62. })
  63. if(updatedRows[0] === 0) {
  64. res.status(400)
  65. res.json({
  66. errors: [Errors.invalidParameter('id', 'invalid notification id')]
  67. })
  68. } else {
  69. res.json({ success: true })
  70. }
  71. } catch (e) {
  72. console.log(e)
  73. res.status(500)
  74. res.json({
  75. errors: [Errors.unknown]
  76. })
  77. }
  78. })
  79. router.delete('/:id', async (req, res) => {
  80. try {
  81. let deleted = await Notification.destroy({
  82. where: {
  83. 'UserId': req.session.UserId,
  84. id: req.params.id
  85. }
  86. })
  87. if(deleted) {
  88. res.json({ success: true })
  89. } else {
  90. res.status(400)
  91. res.json({
  92. errors: [Errors.invalidParameter('id', 'invalid notification id')]
  93. })
  94. }
  95. } catch (e) {
  96. console.log(e)
  97. res.status(500)
  98. res.json({
  99. errors: [Errors.unknown]
  100. })
  101. }
  102. })
  103. module.exports = router