2016-09-21 00:03:26 +00:00
|
|
|
'use strict';
|
2016-08-15 17:04:36 +00:00
|
|
|
|
2016-09-23 23:21:20 +00:00
|
|
|
const util = require('./util.js');
|
|
|
|
|
2016-09-21 00:03:26 +00:00
|
|
|
module.exports.getJoiner = url => {
|
2016-07-14 22:48:56 +00:00
|
|
|
url = url || '';
|
|
|
|
return url.indexOf('?') === -1 ? '?' : '&';
|
2016-09-21 00:03:26 +00:00
|
|
|
};
|
2016-07-14 22:48:56 +00:00
|
|
|
|
2016-09-21 00:03:26 +00:00
|
|
|
module.exports.joinURL = (url, qs) => {
|
2016-07-22 20:02:17 +00:00
|
|
|
if (!qs) {
|
|
|
|
return url;
|
|
|
|
}
|
2016-07-14 22:48:56 +00:00
|
|
|
url = url || '';
|
2016-09-21 00:03:26 +00:00
|
|
|
return url + module.exports.getJoiner(url) + qs;
|
|
|
|
};
|
2016-07-14 22:48:56 +00:00
|
|
|
|
2016-09-21 00:03:26 +00:00
|
|
|
module.exports.build = (param, strict = true) => {
|
2016-07-22 20:02:17 +00:00
|
|
|
// Skip non-name ones in strict mode
|
|
|
|
if (strict && !param.name) {
|
|
|
|
return '';
|
|
|
|
}
|
2016-07-14 22:48:56 +00:00
|
|
|
|
2016-07-22 20:02:17 +00:00
|
|
|
if (!strict || param.value) {
|
2016-09-24 03:26:24 +00:00
|
|
|
const name = util.flexibleEncodeComponent(param.name || '');
|
|
|
|
const value = util.flexibleEncodeComponent(param.value || '');
|
|
|
|
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-09-21 00:03:26 +00:00
|
|
|
};
|
2016-07-14 22:48:56 +00:00
|
|
|
|
2016-07-22 20:02:17 +00:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param parameters
|
|
|
|
* @param strict allow empty names and values
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
2016-09-21 00:03:26 +00:00
|
|
|
module.exports.buildFromParams = (parameters, strict = true) => {
|
2016-07-20 23:16:28 +00:00
|
|
|
let items = [];
|
2016-09-24 03:26:24 +00:00
|
|
|
for (const param of parameters) {
|
|
|
|
let built = module.exports.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-09-21 00:03:26 +00:00
|
|
|
};
|
2016-07-22 20:02:17 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param qs
|
|
|
|
* @param strict allow empty names and values
|
|
|
|
* @returns {Array}
|
|
|
|
*/
|
2016-09-21 00:03:26 +00:00
|
|
|
module.exports.deconstructToParams = (qs, strict = true) => {
|
2016-07-22 20:02:17 +00:00
|
|
|
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;
|
2016-09-21 00:03:26 +00:00
|
|
|
};
|