notification.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors')
  4. let { Notification } = 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. '$User.username$': req.session.username
  20. },
  21. include: [{
  22. model: 'MentionNotification',
  23. include: ['User', 'Post']
  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. res.status(500)
  32. res.json({
  33. errors: [Errors.unknown]
  34. })
  35. }
  36. })
  37. router.put('/', async (req, res) => {
  38. try {
  39. await Notification.updateAll({ read: true }, {
  40. where: {
  41. '$User.username$': req.session.username,
  42. 'read': false
  43. }
  44. })
  45. res.json({ success: true })
  46. } catch (e) {
  47. res.status(500)
  48. res.json({
  49. errors: [Errors.unknown]
  50. })
  51. }
  52. })
  53. module.exports = router