yas-process.js 2.24 KB
const _ = require('lodash');
const logger = global.yoho.logger;

const getPname = (req) => {
    let userAgent = req.get('User-Agent');
    let isiOS = /\(i[^;]+;( U;)? CPU.+Mac OS X/i.test(userAgent);
    let isAndroid = /Android/i.test(userAgent);
    let pName = '';


    if (isiOS) {
        pName = 'iFP_SalesPromotion';
    }

    if (isAndroid) {
        pName = 'aFP_SalesPromotion';
    }

    return pName;
};

/**
 * openbyStr 处理
 */
const _handleOpenbyParams = (params) => {
    const paramsKeyStr = 'openby:yohobuy=';

    let openByStrNew = '';
    let openByParamObj = {};

    if (_.isString(params.openbyStr)) {
        openByStrNew = _.replace(params.openbyStr, paramsKeyStr, '');
    } else {
        return params.openbyStr;
    }

    if (_.isString(openByStrNew)) {
        try {
            openByParamObj = JSON.parse(openByStrNew);
        } catch (error) {
            logger.info(`openbyStr json parse err, raw string is ${openByStrNew}`);
        }
    } else {
        return params.openbyStr;
    }

    if (!_.isEmpty(openByParamObj) && _.has(openByParamObj, 'params')) {
        openByParamObj.params.from_page_name = params.fromPageName;
        openByParamObj.params.from_page_param = params.fromPageParam;

        openByStrNew = `${paramsKeyStr}${JSON.stringify(openByParamObj)}`;
    }

    return openByStrNew;
};

/**
 * 配置的商品添加参数
 */
const addParamsToGoodsHref = (params) => {
    let finalHref = '';
    let paramsSplitArr = params.href.split('?') || [];
    let paramsArr = _.has(paramsSplitArr, '1') ? paramsSplitArr[1].split('&') : [];
    let paramsArrNew = [];
    let paramsStrNew = '';

    paramsArrNew = _.map(paramsArr, param => {
        if (_.isString(param) && param.indexOf('openby:yohobuy=') !== -1) {
            param = _handleOpenbyParams({
                openbyStr: param,
                fromPageName: params.fromPageName,
                fromPageParam: params.fromPageParam
            });
        }

        return param;
    });

    if (paramsArrNew.length) {
        paramsStrNew = paramsArrNew.join('&');
        finalHref = `${paramsSplitArr[0]}?${paramsStrNew}`;
    } else {
        finalHref = params.href;
    }

    return finalHref;
};

module.exports = {
    getPname,
    addParamsToGoodsHref
};