Better url encoding

This commit is contained in:
Gregory Schier 2016-11-17 13:36:55 -08:00
parent 85940179e1
commit 8914b74dcd
3 changed files with 19 additions and 14 deletions

View File

@ -116,7 +116,7 @@ describe('prepareUrlForSending()', () => {
it('encodes querystring', () => {
const url = misc.prepareUrlForSending('https://google.com?s=foo bar 100%&hi');
expect(url).toBe('https://google.com/?s=foo%20bar%20100%25&hi=');
expect(url).toBe('https://google.com/?s=foo%20bar%20100%25&hi');
});
it('encodes querystring with mixed spaces', () => {

View File

@ -81,7 +81,7 @@ export function prepareUrlForSending (url) {
const urlWithProto = setDefaultProtocol(url);
// Parse the URL into components
const parsedUrl = urlParse(urlWithProto, true);
const parsedUrl = urlParse(urlWithProto);
// ~~~~~~~~~~~ //
// 1. Pathname //
@ -99,17 +99,20 @@ export function prepareUrlForSending (url) {
// 2. Querystring //
// ~~~~~~~~~~~~~~ //
// Deleting search key will force url.format to encode parsedURL.query
delete parsedUrl.search;
for (const name of Object.keys(parsedUrl.query)) {
const value = parsedUrl.query[name];
delete parsedUrl[name];
if (Array.isArray(value)) {
parsedUrl[flexibleEncodeComponent(name)] = value.map(flexibleEncodeComponent);
} else {
parsedUrl[flexibleEncodeComponent(name)] = flexibleEncodeComponent(value);
if (parsedUrl.query) {
const qsParams = querystring.deconstructToParams(parsedUrl.query);
const encodedQsParams = [];
for (const {name, value} of qsParams) {
encodedQsParams.push({
name: flexibleEncodeComponent(name),
value: flexibleEncodeComponent(value)
});
console.log('PUSHING', name, value);
}
parsedUrl.query = querystring.buildFromParams(encodedQsParams);
parsedUrl.search = `?${parsedUrl.query}`;
console.log('URL', parsedUrl);
}
return urlFormat(parsedUrl);

View File

@ -68,14 +68,16 @@ export function deconstructToParams (qs, strict = true) {
try {
name = decodeURIComponent(encodedName || '');
} catch (e) {
console.warn(`[querystring] Failed to decode name: ${encodedName}`, e);
// Just leave it
name = encodedName;
}
let value = '';
try {
value = decodeURIComponent(encodedValue || '');
} catch (e) {
console.warn(`[querystring] Failed to decode value: ${encodedValue}`, e);
// Just leave it
value = encodedValue;
}
if (strict && !name) {