Skip to content

Commit

Permalink
fix encode uri parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
worka committed Mar 16, 2020
1 parent b107c8a commit f8cf6d5
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 14 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jcurl.addParamsExtended('example.com', { bar: { foo: 'test', joo: 2 } });
````
_`jcurl` exactly, not `jsurl`, this is not a mistake :)_

#### getParams(String url)
#### getParams(String url, Boolean decode = true)
`alias get()`

> If you have simple parameters like `bar=1` or `foo[]=3&foo[]=5`, then use `getParams()`.<br />
Expand All @@ -55,7 +55,7 @@ jcurl.get('example.com?bar=1&bar[]=2');
// { bar: ['2'] }
```

#### addParams(String url, Object params)
#### addParams(String url, Object params, Boolean encode = false)
`alias add()`

```javascript
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vanilla-js-url",
"version": "2.3.0",
"version": "2.4.0",
"devDependencies": {
"@babel/core": "^7.8.6",
"@babel/preset-env": "^7.8.6",
Expand Down
12 changes: 6 additions & 6 deletions src/_buildQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,24 @@
export default function _buildQuery(params, encode = false) {
let queries = [];

function e(string) {
return encode ? encodeURIComponent(string) : string;
}

for (let key in params) {
if (params.hasOwnProperty(key)) {
const value = params[key];

if (Array.isArray(value) && value.length) {
value.forEach(_value => {
queries.push(`${ key }[]=${ _value }`);
queries.push(`${ e(`${ key }[]`) }=${ e(_value) }`);
});
} else {
queries.push(`${ key }=${ value }`);
queries.push(`${ e(key) }=${ e(value) }`);
}
}
}

if (encode) {
queries = queries.map(query => encodeURIComponent(query));
}

return queries.join('&');
}

Expand Down
10 changes: 5 additions & 5 deletions src/_buildQueryDeep.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import _simplifyObject from './_simplifyObject';
export default function _buildQueryDeep(params, encode = false) {
const tree = [];

function e(string) {
return encode ? encodeURIComponent(string) : string;
}

_simplifyObject(params, [], tree);

let parts = tree.map(branch => {
Expand All @@ -17,15 +21,11 @@ export default function _buildQueryDeep(params, encode = false) {
} else if (i < branch.length - 1) {
return `${ str }[${ item }]`;
} else {
return `${ str }=${ item }`;
return `${ e(str) }=${ e(item) }`;
}
}, '');
});

if (encode) {
parts = parts.map(part => encodeURIComponent(part));
}

return parts.join('&');
}

Expand Down

0 comments on commit f8cf6d5

Please sign in to comment.