全栈项目|小书架|服务器端-NodeJS+Koa2 实现评论功能

评论功能分析

在这里插入图片描述

上图可以看出评论功能主要实现了:评论的发布、评论列表的展示。
在不考虑子评论以及图片评论的场景下,评论功能主要有以下两个接口:

  • 发布评论
  • 获取评论列表(考虑分页)

评论 Model 的建立

结合上图通过分析可以看出一条评论信息主要包含有:

  • 用户 id
  • 用户名
  • 用户头像
  • 评论信息
  • 书籍 id
  • 书籍名称(可选)

那么根据以上的分析,我们的Model设计如下:

Comment.init({
    cmid: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    uid: {
        type: Sequelize.STRING,
    },
    uname: Sequelize.STRING,
    ucontent: Sequelize.STRING,
    bkname: Sequelize.STRING,
    bkid: Sequelize.INTEGER,
    uavatar: {
        type: Sequelize.STRING,
    }
}, {
    sequelize,
    tableName: 'comment'
})

通过Model生成的comment表格最终如下:

comment表格

发布评论

创建了Model之后下一步就是将评论数据提交到服务器,而评论的提交需要用户已经登录,如果未登录是不能发表评论的。这里使用的校验还是之前提到的Auth中间件,通过该中间件去校验用户是否登录。

发布评论的路由如下:

router.post('/write', new Auth().m, async ctx => {
    const v = await new BookIdValidator().validate(ctx)
    const comment = new Comment()
    ctx.body = await comment.addBookComment(v.get('body.commentInfo'))
})

addBookComment方法的处理就是将用户上传的表单中的数据保存到数据库。

async addBookComment(commentInfo) {
        let mCommentInfo = JSON.parse(commentInfo)
        try {
            let comment =  await Comment.create({
                uid: mCommentInfo.userid,
                uname: mCommentInfo.username,
                ucontent: mCommentInfo.conment,
                bkname: mCommentInfo.bookname,
                bkid: mCommentInfo.bookid,
                uavatar: mCommentInfo.avatar
            })
            console.log(comment)
            if (!comment){
                throw new global.errs.NotFound('创建评论失败',-1)
            }
            return comment
          } catch (err) {
            // print the error details
            console.log(err);
          }
        
    }

评论列表

当发布评论之后需要用户返回书籍详情页面展示已发布的评论信息。

获取评论列表的路由如下:

router.get('/', new Auth().m, async ctx => {
    const v = await new BkIdValidator().validate(ctx)
    const comment = new Comment()
    ctx.body = await comment.geCommentByBookId(v.get('query.bkid'))
})

这里的评论列表接口也是使用了Auth中间件去检验用户是否登录。通过上面伪代码可以是通过书籍id去查询书籍的评论列表,那么geCommentByBookId的代码如下:

 async geCommentByBookId(bkid) {
        const comments =await Comment.findAll({
            where: {
                bkid
            }
        })
        if (comments.length <= 0) {
            throw new global.errs.NotFound("还没有评论信息哟~", NotFound.COMMENT_EMPTY)
        }
        return comments
    }

这里的通过书籍id查询数据库中所有的评论信息,如果有评论信息则返回评论数据,没有评论数据则返回错误的提示信息。

ps: 暂不实现分页功能,分页功能在介绍搜索功能时会介绍。

以上就是本次的介绍。


扫码关注公众号,轻撩即可。

在这里插入图片描述

发布了180 篇原创文章 · 获赞 76 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/ITxiaodong/article/details/103385003