egg编写用户收藏的接口

在 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.createcontroller.favorite.destroycontroller.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 方法用于获取用户收藏列表。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值