评论模块
评论的话,门户可以添加,可以删除自己的,可以获取到评论列表,根据文章获取此文章的评论列表。
添加评论
发表评论接口
@PostMapping
public ResponseResult postComment(@RequestBody Comment comment) {
return commentService.postComment(comment);
}
实现接口
/**
* 发表评论
*
* @param comment 评论
* @return
*/
@Override
public ResponseResult postComment(Comment comment) {
//检查用户是否有登录
SobUser sobUser = userService.checkSobUser();
if (sobUser == null) {
return ResponseResult.ACCOUNT_NOT_LOGIN();
}
//检查内容
String articleId = comment.getArticleId();
if (TextUtils.isEmpty(articleId)) {
return ResponseResult.FAILED("文章ID不可以为空.");
}
ArticleNoContent article = articleNoContentDao.findOneById(articleId);
if (article == null) {
return ResponseResult.FAILED("文章不存在.");
}
String content = comment.getContent();
if (TextUtils.isEmpty(content)) {
return ResponseResult.FAILED("评论内容不可以为空.");
}
//补全内容
comment.setId(idWorker.nextId() + "");
comment.setUpdateTime(new Date());
comment.setCreateTime(new Date());
comment.setUserAvatar(sobUser.getAvatar());
comment.setUserName(sobUser.getUserName());
comment.setUserId(sobUser.getId());
//保存入库
commentDao.save(comment);
//返回结果
return ResponseResult.SUCCESS("评论成功");
}
删除评论
评论只能删除自己的,如果不是自己的话不可以删除。前端在编写的时候,判断一下ID跟当前用户的ID是否一样,如果一样,才显示删除按钮,不一样,则不显示。
接口
@DeleteMapping("/{commentId}")
public ResponseResult deleteComment(@PathVariable("commentId") String commentId) {
return commentService.deleteCommentById(commentId);
}
获取评论列表
根据文章获取对应的评论列表
权限:所有用户/非登录访客
@GetMapping("/list/{articleId}/{page}/{size}")
public ResponseResult listComments(@PathVariable("articleId") String articleId, @PathVariable("page") int page,@PathVariable("size") int size) {
return commentService.listCommentByArticleId(articleId, page, size);
}
实现
/**
* 获取文章的评论
* 评论的排序策略:
* 最基本的就按时间排序-->升序和降序-->先发表的在前面或者后发表的在前面
* <p>
* 置顶的:一定在前最前面
* <p>
* 后发表的:前单位时间内会排在前面,过了此单位时间,会按点赞量和发表时间进行排序
*
* @param articleId
* @param page
* @param size
* @return
*/
@Override
public ResponseResult listCommentByArticleId(String articleId, int page, int size) {
page = checkPage(page);
size = checkSize(size);
Sort sort = new Sort(Sort.Direction.DESC, "state", "createTime");
Pageable pageable = PageRequest.of(page - 1, size, sort);
Page<Comment> all = commentDao.findAll(pageable);
return ResponseResult.SUCCESS("评论列表获取成功.").setData(all);
}