From 9cf764efab45fa9309368688d535ddf6e96d6449 Mon Sep 17 00:00:00 2001 From: Nate Abele Date: Tue, 22 Apr 2014 09:34:54 -0400 Subject: [PATCH] feat(UrlMatcher): handle query string arrays UrlMatcher now correctly handles query string array values coming from $location, and properly encodes them to URLs, following $location's convention. Closes #373 --- src/urlMatcherFactory.js | 12 +++++++++--- test/urlMatcherFactorySpec.js | 14 +++++++------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/urlMatcherFactory.js b/src/urlMatcherFactory.js index fa4edf16d..67da94120 100644 --- a/src/urlMatcherFactory.js +++ b/src/urlMatcherFactory.js @@ -301,7 +301,7 @@ UrlMatcher.prototype.format = function (values) { if (!values) return segments.join('').replace('//', '/'); var nPath = segments.length - 1, nTotal = params.length, - result = segments[0], i, search, value, param, cfg; + result = segments[0], i, search, value, param, cfg, array; if (!this.validates(values)) return null; @@ -317,8 +317,14 @@ UrlMatcher.prototype.format = function (values) { for (/**/; i < nTotal; i++) { param = params[i]; - if (values[param] == null) continue; - result += (search ? '&' : '?') + param + '=' + encodeURIComponent(values[param]); + value = values[param]; + if (value == null) continue; + array = isArray(value); + + if (array) { + value = value.map(encodeURIComponent).join('&' + param + '='); + } + result += (search ? '&' : '?') + param + '=' + (array ? value : encodeURIComponent(value)); search = true; } return result; diff --git a/test/urlMatcherFactorySpec.js b/test/urlMatcherFactorySpec.js index 1926c491e..0b253a123 100644 --- a/test/urlMatcherFactorySpec.js +++ b/test/urlMatcherFactorySpec.js @@ -55,13 +55,13 @@ describe("UrlMatcher", function () { it("should parse parameter placeholders", function () { var matcher = new UrlMatcher('/users/:id/details/{type}/{repeat:[0-9]+}?from&to'); - var params = matcher.parameters(); - expect(params.length).toBe(5); - expect(params).toContain('id'); - expect(params).toContain('type'); - expect(params).toContain('repeat'); - expect(params).toContain('from'); - expect(params).toContain('to'); + expect(matcher.parameters()).toEqual(['id', 'type', 'repeat', 'from', 'to']); + }); + + it("should encode and decode duplicate query string values as array", function () { + var matcher = new UrlMatcher('/?foo'), array = { foo: ["bar", "baz"] }; + expect(matcher.exec('/', array)).toEqual(array); + expect(matcher.format(array)).toBe('/?foo=bar&foo=baz'); }); describe("snake-case parameters", function() {