lib/url/format.js
'use strict';
/**
* @private
* @param query
* @returns {String}
*/
var serializeQuery = function (query) {
var parts = [],
key,
value;
for (key in query) {
if (query.hasOwnProperty(key)) {
value = (query[key] || '').toString();
parts.push(key + '=' + encodeURIComponent(value));
}
}
return parts.join('&');
};
var formatUrl = function (components) {
var protocol = components.protocol || '',
host = components.host,
pathname = components.pathname || '',
search = components.search || '',
hash = components.hash || '';
if (protocol.length > 0) {
if (protocol.slice(-1) !== ':') {
protocol += ':';
}
}
if (components.hostname) {
host = components.hostname;
if (components.port) {
host += ':' + components.port;
}
}
if (host && host.length > 0) {
host = '//' + host;
}
if (typeof components.query === 'object' && components.query !== null) {
search = serializeQuery(components.query);
}
if (search && search.length > 0 && search.charAt(0) !== '?') {
search = '?' + search;
}
if (hash && hash.length > 0 && hash.charAt(0) !== '#') {
hash = '#' + hash;
}
return protocol + host + pathname + search + hash;
};
/**
* @module format
* @desc Constructs a URL from its parsed components. 1) Host takes precedence over hostname and port. 2) Query takes precedence over search.
* @param {Object} components - The url components, as generated by url/parse.js.
* @returns {String}
*/
module.exports = formatUrl;