63 lines
2.0 KiB
JavaScript
63 lines
2.0 KiB
JavaScript
var router = require('express').Router();
|
|
var mongoose = require('mongoose');
|
|
var Comment = mongoose.model('Comment');
|
|
var User = mongoose.model('User');
|
|
var auth = require('../auth');
|
|
|
|
// return an article's comments
|
|
router.get('/:article/comments', auth.optional, function (req, res, next) {
|
|
Promise.resolve(req.payload ? User.findById(req.payload.id) : null).then(function (user) {
|
|
return req.article.populate({
|
|
path: 'comments',
|
|
populate: {
|
|
path: 'author'
|
|
},
|
|
options: {
|
|
sort: {
|
|
createdAt: 'desc'
|
|
}
|
|
}
|
|
}).then(function (article) {
|
|
return res.json({
|
|
comments: req.article.comments.map(function (comment) {
|
|
return comment.toJSONFor(user);
|
|
})
|
|
});
|
|
});
|
|
}).catch(next);
|
|
});
|
|
|
|
// create a new comment
|
|
router.post('/:article/comments', auth.required, function (req, res, next) {
|
|
User.findById(req.payload.id).then(function (user) {
|
|
if (!user) {
|
|
return res.sendStatus(401);
|
|
}
|
|
var comment = new Comment(req.body.comment);
|
|
comment.article = req.article;
|
|
comment.author = user;
|
|
|
|
return comment.save().then(function () {
|
|
req.article.comments.push(comment);
|
|
|
|
return req.article.save().then(function (article) {
|
|
res.json({ comment: comment.toJSONFor(user) });
|
|
});
|
|
});
|
|
}).catch(next);
|
|
});
|
|
|
|
router.delete('/:article/comments/:comment', auth.required, function (req, res, next) {
|
|
if (req.comment.author.toString() === req.payload.id.toString()) {
|
|
req.article.comments.remove(req.comment._id);
|
|
req.article.save()
|
|
.then(Comment.find({ _id: req.comment._id }).remove().exec())
|
|
.then(function () {
|
|
res.sendStatus(204);
|
|
});
|
|
} else {
|
|
res.sendStatus(403);
|
|
}
|
|
});
|
|
|
|
module.exports = router; |