comment.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // disable no-return-await for model functions
  2. /* eslint-disable no-return-await */
  3. module.exports = function(crowi) {
  4. const debug = require('debug')('growi:models:comment');
  5. const mongoose = require('mongoose');
  6. const ObjectId = mongoose.Schema.Types.ObjectId;
  7. const commentSchema = new mongoose.Schema({
  8. page: { type: ObjectId, ref: 'Page', index: true },
  9. creator: { type: ObjectId, ref: 'User', index: true },
  10. revision: { type: ObjectId, ref: 'Revision', index: true },
  11. comment: { type: String, required: true },
  12. commentPosition: { type: Number, default: -1 },
  13. createdAt: { type: Date, default: Date.now },
  14. isMarkdown: { type: Boolean, default: false },
  15. replyTo: { type: ObjectId, default: undefined },
  16. });
  17. commentSchema.statics.create = function(pageId, creatorId, revisionId, comment, position, isMarkdown, replyTo) {
  18. const Comment = this;
  19. return new Promise(((resolve, reject) => {
  20. const newComment = new Comment();
  21. newComment.page = pageId;
  22. newComment.creator = creatorId;
  23. newComment.revision = revisionId;
  24. newComment.comment = comment;
  25. newComment.commentPosition = position;
  26. newComment.isMarkdown = isMarkdown || false;
  27. newComment.replyTo = replyTo;
  28. newComment.save((err, data) => {
  29. if (err) {
  30. debug('Error on saving comment.', err);
  31. return reject(err);
  32. }
  33. debug('Comment saved.', data);
  34. return resolve(data);
  35. });
  36. }));
  37. };
  38. commentSchema.statics.getCommentsByPageId = function(id) {
  39. return this.find({ page: id }).sort({ createdAt: -1 });
  40. };
  41. commentSchema.statics.getCommentsByRevisionId = function(id) {
  42. return this.find({ revision: id }).sort({ createdAt: -1 });
  43. };
  44. commentSchema.statics.countCommentByPageId = function(page) {
  45. const self = this;
  46. return new Promise(((resolve, reject) => {
  47. self.count({ page }, (err, data) => {
  48. if (err) {
  49. return reject(err);
  50. }
  51. return resolve(data);
  52. });
  53. }));
  54. };
  55. commentSchema.statics.removeCommentsByPageId = function(pageId) {
  56. const Comment = this;
  57. return new Promise(((resolve, reject) => {
  58. Comment.remove({ page: pageId }, (err, done) => {
  59. if (err) {
  60. return reject(err);
  61. }
  62. resolve(done);
  63. });
  64. }));
  65. };
  66. /**
  67. * post save hook
  68. */
  69. commentSchema.post('save', (savedComment) => {
  70. const Page = crowi.model('Page');
  71. Page.updateCommentCount(savedComment.page)
  72. .then((page) => {
  73. debug('CommentCount Updated', page);
  74. })
  75. .catch(() => {
  76. });
  77. });
  78. return mongoose.model('Comment', commentSchema);
  79. };