redpac.js 4.53 KB
/**
 * Created by qiujun on 2018/10/9.
 * 双11红包雨相关接口
 */

const INVALID_PARAMS = '参数错误';
const RedpacModel = require('../models/redpac');
const _sender = global.yoho.sender;

/**
 *
 * @param len 长度
 * @param radix 基数(chars取字符的长度,例如16,就是取前16个字符作为udid基础字符)
 * @returns {string}
 */
const getUdid = (len, radix) => {
    let chars = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
    let uuid = [], i;

    radix = radix || chars.length;

    if (len) {
        // Compact form
        for (i = 0; i < len; i++) {
            uuid[i] = chars[0 | Math.random() * radix];
        }
    } else {
        // rfc4122, version 4 form
        let r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
};

/**
 * 上报
 * @param type 0: packrain 1: turntable
 * @param tags 一些基础参数
 * @param fields 红包的金额
 * @param isFail 接口是否失败
 */
const sendMessage = (type, tags, fields, isFail) => {
    if (!_sender) {
        return;
    }
    const hostname = (require('os').hostname());
    let typeName = ['packrain', 'turntable'][type || 0];
    let initTags = {
        hostname,
        pid: process.pid || 0,
        app: global.yoho.config.appName,
        type: typeName
    };

    tags = Object.assign({}, initTags, tags);
    isFail = isFail ? 1 : 0;
    fields = Object.assign({}, fields);

    let mesurement = ['monitor_success_report', 'monitor_error_report'][isFail];

    try {
        _sender.addMessage({
            measurement: mesurement,
            tags,
            fields
        });
    } catch (e) {
        console.error(e);
    }
};

const redpac = {

    /**
     * 从接口获取红包的token
     * @param req
     * @param res
     */
    getRedpacToken(req, res) {
        let params = req.query;
        let udid = params.udid || getUdid(40, 16);
        let actSource = params.source || 1002;

        return req.ctx(RedpacModel).getRedpacToken(udid, actSource).then(result => {
            res.json(result);
        });
    },

    /**
     * 领取红包
     * @param req
     * @param res
     * @param next
     * @returns {Promise.<TResult>}
     */
    getRedpac(req, res, next) {
        let params = req.body;

        console.log(params);
        let uid = {
            toString: () => {
                return parseInt(params.uid, 10);
            },
            sessionKey: params.sessionKey,
            appVersion: params.appVersion,
            appSessionType: params.sessionType
        };
        let udid = params.udid || '';
        let redpacToken = params.token || '';
        let actSource = params.source || 1002;

        if (!params.udid || !params.uid || !params.token) {
            return res.json({
                code: 400,
                message: INVALID_PARAMS
            });
        }


        return req.ctx(RedpacModel).getRedpac(uid, udid, actSource, redpacToken).then(result => {
            if (result && result.data) {
                sendMessage(0, {}, {succeedTimes: result.data.amount || 0}, 0);
            } else {
                sendMessage(0, {}, {message: result.message || 'no result', stack: Object.assign({}, {code: result.code})}, 1);
            }

            return res.json(result);
        }).catch(e => {
            console.log('error:', e);
            sendMessage(0, {}, {message: e.message || 'interface error', stack: e}, 1);
            next();
        });
    },

    /**
     * 获取我的红包列表
     * @param req
     * @param res
     * @param next
     */
    getMyRedpac(req, res, next) {
        let params = req.query;
        let uid = {
            toString: () => {
                return parseInt(params.uid, 10);
            },
            sessionKey: params.sessionKey,
            appVersion: params.appVersion,
            appSessionType: params.sessionType
        };

        if (!params.uid) {
            return res.json({
                code: 400,
                message: INVALID_PARAMS
            });
        }

        return req.ctx(RedpacModel).getMyRedpac(uid).then(result => {
            return res.json(result);
        }).catch(next);
    }
};

module.exports = redpac;