diff --git a/modules/Path.js b/modules/Path.js index f510842..9b2bd5f 100644 --- a/modules/Path.js +++ b/modules/Path.js @@ -74,6 +74,11 @@ let tokenise = (str, tokens = []) => { return tokens } +let optTrailingSlash = (source, trailingSlash) => { + if (!trailingSlash) return source + return source.replace(/\/$/, '') + '(?:\/)?' +} + export default class Path { constructor(path) { if (!path) throw new Error('Please supply a path') @@ -117,9 +122,11 @@ export default class Path { }, {}) } - match(path) { + match(path, trailingSlash = 0) { + // trailingSlash: falsy => non optional, truthy => optional + let source = optTrailingSlash(this.source, trailingSlash) // Check if exact match - let match = this._urlMatch(path, new RegExp('^' + this.source + (this.hasQueryParams ? '\?.*$' : '$'))) + let match = this._urlMatch(path, new RegExp('^' + source + (this.hasQueryParams ? '\?.*$' : '$'))) // If no match, or no query params, no need to go further if (!match || !this.hasQueryParams) return match // Extract query params @@ -142,9 +149,11 @@ export default class Path { return null } - partialMatch(path) { + partialMatch(path, trailingSlash = 0) { // Check if partial match (start of given path matches regex) - return this._urlMatch(path, new RegExp('^' + this.source)) + // trailingSlash: falsy => non optional, truthy => optional + let source = optTrailingSlash(this.source, trailingSlash) + return this._urlMatch(path, new RegExp('^' + source)) } build(params = {}, ignoreConstraints = false) { diff --git a/test/main.js b/test/main.js index 21592b1..8578025 100644 --- a/test/main.js +++ b/test/main.js @@ -125,4 +125,16 @@ describe('Path', function () { path.match('/users/;id=A76FE4').should.eql({id: 'A76FE4'}); should.not.exist(path.match('/users;id=Z12345')); }); + + it('should match paths with optional trailing slashes', function () { + var path = new Path('/my-path'); + should.not.exist(path.match('/my-path/')); + path.match('/my-path/', true).should.eql({}); + path.match('/my-path/', 1).should.eql({}); + + path = new Path('/my-path/'); + should.not.exist(path.match('/my-path')); + path.match('/my-path', true).should.eql({}); + path.match('/my-path', 1).should.eql({}); + }); });