filters.js 2.56 KB
/**
 *   格式化 后台 返回的 filters 数据
 *   @author chenxuan <xuan.chen@yoho.cn>
 */
'use strict';

const _ = require('lodash');

/**
 *   处理 以风格的数据
 *   [
 *      {filter_attribute: value}
 *   ]
 *
 *   处理结果
 *   [
 *     {attribute:value,......}
 *   ]
 *
 */
let verboseAttrHandler = (filterField, dataArr) => {
    let result = [];
    let re = new RegExp(`^${filterField}_`);

    dataArr.forEach(obj => {
        let item = {};
        let keys = Object.keys(obj);

        keys.forEach(key=>{
            let newKey = key.replace(re, '');

            item[newKey] = obj[key];
        });

        result.push(item);
    });

    return result;
};

/*
 *   处理 以下风格:
 *    {
       "340,99999": "¥339以上",
        "0,149": "¥0-149",
        "150,179": "¥150-179",
        "180,339": "¥180-339"
 *    },
 *
 *    处理结果:
 *    [
 *       {id: '0,149', value: '0,149', name: '¥0-149'},
 *       {id: '150, 179', value: '150,179', name: '¥150-179'}
 *          .....
 *    ]
 *    按照字符串顺序
 */
let keyIdHandler = (filterField, obj) => {
    const result = [];
    const keys = Object.keys(obj);

    keys.sort();
    keys.forEach(key=> {
        let item = {};

        item.id = key;

        let t = obj[key];
        let isObject = Object.prototype.toString.apply(t) === '[object Object]';

        if (isObject) {
            item = Object.assign(item, t);
        } else {
            item.name = t;
        }

        result.push(item);
    });

    return result;
};

function prettyFilter(filters) {
    let keys = _.keys(filters);

    _.forEach(keys, key => {
        let process;

        // 相同规律的 使用 相同的处理规则
        switch (key) {
            case 'color':
            case 'size':
            case 'brand':
                process = verboseAttrHandler;
                break;

            case 'gender':
            case 'priceRange':
            case 'discount':
                process = keyIdHandler;
                break;

            // 其他不做处理
            default:
                process = _.noop;
        }
        filters[key] = process(key, filters[key]) || filters[key];
    });
}

module.exports = prettyFilter;


/*
filter Object经过 prettyFilter, camelCase 后的 数据格式:
{
    color: [{id,name,value, code}],
    gender: [{id,name}],
    size: [id,name],
    discount: [{id,name,count}],
    priceRange: [{id, name}],
    ageLevel: [{id,name, productCount}]
    brand: [{id, name,domain,alif,ico,keyword,hotKeyword,isHot, nameEn, nameCn}]
    groupSort,
}
*/