1 | ;
|
2 | /**
|
3 | * A collection of utilities for working with URLs
|
4 | * @module URLUtils
|
5 | *
|
6 | * @example
|
7 | * const { buildURL } = require('@cumulus/common/URLUtils');
|
8 | *
|
9 | * buildURL({ protocol: 'http', host: 'example.com' }); // => 'http://example.com'
|
10 | */
|
11 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
12 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
13 | };
|
14 | Object.defineProperty(exports, "__esModule", { value: true });
|
15 | exports.buildURL = void 0;
|
16 | const isString_1 = __importDefault(require("lodash/isString"));
|
17 | const url_join_1 = __importDefault(require("url-join"));
|
18 | const url_1 = require("url");
|
19 | const isNil_1 = __importDefault(require("lodash/isNil"));
|
20 | /**
|
21 | * Build a URL
|
22 | *
|
23 | * @param {Object} params - URL parameters
|
24 | * @param {string} params.protocol - the protocol ('http', 'ftp', 's3', etc)
|
25 | * @param {string} params.host - the host
|
26 | * @param {string|integer} [params.port] - the port
|
27 | * @param {string|string[]} [params.path] - path segment(s) to add to the end of
|
28 | * the URL. Can be either a string or an array of strings, which will be
|
29 | * joined together.
|
30 | * @returns {string} a URL
|
31 | * @throws {TypeError} if protocol or host are not specified
|
32 | *
|
33 | * @alias module:URLUtils
|
34 | *
|
35 | * @example
|
36 | * buildURL({
|
37 | * protocol: 'http'
|
38 | * host: 'example.com',
|
39 | * port: 8080,
|
40 | * path: ['path', 'to', 'file.txt']
|
41 | * }); // => 'http://example.com:8080/path/to/file.txt'
|
42 | */
|
43 | exports.buildURL = (params) => {
|
44 | const { protocol, host, port, path = [], } = params;
|
45 | if (isNil_1.default(protocol))
|
46 | throw new TypeError('protocol is required');
|
47 | if (isNil_1.default(host))
|
48 | throw new TypeError('host is required');
|
49 | const url = new url_1.URL(`${protocol}://${host}`);
|
50 | if (port && protocol !== 's3')
|
51 | url.port = port;
|
52 | if (isString_1.default(path))
|
53 | url.pathname = path;
|
54 | else if (path.length > 0)
|
55 | url.pathname = url_join_1.default(...path);
|
56 | return url.toString().replace(/\/$/, '');
|
57 | };
|
58 | //# sourceMappingURL=URLUtils.js.map |
\ | No newline at end of file |