评论文章接口需要注意地方
- 当前用户状态不是1的情况下,不允许评论文章
- 根据文章id,查询文章是否存在
- 文章存在情况下,文章是发布或者top状态才能被评论
以下是修改后的代码
public ResponseResult addComment(Comment comment) {
//登录?
SobUser sobUser = userService.checkSobUser();
if (sobUser == null) {
return ResponseResult.ACCOUNT_NOT_LOGIN();
}
//用户状态是否可用,可能被禁用(删除)
SobUser dbUser = userDao.findOneById(sobUser.getId());
if (Constants.User.DEL_STATE.equals(dbUser.getState())) {
return ResponseResult.FAILED("你的账户被禁言");
}
//文章id是否存在
if (TextUtils.isEmpty(comment.getArticleId())) {
return ResponseResult.FAILED("文章id不能为空");
}
//内容是否空
String content = comment.getContent();
if (TextUtils.isEmpty(content)) {
return ResponseResult.FAILED("评论内容不能为空");
}
//文章是否存在
ArticleNoContent dbArticle = articleAdminDao.findOneById(comment.getArticleId());
if (dbArticle == null) {
return ResponseResult.FAILED("文章不存在");
}
//文章是否发布,或者置顶,如果不是,就不能评论
if (!Constants.Article.STATE_TOP.equals(dbArticle.getState())
&& !Constants.Article.STATE_PUBLISH.equals(dbArticle.getState())) {
return ResponseResult.FAILED("不能评论未发布的文章");
}
//补全信息,保存入库
comment.setId(String.valueOf(idWorker.nextId()));
comment.setCreateTime(new Date());
comment.setUpdateTime(new Date());
comment.setState("1");
comment.setContent(content.trim());
comment.setUser_id(sobUser.getId());
comment.setUser_name(sobUser.getUserName());
comment.setUser_avatar(sobUser.getAvatar());
//save to db
commentDao.save(comment);
return ResponseResult.SUCCESS("评论成功");
}
查询某一文章的评论
- 先查询文章是否存在,如果不存在,就没有评论
- 可以根据文章的状态,是否发布,来查询评论(可选)
- 视频中,没有使用文章id来查询,直接分页返回了数据,这个时候,查询的是全部评论。不是对应文章的评论,估计在后期会发现这个问题
/**
* 查询某个文章的id
* @param articleId 目标文章的id
* @return
*/
@Override
public ResponseResult listCommentsByArticleId(String articleId) {
//检查文章id,是否空
if (TextUtils.isEmpty(articleId)) {
return ResponseResult.FAILED("评论id不能为空");
}
//检查id对应的文章,是否存在
ArticleNoContent dbArticle = articleAdminDao.findOneById(articleId);
if (dbArticle == null) {
return ResponseResult.FAILED("文章不存在");
}
//评论表中,根据文章id,全部查询。因为评论不多,不需要分页
List<Comment> allByArticleId = commentDao.findAllByArticleId(articleId);
return ResponseResult.SUCCESS("文章评论获取成功").setData(allByArticleId);
}