list-params-process.js 2.15 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',
    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'
};

/**
 * 获取标准参数
 */
const getParams = (url) => {
    let params = [];
    let paramStringRaw = _.last(_.split(url, '/'));

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

        _.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
 */
const generatePathUrl = (queryParams) => {
    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}/list${pathUrl}`;
};

module.exports = {
    getParams,
    generatePathUrl
};