helpers.js 2.08 KB
/*
 * @Author: Targaryen
 * @Date:   2016-05-10 10:11:34
 * @Last Modified by:   Targaryen
 * @Last Modified time: 2016-05-12 11:25:53
 */
/* -----------------------------------------
 * 实现 PHP 的 Helpers 函数
 * -----------------------------------------
 */

'use strict';

const SUB_DOMAIN = '.yohobuy.com';
const SITE_MAIN = 'http://www.yohobuy.com';
const _ = require('lodash');

class HELPERS {

    /**
     * 构建网站的URL
     * @param uri String
     * @param param Array
     * @param module String
     */
    url(uri, param, module) {
        let url = '';

        if (module === null) {
            module = 'index';
        }
        switch (module) {
            case 'default':
                url = 'http://m.yohobuy.com';
                break;
            case 'guang':
                url = 'http://guang' + SUB_DOMAIN;
                break;
            case 'list':
                url = 'http://list' + SUB_DOMAIN;
                break;
            case 'search':
                url = 'http://search' + SUB_DOMAIN;
                break;
            case 'index':
                url = SITE_MAIN;
                break;
            case '':
                break;
            case undefined:
                break;
            default:
                url = 'http://' + module + SUB_DOMAIN;
                break;
        }

        url += uri;
        if (param !== null && param !== undefined) {
            url += '?';
            _.forEach(param, function(value, key) {
                url += (key + '=' + value + '&');
            });
        }
        if (url.substr(-1, 1) === '&') {
            return url.substr(0, url.length - 1);
        } else {
            return url;
        }

    }

    /**
     * 根据尺寸获得图片url
     * @param uri String
     * @param param Array
     * @param module String
     */
    getImageUrl(url, width, height, mode) {
        if (mode === null) {
            mode = 2;
        }
        return url.replace(/{width}/g, width)
            .replace(/{height}/g, height)
            .replace(/{mode}/g, mode);
    }
}

module.exports = HELPERS;