post.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. let marked = require('marked')
  2. const Errors = require('../lib/errors')
  3. marked.setOptions({
  4. highlight: function (code) {
  5. return require('highlight.js').highlightAuto(code).value;
  6. },
  7. sanitize: true
  8. });
  9. module.exports = (sequelize, DataTypes) => {
  10. let Post = sequelize.define('Post', {
  11. content: {
  12. type: DataTypes.TEXT,
  13. set (val) {
  14. if(!val) throw Errors.sequelizeValidation(sequelize, {
  15. error: 'content must be a string',
  16. path: 'content'
  17. })
  18. this.setDataValue('content', marked(val))
  19. },
  20. allowNull: false
  21. },
  22. postNumber: DataTypes.INTEGER,
  23. replyingToUsername: DataTypes.STRING,
  24. removed: {
  25. type: DataTypes.BOOLEAN,
  26. defaultValue: false
  27. }
  28. }, {
  29. instanceMethods: {
  30. getReplyingTo () {
  31. return Post.findByPrimary(this.replyId)
  32. },
  33. setReplyingTo (post) {
  34. return post.getUser().then(user => {
  35. return this.update({ replyingToUsername: user.username, replyId: post.id })
  36. })
  37. }
  38. },
  39. classMethods: {
  40. associate (models) {
  41. Post.belongsTo(models.User)
  42. Post.belongsTo(models.Thread)
  43. Post.hasMany(models.Post, { as: 'Replies', foreignKey: 'replyId' })
  44. Post.belongsToMany(models.User, { as: 'Likes', through: 'user_post' })
  45. Post.hasMany(models.Report, { foreignKeyConstraint: true, onDelete: 'CASCADE', hooks: true })
  46. },
  47. includeOptions () {
  48. let models = sequelize.models
  49. return [
  50. { model: models.User, attributes: ['username', 'createdAt', 'id', 'color', 'picture'] },
  51. { model: models.User, as: 'Likes', attributes: ['username', 'createdAt', 'id', 'color', 'picture'] },
  52. { model: models.Thread, include: [models.Category]} ,
  53. {
  54. model: models.Post, as: 'Replies', include:
  55. [{ model: models.User, attributes: ['username', 'id', 'color', 'picture'] }]
  56. }
  57. ]
  58. },
  59. async getReplyingToPost (id, thread) {
  60. let { Thread, User } = sequelize.models
  61. let replyingToPost = await Post.findById(
  62. id,
  63. { include: [Thread, { model: User, attributes: ['username'] }] }
  64. )
  65. if(!replyingToPost) {
  66. throw Errors.invalidParameter('replyingToId', 'post does not exist')
  67. } else if(replyingToPost.Thread.id !== thread.id) {
  68. throw Errors.invalidParameter('replyingToId', 'replies must be in same thread')
  69. } else if (replyingToPost.removed) {
  70. throw Errors.postRemoved
  71. } else {
  72. return replyingToPost
  73. }
  74. }
  75. }
  76. })
  77. return Post
  78. }