Skip to content

Commit

Permalink
fix: regex for absolute url
Browse files Browse the repository at this point in the history
  • Loading branch information
Rexer Wang committed Apr 30, 2023
1 parent c59dd4e commit f3d87cc
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
20 changes: 10 additions & 10 deletions src/helpers/__tests__/getUri.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ describe('getUri specs', () => {
})
)
).toBe('https://api.com/api/v1/posts')

expect(
getUri(
toAny({
baseURL: 'https://requete.com',
url: '//api.com/api/v1/posts',
})
)
).toBe('//api.com/api/v1/posts')
})

it('should not join when baseURL is falsy', () => {
Expand Down Expand Up @@ -44,20 +53,11 @@ describe('getUri specs', () => {
)
).toBe('https://requete.com/api/v1/posts')

expect(
getUri(
toAny({
baseURL: 'https://requete.com/',
url: '//api/v1/posts/',
})
)
).toBe('https://requete.com/api/v1/posts/')

expect(
getUri(
toAny({
baseURL: 'https://requete.com//',
url: '//api/v1/posts/',
url: '/api/v1/posts/',
})
)
).toBe('https://requete.com/api/v1/posts/')
Expand Down
6 changes: 5 additions & 1 deletion src/helpers/getUri.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@ function stringifyUrl(target: string, query: NonNullable<IRequest['params']>) {
return url + '?' + searchParams.toString()
}

function isAbsolute(url: string) {
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)
}

export function getUri(config: IRequest) {
let url = config.url

if (!url.includes('://') && config.baseURL) {
if (!isAbsolute(url) && config.baseURL) {
url = config.baseURL.replace(/\/+$/, '') + '/' + url.replace(/^\/+/, '')
}

Expand Down

0 comments on commit f3d87cc

Please sign in to comment.