rewrite.js 2.06 KB
/**
 * 路由重写
 * @author: chenfeng<feng.chen@yoho.cn>
 * @date: 2017/2/20
 */
'use strict';

const typeLib = require('../../config/type-lib');
const _ = require('lodash');

const resolve = (req, res, next) => {
    let path = req.params[0],
        params = {
            channel: req.yoho.channel
        };

    if (!path) {
        return next();
    }
    let conditions = path.replace('.html', '').split('-');

    _.each(conditions, condition => {
        if (typeLib.channels[condition]) {
            params.channel = condition;
        } else if (condition.indexOf('_') >= 0) {
            let item = condition.split('_');

            if (item.length === 2) {
                params[item[0]] = item[1];
            }
        } else if (condition >= 0) {
            params.id = _.parseInt(condition);
        }
    });
    req.yoho.channel = params.channel;
    res.locals.channel = params.channel;
    res.locals.pageChannel = { [params.channel]: true };
    res.locals.setChannel = true;
    Object.assign(req.query, params);
    next();
};

const channel = (req, res, next) => {
    let channelName;

    if (req.query.channel) {
        if (req.query.channel >= 0) {
            channelName = typeLib.channelNames[req.query.channel];
        } else if (typeLib.channels[req.query.channel]) {
            channelName = req.query.channel;
        }
    } else if (req.query.gender) {
        let gender = req.query.gender;

        switch (gender) {
            case typeLib.gender.boys:
                gender = 1;
                break;
            case typeLib.gender.girls:
                gender = 2;
                break;
            case typeLib.gender.kids:
                gender = 3;
                break;
            case typeLib.gender.lifestyle:
                gender = 4;
                break;
        }
        channelName = typeLib.channelNames[gender];
    }
    channelName = channelName || req.yoho.channel;
    req.yoho.channel = channelName;
    delete req.query.channel;
    delete req.query.gender;
    next();
};

module.exports = {
    resolve,
    channel
};