diff --git a/API.md b/API.md index 8ca55fd..24e7c36 100644 --- a/API.md +++ b/API.md @@ -424,7 +424,7 @@ router ### Router.url(path, params) ⇒ String -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 [Router](#exp_module_koa-router--Router) diff --git a/lib/layer.js b/lib/layer.js index 5ad4d38..7cddcbe 100644 --- a/lib/layer.js +++ b/lib/layer.js @@ -119,7 +119,7 @@ Layer.prototype.url = function (params, options) { } } - const toPath = compile(url, options); + const toPath = compile(url, { encode: encodeURIComponent, ...options }); let replaced; const tokens = parse(url); diff --git a/package.json b/package.json index b2e9259..bb0fbaa 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@koa/router", "description": "Router middleware for koa. Maintained by Forward Email and Lad.", - "version": "11.0.1", + "version": "12.0.0", "author": "Alex Mingoia ", "bugs": { "url": "https://github.com/koajs/router/issues", diff --git a/test/lib/layer.js b/test/lib/layer.js index f202be5..9b82847 100644 --- a/test/lib/layer.js +++ b/test/lib/layer.js @@ -303,6 +303,17 @@ 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' diff --git a/test/lib/router.js b/test/lib/router.js index 547bfb1..67da1e1 100644 --- a/test/lib/router.js +++ b/test/lib/router.js @@ -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 () {