notification.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. module.exports = router