Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use encodeURIComponent to encode URL params #43

Merged
merged 1 commit into from
Dec 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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