post.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. }, {
  19. instanceMethods: {
  20. getReplyingTo () {
  21. return Post.findByPrimary(this.replyId)
  22. },
  23. setReplyingTo (post) {
  24. return post.getUser().then(user => {
  25. return this.update({ replyingToUsername: user.username, replyId: post.id })
  26. })
  27. }
  28. },
  29. classMethods: {
  30. associate (models) {
  31. Post.belongsTo(models.User)
  32. Post.belongsTo(models.Thread)
  33. Post.hasMany(models.Post, { as: 'Replies', foreignKey: 'replyId' })
  34. Post.belongsToMany(models.User, { as: 'Likes', through: 'user_post' })
  35. },
  36. includeOptions () {
  37. let models = sequelize.models
  38. return [
  39. { model: models.User, attributes: ['username', 'createdAt', 'id', 'color'] },
  40. { model: models.User, as: 'Likes', attributes: ['username', 'createdAt', 'id', 'color'] },
  41. { model: models.Thread, include: [models.Category]} ,
  42. {
  43. model: models.Post, as: 'Replies', include:
  44. [{ model: models.User, attributes: ['username', 'id', 'color'] }]
  45. }
  46. ]
  47. }
  48. }
  49. })
  50. return Post
  51. }