在 Egg 框架中编写用户收藏的接口,可以按照以下步骤进行:
1.在 app/controller 目录下创建对应的控制器文件,例如 app/controller/favorite.js
。
在控制器文件中编写用户收藏的方法,可以参考以下示例代码:
'use strict';
const Controller = require('egg').Controller;
class FavoriteController extends Controller {
async create() {
const { ctx } = this;
const { userId, goodsId } = ctx.request.body;
const result = await ctx.service.favorite.create(userId, goodsId);
ctx.body = result;
}
async destroy() {
const { ctx } = this;
const { userId, goodsId } = ctx.request.body;
const result = await ctx.service.favorite.destroy(userId, goodsId);
ctx.body = result;
}
async index() {
const { ctx } = this;
const { userId } = ctx.query;
const result = await ctx.service.favorite.list(userId);
ctx.body = result;
}
}
module.exports = FavoriteController;
上述代码中,create
方法接收客户端传递过来的用户 ID 和商品 ID,然后调用对应的服务层方法进行用户收藏操作,并将操作结果返回给客户端。destroy
方法接收客户端传递过来的用户 ID 和商品 ID,然后调用对应的服务层方法进行用户取消收藏操作,并将操作结果返回给客户端。index
方法接收客户端传递过来的用户 ID,然后调用对应的服务层方法获取用户收藏列表,并将列表返回给客户端。
2.在 app/router.js 文件中添加对应的路由规则,例如:
'use strict';
module.exports = app => {
const { router, controller } = app;
router.post('/api/favorites', controller.favorite.create);
router.delete('/api/favorites', controller.favorite.destroy);
router.get('/api/favorites', controller.favorite.index);
};
上述代码中,/api/favorites
是客户端请求用户收藏接口的 URL,对应的控制器方法是 controller.favorite.create
、controller.favorite.destroy
和 controller.favorite.index
。
3.在 app/service 目录下创建对应的服务层文件,例如 app/service/favorite.js
。
在服务层文件中编写用户收藏的方法,可以参考以下示例代码:
'use strict';
const Service = require('egg').Service;
class FavoriteService extends Service {
async create(userId, goodsId) {
const { ctx } = this;
const result = await ctx.model.Favorite.create({ userId, goodsId });
return result;
}
async destroy(userId, goodsId) {
const { ctx } = this;
const result = await ctx.model.Favorite.destroy({ where: { userId, goodsId } });
return result;
}
async list(userId) {
const { ctx } = this;
const result = await ctx.model.Favorite.findAll({ where: { userId } });
return result;
}
}
module.exports = FavoriteService;
上述代码中,create
方法接收客户端传递过来的用户 ID 和商品 ID,然后使用 Sequelize 提供的 create
方法进行用户收藏操作,并将操作结果返回给控制器方法。destroy
方法删除指定的用户收藏记录。list
方法用于获取用户收藏列表。