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

创建直播间


控制器:app/controller/api/live.js

js
	// 引入模块
	const md5 = require('md5');

	// 创建直播间
    async save() {
        let { ctx, app } = this;
        let user_id = ctx.authUser.id;
        // 参数验证
        ctx.validate({
            title: {
                type: 'string',
                required: true,
                desc: '直播间标题'
            },
            cover: {
                type: 'string',
                required: true,
                desc: '直播间封面'
            }
        });

        let {
            title, cover
        } = ctx.request.body;

        // 生成唯一key
        let key = ctx.randomString(20);

        // 直接创建
        let res = await app.model.Live.create({
            title,
            cover,
            user_id,
            key,
        });

        // 生成签名
        let sign = this.sign(key)

        ctx.apiSuccess({
            data: res,
            sign
        });
    }
	
	// 生成签名
    sign(key) {
        let { ctx, app } = this;
        const secret = app.config.mediaServer.auth.secret
        const expire = parseInt((Date.now() + 100000000) / 1000);
        const hashValue = md5(`/live/${key}-${expire}-${secret}`);
        return `${expire}-${hashValue}`
    }

扩展:app/extend/context.js

js
randomString(length) {
       const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
       var result = '';
       for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
       return result;
   },

路由:app/router.js

js
// 创建直播间
router.post("/api/live/create", controller.api.live.save);