post.js 2.5 KB

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