@cumulus/common
Version:
Common utilities used across tasks
59 lines • 2.07 kB
JavaScript
;
/**
* A collection of utilities for working with URLs
* @module URLUtils
*
* @example
* const { buildURL } = require('@cumulus/common/URLUtils');
*
* buildURL({ protocol: 'http', host: 'example.com' }); // => 'http://example.com'
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildURL = void 0;
const isString_1 = __importDefault(require("lodash/isString"));
const url_join_1 = __importDefault(require("url-join"));
const url_1 = require("url");
const isNil_1 = __importDefault(require("lodash/isNil"));
/**
* Build a URL
*
* @param {Object} params - URL parameters
* @param {string} params.protocol - the protocol ('http', 'ftp', 's3', etc)
* @param {string} params.host - the host
* @param {string|integer} [params.port] - the port
* @param {string|string[]} [params.path] - path segment(s) to add to the end of
* the URL. Can be either a string or an array of strings, which will be
* joined together.
* @returns {string} a URL
* @throws {TypeError} if protocol or host are not specified
*
* @alias module:URLUtils
*
* @example
* buildURL({
* protocol: 'http'
* host: 'example.com',
* port: 8080,
* path: ['path', 'to', 'file.txt']
* }); // => 'http://example.com:8080/path/to/file.txt'
*/
const buildURL = (params) => {
const { protocol, host, port, path = [], } = params;
if ((0, isNil_1.default)(protocol))
throw new TypeError('protocol is required');
if ((0, isNil_1.default)(host))
throw new TypeError('host is required');
const url = new url_1.URL(`${protocol}://${host}`);
if (port && protocol !== 's3')
url.port = port;
if ((0, isString_1.default)(path))
url.pathname = path;
else if (path.length > 0)
url.pathname = (0, url_join_1.default)(...path);
return url.toString().replace(/\/$/, '');
};
exports.buildURL = buildURL;
//# sourceMappingURL=URLUtils.js.map