Skip to content
关注公众号,获取新课通知

视频详情


控制器:app/controller/video.js

js
	async read() {
        let { ctx, service, app } = this;
        let currentUser = ctx.authUser;

        ctx.validate({
            id: {
                type: "int",
                required: true,
                desc: "作品ID"
            },
        });

        let { id } = ctx.params;

        let video = await app.model.Video.findOne({
            where: {
                id
            },
            include: [{
                model: app.model.VideoDetail
            }, {
                model: app.model.User,
                attributes: ['id', 'username', 'nickname', 'avatar']
            }]
        });

        let hot = await this.hot()

        // 是否已收藏
        let fava = false
        // 是否关注
        let follow = false
        if (currentUser) {
            fava = !!(await app.model.Fava.findOne({
                where: {
                    video_id: video.id,
                    user_id: currentUser.id
                }
            }))

            follow = await service.user.isFollow(currentUser.id, video.user_id);
        }

        ctx.apiSuccess({
            video,
            hot,
            fava,
            follow
        });
    }
	
	// 热门视频
    async hot() {
        let { ctx, app } = this;

        let rows = await app.model.Video.findAll({
            order: [
                ['id', 'DESC'],
                ['play_count', 'DESC']
            ],
            limit: 5
        });

        return rows
    }

服务:app/service/user.js

js
// 当前用户是否关注某用户
   async isFollow(user_id, follow_id) {
       return !!(await this.app.model.Follow.findOne({
           where: {
               user_id,
               follow_id
           }
       }));
   }

中间件:app/middleware/getuser.js

js
module.exports = (option, app) => {
  return async (ctx, next) => {
    //1. 获取 header 头token
    let token = ctx.header.token || ctx.query.token;
    if (token) {
      let user = {};
      try {
        user = app.jwt.verify(token, app.config.jwt.secret);
      } catch (error) {
        console.log(error);
      }
      //3. 判断当前用户是否登录
      if (user && user.id) {
        let t = await ctx.service.cache.get("user_" + user.id);
        if (t && t === token) {
          user = await app.model.User.findByPk(user.id);
          ctx.authUser = user;
        }
      }
    }
    await next();
  };
};

配置:config/config.default.js

js
config.middleware = [
  // ...
  "getuser",
  // ...
];

路由:app/router.js

js
// 查看视频详情
router.get("/video_read/:id", controller.video.read);