/
comment.js
105 lines (87 loc) · 2.81 KB
/
comment.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// disable no-return-await for model functions
/* eslint-disable no-return-await */
module.exports = function(crowi) {
const debug = require('debug')('growi:models:comment');
const mongoose = require('mongoose');
const ObjectId = mongoose.Schema.Types.ObjectId;
const commentSchema = new mongoose.Schema({
page: { type: ObjectId, ref: 'Page', index: true },
creator: { type: ObjectId, ref: 'User', index: true },
revision: { type: ObjectId, ref: 'Revision', index: true },
comment: { type: String, required: true },
commentPosition: { type: Number, default: -1 },
isMarkdown: { type: Boolean, default: false },
replyTo: { type: ObjectId },
}, {
timestamps: true,
});
commentSchema.statics.create = function(pageId, creatorId, revisionId, comment, position, isMarkdown, replyTo) {
const Comment = this;
return new Promise(((resolve, reject) => {
const newComment = new Comment();
newComment.page = pageId;
newComment.creator = creatorId;
newComment.revision = revisionId;
newComment.comment = comment;
newComment.commentPosition = position;
newComment.isMarkdown = isMarkdown || false;
newComment.replyTo = replyTo;
newComment.save((err, data) => {
if (err) {
debug('Error on saving comment.', err);
return reject(err);
}
debug('Comment saved.', data);
return resolve(data);
});
}));
};
commentSchema.statics.getCommentsByPageId = function(id) {
return this.find({ page: id }).sort({ createdAt: -1 });
};
commentSchema.statics.getCommentsByRevisionId = function(id) {
return this.find({ revision: id }).sort({ createdAt: -1 });
};
commentSchema.statics.countCommentByPageId = function(page) {
const self = this;
return new Promise(((resolve, reject) => {
self.count({ page }, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
}));
};
commentSchema.statics.removeCommentsByPageId = function(pageId) {
const Comment = this;
return new Promise(((resolve, reject) => {
Comment.remove({ page: pageId }, (err, done) => {
if (err) {
return reject(err);
}
resolve(done);
});
}));
};
commentSchema.methods.removeWithReplies = async function() {
const Comment = crowi.model('Comment');
return Comment.remove({
$or: (
[{ replyTo: this._id }, { _id: this._id }]),
});
};
/**
* post save hook
*/
commentSchema.post('save', (savedComment) => {
const Page = crowi.model('Page');
Page.updateCommentCount(savedComment.page)
.then((page) => {
debug('CommentCount Updated', page);
})
.catch(() => {
});
});
return mongoose.model('Comment', commentSchema);
};