Notification.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const Errors = require('../lib/errors')
  2. module.exports = (sequelize, DataTypes) => {
  3. let Notification = sequelize.define('Notification', {
  4. interacted: {
  5. type: DataTypes.BOOLEAN,
  6. defaultValue: false
  7. },
  8. read: {
  9. type: DataTypes.BOOLEAN,
  10. defaultValue: false
  11. },
  12. type: DataTypes.ENUM('mention', 'thread update', 'reply')
  13. }, {
  14. classMethods: {
  15. associate (models) {
  16. Notification.hasOne(models.PostNotification)
  17. Notification.belongsTo(models.User)
  18. },
  19. filterMentions (mentions) {
  20. //If mentions is not an array of strings
  21. if(!Array.isArray(mentions) || mentions.filter(m => typeof m !== 'string').length) {
  22. throw Errors.sequelizeValidation(sequelize, {
  23. error: 'mentions must be an array of strings',
  24. value: mentions
  25. })
  26. }
  27. return mentions.filter((mention, pos, self) => {
  28. return self.indexOf(mention) === pos
  29. })
  30. },
  31. //Props fields: userFrom, usernameTo, post, type
  32. async createPostNotification (props) {
  33. let { PostNotification, User, Post } = sequelize.models
  34. let userTo = await User.findOne({ where: { username: props.usernameTo } })
  35. if(!userTo) return null
  36. let notification = await Notification.create({ type: props.type })
  37. let postNotification = await PostNotification.create()
  38. await postNotification.setUser(props.userFrom)
  39. await postNotification.setPost(props.post)
  40. await notification.setPostNotification(postNotification)
  41. await notification.setUser(userTo)
  42. let reloadedNotification = await notification.reload({
  43. include: [{
  44. model: PostNotification,
  45. include: [Post, { model: User, attributes: ['createdAt', 'username', 'color'] }]
  46. }]
  47. })
  48. return reloadedNotification
  49. }
  50. },
  51. instanceMethods: {
  52. async emitNotificationMessage (ioUsers, io) {
  53. let User = sequelize.models.User
  54. let user = await User.findById(this.UserId)
  55. if(ioUsers[user.username]) {
  56. console.log(ioUsers)
  57. io.to(ioUsers[user.username])
  58. .emit('notification', this.toJSON())
  59. }
  60. }
  61. }
  62. })
  63. return Notification
  64. }