list-params-process.js 2.17 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',
    nw: 'new',
    od: 'order',
    ol: 'outlets',
    pc: 'price',
    pd: 'p_d',
    pg: 'page',
    pm: 'promotion',
    pp: 'productPool',
    qr: 'query',
    sd: 'standard',
    se: 'shelveTime',
    sf: 'specialoffer',
    sh: 'shop_id',
    si: 'specialsale_id',
    so: 'sort',
    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}/${path || 'list'}${pathUrl}`;
};

module.exports = {
    getParams,
    generatePathUrl
};