common.js 1.75 KB
/**
 *
 * @author: jiangfeng<jeff.jiang@yoho.cn>
 * @date: 16/7/22
 */
'use strict';
const moment = require('moment');
const xml2js = require('xml2js');

const common = {
    getPayExpireMin(expire) {
        let defaultValue = 120;

        if (expire) {
            let expireTime = moment(expire, 'YYYY-MM-DD HH:mm:ss');
            let diff = expireTime.diff(moment());

            if (diff > 0) {
                return Math.floor(diff / 1000 / 60);
            } else {
                return 0;
            }

        } else {
            return defaultValue;
        }
    },
    getPayExpireCouple(expire) {
        let start = expire ? moment(expire, 'YYYY-MM-DD HH:mm:ss') : moment();
        let end = expire ? moment(expire, 'YYYY-MM-DD HH:mm:ss') : moment();

        return {
            start: start.subtract(2, 'hours'),
            end: end.add(5, 'minutes')
        };
    },
    nonceStr(length) {
        length = length || 32;

        let chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        let str = '';

        for (let i = 0; i < length; i++) {
            str += chars[parseInt(Math.random() * length, 10)];
        }
        return str;
    },
    toXml(obj, root) {
        let xmlBuilder = new xml2js.Builder({
            rootName: root || 'xml'
        });

        return xmlBuilder.buildObject(obj);
    },
    xml2Obj(xml) {
        let xmlParser = new xml2js.Parser({
            trim: true,
            explicitArray: false
        });

        return new Promise((resolve, reject) => {
            xmlParser.parseString(xml, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
    }
};

module.exports = common;