mobile-refer.js 1.84 KB
/**
 * page cache 前端js跳转url中间件
 */
'use strict';

const _ = require('lodash');
const queryString = require('querystring');

const ptm = {
    // 首页
    '/': '',
    '/woman': '/girls',
    '/kids': '/kids',
    '/lifestyle': '/lifestyle',

    // 登录注册
    '/signin.html': '/signin.htm',
    '/reg.html': '/passport/reg/index',
    '/passport/back/index': '/passport/back/mobile',

    // 列表
    '/product/list/new': '/product/new',

    // 品牌列表
    '/brands': '/brands',

    // 领券中心
    '/coupon/index': '/coupon/floor?title=领券中心&code=b78b32ed81b18dde8ac84fd33602b88b'
};

const notNeedReferMap = [
    /^\/special\/(\d+)_/
];

const genderMap = {
    boys: '1,3',
    girls: '2,3',
    kids: '1,2,3',
    lifestyle: '1,2,3'
};

module.exports = () => {
    return (req, res, next) => {
        let domain = 'm.yohobuy.com';
        let proRegNew = /^\/product\/([\d]+).html(.*)/;

        if (!req.xhr) {
            let url = _.head(_.split(req.url, '?'));
            let data = {};

            if (ptm.hasOwnProperty(url)) {
                data.mobileRefer = `//${domain}${ptm[url]}`;
            } else if (url === '/guang/') {
                req.query.gender = genderMap[req.query.channel];
                _.unset(req.query, 'channel');
                data.mobileRefer = `//${domain}/guang?${queryString.stringify(req.query)}`;
            } else if (proRegNew.test(url)) {
                data.mobileRefer = url.replace(proRegNew, `//${domain}/product/$1.html$2`);
            }

            // 设置不需要跳转页面
            req.noRefer = _.find(notNeedReferMap, rule => {
                return (_.isRegExp(rule) && rule.test(req.url) ||
                    (_.isString(rule) && _.isEqual(req.url, rule)));
            });

            Object.assign(res.locals, data);
        }
        next();
    };
};