helpers.js 7.4 KB
/**
 * Handlebars helpers
 * bikai kai.bi@yoho.cn
 * 2016-05-10
 */
'use strict';
const querystring = require('querystring');
const _ = require('lodash');
const moment = require('moment');
const config = require('../config/common');

/**
 * 七牛图片路径处理
 * @param  {[string]} url
 * @param  {[string]} width
 * @param  {[string]} height
 * @param  {[string]} mode
 * @return {[string]}
 */
exports.image = (url, width, height, mode) => {
    mode = _.isNumber(mode) ? mode : 2;
    url = url || '';
    return url.replace(/{width}/g, width).replace(/{height}/g, height).replace(/{mode}/g, mode);
};

/**
 * 条件判断
 * @param  {[string]} v1
 * @param  {[string]} v2
 * @param  {[object]} options 上下文环境,一般不手动传
 * @return {[boolen]}
 */
exports.isEqual = (v1, v2, _options) => {
    if (_.isEqual(v1, v2)) {
        return _options.fn(this); // eslint-disable-line
    }

    return _options.inverse(this); // eslint-disable-line
};

/**
 * 站内地址格式化
 * @param  {[string]} uri 路径
 * @param  {[object]} qs 查询字符串
 * @param  {[string]} module 模块
 * @return {[string]}
 */
exports.urlFormat = (uri, qs, module) => {
    const subDomain = '.yohobuy.com';
    const subName = {
        default: config.siteUrl,
        guang: `//guang${subDomain}`,
        list: `//list${subDomain}`,
        search: `//search${subDomain}`,
        huodong: `//huodong${subDomain}`,
        activity: '//activity.yohobuy.com',
        index: config.siteUrl
    };
    let url;

    module = module || 'default';
    if (subName[module]) {
        url = subName[module];
    } else {
        url = `//${module}${subDomain}`; // 规则没匹配到就把模块当作子域名
    }

    url += uri;
    if (qs) {
        url += `?${querystring.stringify(qs)}`;
    }

    return url;
};

/**
 * 站内地址格式化
 * @param  {[string]} uri 路径
 * @param  {[object]} qs 查询字符串
 * @param  {[string]} module 模块
 * @return {[string]}
 */
exports.fakeUrlFormat = (uri, qs, module) => {
    const subDomain = 'http://localhost:6001';
    const subName = {
        default: subDomain,
        guang: `${subDomain}`,
        list: `${subDomain}`,
        search: `${subDomain}`,
        huodong: `${subDomain}`,
        index: subDomain
    };
    let url;

    module = module || 'default';
    if (subName[module]) {
        url = subName[module];
    } else {
        url = `//${module}${subDomain}`; // 规则没匹配到就把模块当作子域名
    }

    url += uri;
    if (qs) {
        url += `?${querystring.stringify(qs)}`;
    }

    return url;
};

/**
 * 大写转小写处理
 * @param  {[string]} str 转换字符
 */
exports.lowerCase = (str) => {
    str = str || '';
    return str.toLowerCase();
};

/**
 * 小写转大写处理
 * @param  {[string]} str 转换字符
 */
exports.upperCase = (str) => {
    str = str || '';
    return str.toUpperCase();
};

/**
 * 四舍五入
 * @param  {[type]} num 数字
 * @param  {[type]} precision 精度
 * @return {[type]}
 */
exports.round = (num, precision) => {
    precision = _.isNumber(precision) ? precision : 2;
    num = _.isInteger(num) ? (+num).toFixed(precision) : _.round(num, precision);
    return num;
};

/**
 * 时间格式化
 * @param format 格式化token @see{http://momentjs.cn/docs/#/displaying/format/}
 * @param date 日期或者数字
 * @return string
 *
 */
exports.dateFormat = (format, date) => {
    if (typeof format !== 'string' || typeof date === 'undefined') {
        return '';
    } else {
        if (date instanceof Date) {
            return moment(date).format(format);
        } else {
            const d = moment.unix(date);

            return moment(d).utc().format(format);
        }
    }
};

