在本节课程中,我们将学习如何使用 Koa 框架编写交互模块,并实现添加视频评论的功能。我们将分为以下几个步骤进行讲解:添加路由、定义数据模型、编写控制器、以及使用 Postman 进行验证。
添加路由
首先,我们需要在路由中添加一个处理视频评论的端点。在 router 中添加如下代码:
// 交互模块
router.post('/video/comment/:videoId', verifyToken(true), videoController.createComment)
这个路由会调用 videoController 中的 createComment 方法,并传递视频 ID 和评论内容。
定义数据模型
接下来,我们需要定义一个 videoCommentModel 来描述评论的数据结构。这个模型将包括评论内容、视频 ID 和用户 ID。
const mongoose = require('mongoose')
const baseModel = require('./baseModel')
const videoCommentSchema = new mongoose.Schema({
content: {
type: String,
required: true
},
video: {
type: mongoose.ObjectId,
required: true,
ref: 'Video'
},
user: {
type: mongoose.ObjectId,
required: true,
ref: 'User'
},
...baseModel
})
module.exports = videoCommentSchema
编写控制器
控制器负责处理实际的业务逻辑。在 videoController 中添加 createComment 方法,用于处理评论的创建:
// 添加视频评论
module.exports.createComment = async ctx => {
const videoId = ctx.request.params.videoId
const { content } = ctx.request.body
const userId = ctx.user.userInfo._id
const videoInfo = await Video.findById(videoId)
if (videoInfo) {
let commentModel = new VideoComment({
content,
video: videoId,
user: userId
})
let dbBack = await commentModel.save()
if (dbBack) {
videoInfo.commentCount++
await videoInfo.save()
ctx.body = { msg: "评论成功" }
} else {
ctx.throw(501, '评论失败')
}
} else {
ctx.throw(404, '视频不存在')
}
}
这个方法首先检查视频是否存在,然后创建并保存评论,最后更新视频的评论计数。
使用 Postman 进行验证
在完成上述步骤后,我们可以使用 Postman 来测试我们的 API。打开 Postman,设置请求类型为 POST,并将 URL 设置为 /video/comment/:videoId,然后在 Body 中添加评论内容并发送请求。
总结
通过本次学习,我们掌握了如何在 Koa 中添加路由、定义数据模型、编写控制器以及使用 Postman 进行验证的方法。使用这些技能,我们可以轻松地为应用添加各种交互功能。Koa 的简洁和灵活性使得开发和维护更加高效,是构建现代 Web 应用的强大工具。