Skip to content

Commit 77fa11b

Browse files
fix(UrlMatcherFactory): Correct trailing slash of terminal optional parameter
Fixes #1902
1 parent 9dc31c5 commit 77fa11b

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/urlMatcherFactory.js

+4
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,8 @@ UrlMatcher.prototype.format = function (values) {
342342

343343
if (isPathParam) {
344344
var nextSegment = segments[i + 1];
345+
var isFinalPathParam = i + 1 === nPath;
346+
345347
if (squash === false) {
346348
if (encoded != null) {
347349
if (isArray(encoded)) {
@@ -357,6 +359,8 @@ UrlMatcher.prototype.format = function (values) {
357359
} else if (isString(squash)) {
358360
result += squash + nextSegment;
359361
}
362+
363+
if (isFinalPathParam && param.squash === true && result.slice(-1) === '/') result = result.slice(0, -1);
360364
} else {
361365
if (encoded == null || (isDefaultValue && squash !== false)) continue;
362366
if (!isArray(encoded)) encoded = [ encoded ];

test/urlMatcherFactorySpec.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,14 @@ describe("UrlMatcher", function () {
149149
params = { id: 'bob', section: 'contact-details' };
150150
expect(m.format(params)).toEqual('/users/bob#contact-details');
151151
});
152+
153+
it("should trim trailing slashes when the terminal value is optional", function () {
154+
var config = { params: { id: { squash: true, value: '123' } } },
155+
m = new UrlMatcher('/users/:id', config),
156+
params = { id: '123' };
157+
158+
expect(m.format(params)).toEqual('/users');
159+
});
152160
});
153161

154162
describe(".concat()", function() {
@@ -623,8 +631,8 @@ describe("urlMatcherFactory", function () {
623631
params: { id: { value: null, squash: true }, state: { value: null, squash: true } }
624632
});
625633

626-
expect(m.format()).toBe("/users/");
627-
expect(m.format({ id: 1138 })).toBe("/users/1138/");
634+
expect(m.format()).toBe("/users");
635+
expect(m.format({ id: 1138 })).toBe("/users/1138");
628636
expect(m.format({ state: "NY" })).toBe("/users/NY");
629637
expect(m.format({ id: 1138, state: "NY" })).toBe("/users/1138/NY");
630638
});

0 commit comments

Comments
 (0)