insomnia/app/common/querystring.js

99 lines
2.0 KiB
JavaScript
Raw Normal View History

2016-11-10 05:56:23 +00:00
import * as util from './misc.js';
2016-11-10 02:45:43 +00:00
/** Join a URL with a querystring */
export function joinUrl (url, qs) {
if (!qs) {
return url;
}
2016-11-10 02:45:43 +00:00
// TODO: Make this work with URLs that have a #hash component
2016-07-14 22:48:56 +00:00
url = url || '';
return url + getJoiner(url) + qs;
}
2016-07-14 22:48:56 +00:00
2016-11-10 02:45:43 +00:00
export function getJoiner (url) {
url = url || '';
return url.indexOf('?') === -1 ? '?' : '&';
}
/** Build a querystring param out of a name/value pair */
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-09-24 03:26:24 +00:00
const name = util.flexibleEncodeComponent(param.name || '');
2016-11-17 21:55:48 +00:00
const value = util.flexibleEncodeComponent(param.value || '')
.replace(/%2C/gi, ','); // Don't encode , in values
2016-09-24 03:26:24 +00:00
return `${name}=${value}`
2016-07-14 22:48:56 +00:00
} else {
2016-09-24 03:26:24 +00:00
return util.flexibleEncodeComponent(param.name);
2016-07-14 22:48:56 +00:00
}
}
2016-07-14 22:48:56 +00:00
/**
2016-11-10 02:45:43 +00:00
* Build a querystring from a list of name/value pairs
* @param parameters
* @param strict allow empty names and values
*/
export function buildFromParams (parameters, strict = true) {
2016-07-20 23:16:28 +00:00
let items = [];
2016-12-08 17:20:10 +00:00
2016-09-24 03:26:24 +00:00
for (const param of parameters) {
let built = build(param, 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-11-10 02:45:43 +00:00
* Deconstruct a querystring to name/value pairs
* @param qs
* @param strict allow empty names and values
*/
export function deconstructToParams (qs, strict = true) {
2016-12-01 18:48:49 +00:00
if (!qs) {
return [];
}
const stringPairs = qs.split('&');
const pairs = [];
for (let stringPair of stringPairs) {
2016-11-17 18:57:18 +00:00
const [encodedName, encodedValue] = stringPair.split('=');
2016-11-17 18:45:54 +00:00
let name = '';
try {
2016-11-17 18:57:18 +00:00
name = decodeURIComponent(encodedName || '');
2016-11-17 18:45:54 +00:00
} catch (e) {
2016-11-17 21:36:55 +00:00
// Just leave it
name = encodedName;
2016-11-17 18:45:54 +00:00
}
let value = '';
try {
2016-11-17 18:57:18 +00:00
value = decodeURIComponent(encodedValue || '');
2016-11-17 18:45:54 +00:00
} catch (e) {
2016-11-17 21:36:55 +00:00
// Just leave it
value = encodedValue;
2016-11-17 18:45:54 +00:00
}
if (strict && !name) {
continue;
}
pairs.push({name, value});
}
return pairs;
}