Skip to content

Commit

Permalink
Add decode option to .parse() (sindresorhus#124)
Browse files Browse the repository at this point in the history
  • Loading branch information
yadielar authored and sindresorhus committed May 2, 2018
1 parent e5a6c1f commit 3fd6fd9
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
14 changes: 11 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ function encode(value, options) {
return value;
}

function decode(value, options) {
if (options.decode) {
return decodeComponent(value);
}

return value;
}

function keysSorter(input) {
if (Array.isArray(input)) {
return input.sort();
Expand All @@ -119,7 +127,7 @@ function extract(input) {
}

function parse(input, options) {
options = Object.assign({arrayFormat: 'none'}, options);
options = Object.assign({decode: true, arrayFormat: 'none'}, options);

const formatter = parserForArrayFormat(options);

Expand All @@ -141,9 +149,9 @@ function parse(input, options) {

// Missing `=` should be `null`:
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
value = value === undefined ? null : decodeComponent(value);
value = value === undefined ? null : decode(value, options);

formatter(decodeComponent(key), value, ret);
formatter(decode(key, options), value, ret);
}

return Object.keys(ret).sort().reduce((result, key) => {
Expand Down
7 changes: 6 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,12 @@ Parse a query string into an object. Leading `?` or `#` are ignored, so you can

The returned object is created with [`Object.create(null)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) and thus does not have a `prototype`.

URI components are decoded with [`decode-uri-component`](https://github.com/SamVerschueren/decode-uri-component).
#### decode

Type: `boolean`<br>
Default: `true`

Decode the keys and values. URI components are decoded with [`decode-uri-component`](https://github.com/SamVerschueren/decode-uri-component).

#### arrayFormat

Expand Down
4 changes: 4 additions & 0 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,7 @@ test('decode keys and values', t => {
t.deepEqual(m.parse('st%C3%A5le=foo'), {ståle: 'foo'});
t.deepEqual(m.parse('foo=%7B%ab%%7C%de%%7D+%%7Bst%C3%A5le%7D%'), {foo: '{%ab%|%de%} %{ståle}%'});
});

test('disable decoding of keys and values', t => {
t.deepEqual(m.parse('tags=postal%20office,burger%2C%20fries%20and%20coke', {decode: false}), {tags: 'postal%20office,burger%2C%20fries%20and%20coke'});
});

0 comments on commit 3fd6fd9

Please sign in to comment.