insomnia/app/lib/querystring.js

74 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-07-14 22:48:56 +00:00
export function getJoiner (url) {
url = url || '';
return url.indexOf('?') === -1 ? '?' : '&';
2016-07-20 23:16:28 +00:00
}
2016-07-14 22:48:56 +00:00
export function joinURL (url, qs) {
if (!qs) {
return url;
}
2016-07-14 22:48:56 +00:00
url = url || '';
return url + getJoiner(url) + qs;
2016-07-20 23:16:28 +00:00
}
2016-07-14 22:48:56 +00:00
export function build (param, strict = true) {
// Skip non-name ones in strict mode
if (strict && !param.name) {
return '';
}
2016-07-14 22:48:56 +00:00
if (!strict || param.value) {
2016-07-14 22:48:56 +00:00
return encodeURIComponent(param.name) + '=' + encodeURIComponent(param.value);
} else {
return encodeURIComponent(param.name);
}
2016-07-20 23:16:28 +00:00
}
2016-07-14 22:48:56 +00:00
/**
*
* @param parameters
* @param strict allow empty names and values
* @returns {string}
*/
export function buildFromParams (parameters, strict = true) {
2016-07-20 23:16:28 +00:00
let items = [];
for (var i = 0; i < parameters.length; i++) {
let built = build(parameters[i], strict);
2016-07-20 23:16:28 +00:00
if (!built) {
continue;
}
items.push(built);
2016-07-14 22:48:56 +00:00
}
return items.join('&');
2016-07-20 23:16:28 +00:00
}
/**
*
* @param qs
* @param strict allow empty names and values
* @returns {Array}
*/
export function deconstructToParams (qs, strict = true) {
const stringPairs = qs.split('&');
const pairs = [];
for (let stringPair of stringPairs) {
const tmp = stringPair.split('=');
const name = decodeURIComponent(tmp[0] || '');
const value = decodeURIComponent(tmp[1] || '');
if (strict && !name) {
continue;
}
pairs.push({name, value});
}
return pairs;
}