Skip to content

Commit b381b12

Browse files
committedNov 11, 2017
Add Router#url() query params support
1 parent 07d0d37 commit b381b12

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed
 

‎lib/layer.js

+23-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
var debug = require('debug')('koa-router');
22
var pathToRegExp = require('path-to-regexp');
3+
var uri = require('urijs');
34

45
module.exports = Layer;
56

@@ -112,27 +113,42 @@ Layer.prototype.captures = function (path) {
112113
* @private
113114
*/
114115

115-
Layer.prototype.url = function (params) {
116+
Layer.prototype.url = function (params, options) {
116117
var args = params;
117118
var url = this.path.replace('\(\.\*\)', '');
118119
var toPath = pathToRegExp.compile(url);
120+
var replaced;
119121

120-
// argument is of form { key: val }
121122
if (typeof params != 'object') {
122123
args = Array.prototype.slice.call(arguments);
124+
if (typeof args[args.length - 1] == 'object') {
125+
options = args[args.length - 1];
126+
args = args.slice(0, args.length - 1);
127+
}
123128
}
124129

130+
var tokens = pathToRegExp.parse(url);
131+
var replace = {};
132+
125133
if (args instanceof Array) {
126-
var tokens = pathToRegExp.parse(url);
127-
var replace = {};
128134
for (var len = tokens.length, i=0, j=0; i<len; i++) {
129135
if (tokens[i].name) replace[tokens[i].name] = args[j++];
130136
}
131-
return toPath(replace);
137+
} else if (tokens.some(token => token.name)) {
138+
replace = params;
139+
} else {
140+
options = params;
132141
}
133-
else {
134-
return toPath(params);
142+
143+
replaced = toPath(replace);
144+
145+
if (options && options.query) {
146+
var replaced = new uri(replaced)
147+
replaced.search(options.query);
148+
return replaced.toString();
135149
}
150+
151+
return replaced;
136152
};
137153

138154
/**

‎package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
"http-errors": "^1.3.1",
2323
"koa-compose": "^3.0.0",
2424
"methods": "^1.0.1",
25-
"path-to-regexp": "^1.1.1"
25+
"path-to-regexp": "^1.1.1",
26+
"urijs": "^1.19.0"
2627
},
2728
"devDependencies": {
2829
"expect.js": "^0.3.1",

0 commit comments

Comments
 (0)
Please sign in to comment.