list-params-process.js 2.2 KB
const _ = require('lodash');
const config = global.yoho.config;

/**
 * 参数列表
 */
const PARAMMAP = {
    ag: 'age_level',
    bd: 'brand',
    cc: 'coupon_code',
    cd: 'coupon_id',
    ci: 'category_id',
    cl: 'color',
    cn: 'channel',
    fp: 'filter_poolId',
    gd: 'gender',
    id: 'id',
    ld: 'limited',
    lt: 'limit',
    mi: 'misort',
    ms: 'msort',
    nb: 'navBar',
    nw: 'new',
    od: 'order',
    ol: 'outlets',
    pc: 'price',
    pd: 'p_d',
    pg: 'page',
    pm: 'promotion',
    pp: 'productPool',
    sd: 'standard',
    se: 'shelveTime',
    sf: 'specialoffer',
    sh: 'shop_id',
    si: 'specialsale_id',
    so: 'sort',
    sp: 'saleType',
    st: 'style',
    sz: 'size',
    tp: 'type'
};

/**
 * 解析 pathParams 获取标准参数
 */
const getParams = (pathParams) => {
    let params = {};

    if (pathParams) {
        let paramsRaw = _.split(pathParams, '-');

        _.forEach(paramsRaw, paramRaw => {
            let keyRaw = paramRaw.substr(0, 2);
            let valueRaw = _.chain(paramRaw)
                .replace(keyRaw, '')
                .replace('__', '-')
                .value();

            if (PARAMMAP[keyRaw]) {
                params[PARAMMAP[keyRaw]] = valueRaw;
            }
        });
    }

    return _.toPlainObject(params);
};

/**
 * 生成链接
 * @param {参数} queryParams
 * @param {path} path
 */
const generatePathUrl = (queryParams, path) => {
    let pathUrlParams = []; // 可以找到对应关系的参数
    let noFindParams = []; // 没有找到对应关系的
    let pathUrl = '';

    _.forEach(queryParams, (value, key) => {
        let paramKey = _.findKey(PARAMMAP, o => {
            return o === key;
        });

        if (paramKey) {
            pathUrlParams.push(paramKey + value + '');
        } else {
            noFindParams.push(key + '=' + value);
        }
    });

    pathUrl = pathUrlParams.length ? pathUrlParams.join('-') : '';
    pathUrl += noFindParams.length ? '?' + noFindParams.join('&') : '';
    pathUrl = (pathUrl && !_.startsWith(pathUrl, '?')) ? `/${pathUrl}` : pathUrl;

    return `${config.subDomains.default}/${_.trim(path, '/') || 'list'}${pathUrl}`;
};

module.exports = {
    getParams,
    generatePathUrl
};