Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] URL-encode path parameters for Router.url #116

Merged
merged 1 commit into from
Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion API.md
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ router

### Router.url(path, params) ⇒ <code>String</code>

Generate URL from url pattern and given `params`.
Generate URL from url pattern and given `params`. This method URL-encodes the parameters before including them in the URL.

**Kind**: static method of <code>[Router](#exp_module_koa-router--Router)</code>

Expand Down
2 changes: 1 addition & 1 deletion lib/layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ Layer.prototype.url = function (params, options) {
}
}

const toPath = compile(url, options);
const toPath = compile(url, Object.assign({ encode: encodeURIComponent }, options));
let replaced;

const tokens = parse(url);
Expand Down
6 changes: 6 additions & 0 deletions test/lib/layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,12 @@ describe('Layer', function () {
url.should.equal('/programming/how-to-node');
});

it('escapes using encodeURIComponent()', function() {
const route = new Layer('/:category/:title', ['get'], [function () {}], {name: 'books'});
const url = route.url({ category: 'programming', title: 'how to node & js/ts' });
url.should.equal('/programming/how%20to%20node%20%26%20js%2Fts');
});

it('setPrefix method checks Layer for path', function () {
const route = new Layer('/category', ['get'], [function () {}], {
name: 'books'
Expand Down
8 changes: 8 additions & 0 deletions test/lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -1674,6 +1674,14 @@ describe('Router', function () {
router.url('Picard').should.be.Error();
router.url(Symbol('books')).should.be.Error();
});

it('escapes using encodeURIComponent()', function() {
const url = Router.url(
'/:category/:title',
{ category: 'programming', title: 'how to node & js/ts' }
);
url.should.equal('/programming/how%20to%20node%20%26%20js%2Fts');
});
});

describe('Router#param()', function () {
Expand Down