Skip to content

Commit

Permalink
fix: use encodeURIComponent to encode URL params (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
troch authored Dec 29, 2019
1 parent b294b17 commit 946d256
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
16 changes: 15 additions & 1 deletion src/Path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ const upToDelimiter = (source: string, delimiter?: boolean) => {
return /(\/)$/.test(source) ? source : source + '(\\/|\\?|\\.|;|$)'
}

const encodeSpatParam = (value: string) =>
value
.split('/')
.map(encodeURIComponent)
.join('/')

const appendQueryParam = (
params: Record<string, any>,
param: string,
Expand Down Expand Up @@ -119,6 +125,10 @@ export class Path {
return this.queryParams.indexOf(name) !== -1
}

public isSpatParam(name: string): boolean {
return this.spatParams.indexOf(name) !== -1
}

public test(path: string, opts?: ITestOptions): TestMatch {
const options = { strictTrailingSlash: false, queryParams: {}, ...opts }
// trailingSlash: falsy => non optional, truthy => optional
Expand Down Expand Up @@ -190,7 +200,11 @@ export class Path {
}

const val = params[key]
const encode = this.isQueryParam(key) ? identity : encodeURI
const encode = this.isQueryParam(key)
? identity
: this.isSpatParam(key)
? encodeSpatParam
: encodeURIComponent

if (typeof val === 'boolean') {
acc[key] = val
Expand Down
3 changes: 1 addition & 2 deletions test/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ describe('Path', function() {
expect(path.partialTest('/test/%7B123-456%7D')).toEqual({ id: '{123-456}' })
})

it('should encoded values and build paths', function() {
it('should encode values and build paths', function() {
const path = new Path('/test/:id')

expect(path.build({ id: '{123-456}' })).toBe('/test/%7B123-456%7D')
Expand All @@ -280,7 +280,6 @@ describe('Path', function() {
expect(path.partialTest('/test/he:re/test2')).toEqual({ name: 'he:re' })
expect(path.partialTest("/test/he're/test2")).toEqual({ name: "he're" })

expect(path.build({ name: 'he:re' })).toEqual('/test/he:re/test2')
expect(path.build({ name: "he're" })).toEqual("/test/he're/test2")
})

Expand Down

0 comments on commit 946d256

Please sign in to comment.