UNPKG

@sangaman/xud

Version:
103 lines 3.34 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const http_1 = __importDefault(require("http")); const errors_1 = __importDefault(require("../p2p/errors")); /** * Gets the external IP of the node */ exports.getExternalIp = () => { return new Promise((resolve, reject) => { http_1.default.get('http://ipv4.icanhazip.com/', (res) => { let body = ''; res.on('data', (chunk) => { body += chunk; }); res.on('end', () => { // Removes new line at the end of the string body = body.trimRight(); resolve(body); }); res.on('error', (err) => { reject(errors_1.default.EXTERNAL_IP_UNRETRIEVABLE(err)); }); }).on('error', (err) => { reject(errors_1.default.EXTERNAL_IP_UNRETRIEVABLE(err)); }); }); }; /** * Check whether a variable is a non-array object */ exports.isObject = (val) => { return (val && typeof val === 'object' && !Array.isArray(val)); }; /** * Check whether a variable is an empty object */ exports.isEmptyObject = (val) => { return exports.isObject(val) && Object.keys(val).length === 0; }; /** Get the current date in the LocaleString format. */ exports.getTsString = () => (new Date()).toLocaleString(); /** * Recursively merge properties from different sources into a target object, overriding any * existing properties. * @param target the destination object to merge into. * @param sources the sources objects to copy from. */ exports.deepMerge = (target, ...sources) => { if (!sources.length) return target; const source = sources.shift(); if (exports.isObject(target) && exports.isObject(source)) { Object.keys(source).forEach((key) => { if (exports.isObject(source[key])) { if (!target[key]) Object.assign(target, { [key]: {} }); exports.deepMerge(target[key], source[key]); } else if (source[key] !== undefined) { Object.assign(target, { [key]: source[key] }); } }); } return exports.deepMerge(target, ...sources); }; /** * Get all methods from an object whose name doesn't start with an underscore. */ exports.getPublicMethods = (obj) => { const ret = {}; Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).forEach((name) => { const func = obj[name]; if ((func instanceof Function) && name !== 'constructor' && !name.startsWith('_')) { ret[name] = func; } }); return ret; }; exports.groupBy = (arr, keyGetter) => { const ret = {}; arr.forEach((item) => { const key = keyGetter(item); const group = ret[key]; if (!group) { ret[key] = [item]; } else { group.push(item); } }); return ret; }; /** * Get current time in unix time (milliseconds). */ exports.ms = () => { return Date.now(); }; //# sourceMappingURL=utils.js.map