notification.js 2.1 KB

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