notification.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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, next) => {
  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) { next(e) }
  32. })
  33. router.put('/', async (req, res, next) => {
  34. try {
  35. await Notification.update({ read: true }, {
  36. where: {
  37. 'UserId': req.session.UserId,
  38. 'read': false
  39. }
  40. })
  41. res.json({ success: true })
  42. } catch (e) { next(e) }
  43. })
  44. router.put('/:id', async (req, res, next) => {
  45. try {
  46. let updatedRows = await Notification.update({ interacted: true, read: true }, {
  47. where: {
  48. 'UserId': req.session.UserId,
  49. id: req.params.id
  50. }
  51. })
  52. if(updatedRows[0] === 0) {
  53. res.status(400)
  54. res.json({
  55. errors: [Errors.invalidParameter('id', 'invalid notification id')]
  56. })
  57. } else {
  58. res.json({ success: true })
  59. }
  60. } catch (e) { next(e) }
  61. })
  62. router.delete('/:id', async (req, res, next) => {
  63. try {
  64. let deleted = await Notification.destroy({
  65. where: {
  66. 'UserId': req.session.UserId,
  67. id: req.params.id
  68. }
  69. })
  70. if(deleted) {
  71. res.json({ success: true })
  72. } else {
  73. res.status(400)
  74. res.json({
  75. errors: [Errors.invalidParameter('id', 'invalid notification id')]
  76. })
  77. }
  78. } catch (e) { next(e) }
  79. })
  80. module.exports = router