/**
 * 时间差格式化
 * @param {[string]} format 格式化字符串
 * @param {[number]} diff 相差值
 * @param {[string]} type diff时间类型 默认ms
 *
 *          Key                Shorthand
 *           years              y
 *           quarters           Q
 *           months             M
 *           weeks              w
 *           days               d
 *           hours              h
 *           minutes            m
 *           seconds            s
 *           milliseconds       ms
 *
 * @example
 *  let diff = 60 * 60 * 24 * (1.3) + 2;
 *
 *  let s = helpers.dateDiffFormat('{d}天{h}小时', diff, 's');
 *  >>> 1天7小时
 */
exports.dateDiffFormat = (format, diff, type) => {
    if (typeof format !== 'string' || typeof diff === 'undefined') {
        return '';
    } else {
        type = type || 'ms';
        const m = moment.duration(diff, type);

        format.match(/(\{.*?\})/g).forEach((s) => {
            format = format.replace(s, m.get(s.substring(1, s.length - 1)));
        });

        return format;
    }
};

/**
 * 验证邮箱是否合法
 *
 * @param string email
 * @return boolean
 */
exports.verifyEmail = (email) => {
    if (!email) {
        return false;
    }

    const emailRegExp = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

    return emailRegExp.test(email);
};

/**
 * 各国手机号规则
 */
function areaMobileVerify(phone, area) {
    area = area || '86';
    phone = phone.trim();

    let verify = {
        86: {
            name: '中国',
            match: /^1[3|4|5|8|7][0-9]{9}$/.test(phone)
        },
        852: {
            name: '中国香港',
            match: /^[9|6|5][0-9]{7}$/.test(phone)
        },
        853: {
            name: '中国澳门',
            match: /^[0-9]{8}$/.test(phone)
        },
        886: {
            name: '中国台湾',
            match: /^[0-9]{10}$/.test(phone)
        },
        65: {
            name: '新加坡',
            match: /^[9|8][0-9]{7}$/.test(phone)
        },
        60: {
            name: '马来西亚',
            match: /^1[1|2|3|4|6|7|9][0-9]{8}$/.test(phone)
        },
        1: {
            name: '加拿大&美国',
            match: /^[0-9]{10}$/.test(phone)
        },
        82: {
            name: '韩国',
            match: /^01[0-9]{9}$/.test(phone)
        },
        44: {
            name: '英国',
            match: /^7[7|8|9][0-9]{8}$/.test(phone)
        },
        81: {
            name: '日本',
            match: /^0[9|8|7][0-9]{9}$/.test(phone)
        },
        61: {
            name: '澳大利亚',
            match: /^[0-9]{11}$/.test(phone)
        }
    };

    if (verify[area]) {
        return verify[area].match;
    } else {
        return false;
    }
}

/**
 * 验证国际手机号是否合法
 */
exports.isAreaMobile = (areaMobile) => {
    if (!areaMobile) {
        return false;
    }

    let mobile = {
        area: '86',
        phone: ''
    };

    let splitMobile = areaMobile.split('-');

    if (splitMobile.length === 2) {
        mobile.area = splitMobile[0];
        mobile.phone = splitMobile[1];
    } else {
        mobile.phone = splitMobile[0];
    }

    return areaMobileVerify(mobile.phone, mobile.area);
};

/**
 *  验证手机是否合法
 */
exports.verifyMobile = (phone) => {
    if (!phone) {
        return false;
    }

    return /^1[3|4|5|8|7][0-9]{9}$/.test(phone);
};

/**
 * 组合国际手机号
 */
exports.makeAreaMobile = (area, mobile) => {
    if (!area || area === '86') {
        return mobile;
    }

    return `${area}-${mobile}`;
};

exports.isPassword = (pwd) => {
    if (!pwd) {
        return false;
    }

    let pwdRegexp = /^([a-zA-Z0-9\-\+_!@\#$%\^&\*\(\)\:\;\.=\[\]\\\',\?]){6,20}$/;

    return pwdRegexp.test(_.trim(pwd));
};