@vtmap/vtmap-sdk-js
Version:
JS SDK for accessing Viettelmaps APIs
121 lines (110 loc) • 3.02 kB
JavaScript
;
// Encode each item of an array individually. The comma
// delimiters should not themselves be encoded.
function encodeArray(arrayValue) {
return arrayValue.map(encodeURIComponent).join(',');
}
function encodeValue(value) {
if (Array.isArray(value)) {
return encodeArray(value);
}
return encodeURIComponent(String(value));
}
/**
* Append a query parameter to a URL.
*
* @param {string} url
* @param {string} key
* @param {string|number|boolean|Array<*>>} [value] - Provide an array
* if the value is a list and commas between values need to be
* preserved, unencoded.
* @returns {string} - Modified URL.
*/
function appendQueryParam(url, key, value) {
if (value === false || value === null) {
return url;
}
var punctuation = /\?/.test(url) ? '&' : '?';
var query = encodeURIComponent(key);
if (value !== undefined && value !== '' && value !== true) {
query += '=' + encodeValue(value);
}
return '' + url + punctuation + query;
}
/**
* Derive a query string from an object and append it
* to a URL.
*
* @param {string} url
* @param {Object} [queryObject] - Values should be primitives.
* @returns {string} - Modified URL.
*/
function appendQueryObject(url, queryObject) {
if (!queryObject) {
return url;
}
var result = url;
Object.keys(queryObject).forEach(function(key) {
var value = queryObject[key];
if (value === undefined) {
return;
}
if (Array.isArray(value)) {
value = value
.filter(function(v) {
return v !== null && v !== undefined;
})
.join(',');
}
result = appendQueryParam(result, key, value);
});
return result;
}
/**
* Prepend an origin to a URL. If the URL already has an
* origin, do nothing.
*
* @param {string} url
* @param {string} origin
* @returns {string} - Modified URL.
*/
function prependOrigin(url, origin) {
if (!origin) {
return url;
}
if (url.slice(0, 4) === 'http') {
return url;
}
var delimiter = url[0] === '/' ? '' : '/';
return '' + origin.replace(/\/$/, '') + delimiter + url;
}
/**
* Interpolate values into a route with express-style,
* colon-prefixed route parameters.
*
* @param {string} route
* @param {Object} [params] - Values should be primitives
* or arrays of primitives. Provide an array if the value
* is a list and commas between values need to be
* preserved, unencoded.
* @returns {string} - Modified URL.
*/
function interpolateRouteParams(route, params) {
if (!params) {
return route;
}
return route.replace(/\/:([a-zA-Z0-9]+)/g, function(_, paramId) {
var value = params[paramId];
if (value === undefined) {
throw new Error('Unspecified route parameter ' + paramId);
}
var preppedValue = encodeValue(value);
return '/' + preppedValue;
});
}
module.exports = {
appendQueryObject: appendQueryObject,
appendQueryParam: appendQueryParam,
prependOrigin: prependOrigin,
interpolateRouteParams: interpolateRouteParams
};