Skip to content

Commit

Permalink
Merge pull request #95 from dailyrandomphoto/fix-encode-once
Browse files Browse the repository at this point in the history
fix(encodeURL): handle 'URI malformed' exception gracefully
  • Loading branch information
curbengh authored Sep 17, 2019
2 parents 6155112 + 08eeff8 commit a4a0b37
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
29 changes: 19 additions & 10 deletions lib/encode_url.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,35 @@
const { parse, format } = require('url');

function encodeURL(str) {
if (parse(str).protocol) {
const parsed = parse(str);
if (parsed.protocol) {
const obj = Object.assign({}, {
auth: parse(str).auth,
protocol: parse(str).protocol,
host: parse(str).host,
pathname: encodeURI(decodeURI(parse(str).pathname))
auth: parsed.auth,
protocol: parsed.protocol,
host: parsed.host,
pathname: encodeURI(safeDecodeURI(parsed.pathname))
});

if (parse(str).hash) {
Object.assign(obj, { hash: encodeURI(decodeURI(parse(str).hash)) });
if (parsed.hash) {
Object.assign(obj, { hash: encodeURI(safeDecodeURI(parsed.hash)) });
}

if (parse(str).search) {
Object.assign(obj, { search: encodeURI(decodeURI(parse(str).search)) });
if (parsed.search) {
Object.assign(obj, { search: encodeURI(safeDecodeURI(parsed.search)) });
}

return format(obj);
}

return encodeURI(decodeURI(str));
return encodeURI(safeDecodeURI(str));
}

function safeDecodeURI(str) {
try {
return decodeURI(str);
} catch (err) {
return str;
}
}

module.exports = encodeURL;
10 changes: 10 additions & 0 deletions test/encode_url.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ describe('encodeURL', () => {
encodeURL(content).should.eql('http://foo.com/bar?q%C3%BAery=b%C3%A1z');
});

it('query contains %', () => {
const content = 'http://foo.com/bar?query=%';
encodeURL(content).should.eql('http://foo.com/bar?query=%25');
});

it('path or query contains %', () => {
const content = '/bar?query=%';
encodeURL(content).should.eql('/bar?query=%25');
});

it('multiple queries', () => {
const content = 'http://foo.com/bar?query1=aáa&query2=aàa';
encodeURL(content).should.eql('http://foo.com/bar?query1=a%C3%A1a&query2=a%C3%A0a');
Expand Down

0 comments on commit a4a0b37

Please sign in to comment.