post.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. let marked = require('marked')
  2. marked.setOptions({
  3. highlight: function (code) {
  4. return require('highlight.js').highlightAuto(code).value;
  5. },
  6. sanitize: true
  7. });
  8. module.exports = (sequelize, DataTypes) => {
  9. let Post = sequelize.define('Post', {
  10. content: {
  11. type: DataTypes.TEXT,
  12. set (val) {
  13. this.setDataValue('content', marked(val))
  14. }
  15. },
  16. postNumber: DataTypes.INTEGER,
  17. replyingToUsername: DataTypes.STRING,
  18. removed: {
  19. type: DataTypes.BOOLEAN,
  20. defaultValue: false
  21. }
  22. }, {
  23. instanceMethods: {
  24. getReplyingTo () {
  25. return Post.findByPrimary(this.replyId)
  26. },
  27. setReplyingTo (post) {
  28. return post.getUser().then(user => {
  29. return this.update({ replyingToUsername: user.username, replyId: post.id })
  30. })
  31. }
  32. },
  33. classMethods: {
  34. associate (models) {
  35. Post.belongsTo(models.User)
  36. Post.belongsTo(models.Thread)
  37. Post.hasMany(models.Post, { as: 'Replies', foreignKey: 'replyId' })
  38. Post.belongsToMany(models.User, { as: 'Likes', through: 'user_post' })
  39. },
  40. includeOptions () {
  41. let models = sequelize.models
  42. return [
  43. { model: models.User, attributes: ['username', 'createdAt', 'id', 'color'] },
  44. { model: models.User, as: 'Likes', attributes: ['username', 'createdAt', 'id', 'color'] },
  45. { model: models.Thread, include: [models.Category]} ,
  46. {
  47. model: models.Post, as: 'Replies', include:
  48. [{ model: models.User, attributes: ['username', 'id', 'color'] }]
  49. }
  50. ]
  51. }
  52. }
  53. })
  54. return Post
  55. }