Skip to content

Commit

Permalink
feat: support optional trailing slashes
Browse files Browse the repository at this point in the history
  • Loading branch information
troch committed Aug 19, 2015
1 parent 741e70d commit 6785886
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
17 changes: 13 additions & 4 deletions modules/Path.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions test/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({});
});
});

0 comments on commit 6785886

Please sign in to comment.