egg编写管理员回复评论的接口
1.首先,我们需要定义路由,创建一个新的 reply
路由:
// app/router.jsmodule.exports = app => {const { router, controller } = app;// 管理员回复评论router.post('/api/reply', controller.reply.create);
};
2.然后,在 controller
目录下创建 reply.js
文件,并添加 create
方法用于创建新的回复:
// app/controller/reply.jsconst Controller = require('egg').Controller;class ReplyController extends Controller {async create() {const { ctx, service } = this;const { commentId, content } = ctx.request.body;// 获取当前管理员的信息const adminId = ctx.session.adminId;// 检查管理员是否已登录if (!adminId) {ctx.status = 401;ctx.body = {message: '请先登录',};return;}// 创建新的回复const reply = await service.reply.create({adminId,commentId,content,});ctx.body = {data: reply,};}
}module.exports = ReplyController;
在上面的示例代码中,我们首先获取 commentId
和 content
参数,然后通过 ctx.session.adminId
获取当前管理员的 ID,以确保管理员已经登录。如果管理员未登录,则返回 401 状态码并提示用户登录。
3.接下来,我们使用 service.reply.create()
方法创建新的回复,并将其返回给客户端。该方法会在 service
目录下的 reply.js
文件中实现。
我们需要在 service
目录下的 reply.js
文件中实现 create
方法:
// app/service/reply.jsconst Service = require('egg').Service;class ReplyService extends Service {async create(data) {const { app } = this;const { commentId, adminId, content } = data;// 检查评论是否存在const comment = await app.model.Comment.findByPk(commentId);if (!comment) {throw new Error('评论不存在');}// 创建新的回复const reply = await app.model.Reply.create({adminId,commentId,content,});return reply;}
}module.exports = ReplyService;
在上面的示例代码中,我们首先检查 commentId
参数对应的评论是否存在。如果评论不存在,则抛出一个异常。否则,我们创建一个新的回复,并将其返回给控制器。
到此为止,我们已经完成了管理员回复评论的接口开发。在客户端调用该接口时,需要传入 commentId
和 content
参数,并且必须使用管理员的身份进行登录。