diff --git a/lib/url.js b/lib/url.js index 250974f..624eb5d 100644 --- a/lib/url.js +++ b/lib/url.js @@ -90,7 +90,13 @@ Url.toQueryString = function (queryObject) { } _.each(queryObject, function (value, key) { - result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); + if (_.isArray(value)) { + _.each(value, function(valuePart) { + result.push(encodeURIComponent(key + '[]') + '=' + encodeURIComponent(valuePart)); + }); + } else { + result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); + } }); // no sense in adding a pointless question mark @@ -247,7 +253,16 @@ Url.prototype.params = function (path) { if (queryString) { _.each(queryString.split('&'), function (paramString) { paramParts = paramString.split('='); - params[paramParts[0]] = decodeURIComponent(paramParts[1]); + var key = paramParts[0]; + var value = decodeURIComponent(paramParts[1]); + + if (key.slice(-2) === '[]') { + var key = key.slice(0, -2) + params[key] = params[key] || []; + params[key].push(value) + } else { + params[key] = value; + } }); } diff --git a/test/url_test.js b/test/url_test.js index 1ae203b..1d0153c 100644 --- a/test/url_test.js +++ b/test/url_test.js @@ -168,3 +168,23 @@ Tinytest.add('Url - matching', function (test) { test.isTrue(path.exec('/commits/123..456')); */ }); + +Tinytest.add('Url - params', function (test) { + var path = new Url(paths.explicit); + test.isUndefined(path.params('/posts').foo); + test.equal(path.params('/posts?foo=bar').foo, 'bar'); + test.equal(path.params('/posts?foo[]=bar').foo, ['bar']); + test.equal(path.params('/posts?foo%5B%5D=bar').foo, ['bar']); + test.equal(path.params('/posts?foo[]=bar&foo[]=baz').foo, ['bar', 'baz']); + test.equal(path.params('/posts?foo%5B%5D=bar&foo%5B%5D=baz').foo, ['bar', 'baz']); +}); + +Tinytest.add('Url - resolve', function (test) { + var path = new Url(paths.explicit); + test.equal(path.resolve({}), '/posts'); + test.equal(path.resolve({}, {query: {foo: 'bar'}}), '/posts?foo=bar'); + test.equal(path.resolve({}, {query: {foo: ['bar']}}), '/posts?foo%5B%5D=bar'); + test.equal(path.resolve({}, {query: {foo: ['bar', 'baz']}}), '/posts?foo%5B%5D=bar&foo%5B%5D=baz'); + // no good resolution of this one + test.equal(path.resolve({}, {query: {foo: []}}), '/posts'); +});