Skip to content

Commit

Permalink
normalizeEntityUri.ts: also remove base path of api if api does not r…
Browse files Browse the repository at this point in the history
…eturn host+port
  • Loading branch information
BacLuc committed Jan 4, 2023
1 parent ac3e155 commit 28a768b
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
29 changes: 28 additions & 1 deletion src/normalizeEntityUri.ts
Expand Up @@ -55,7 +55,34 @@ function normalizeEntityUri (uriOrEntity: string | ResourceInterface | null = ''
*/
function normalizeUri (uri: unknown, baseUrl: string): string | null {
if (typeof uri !== 'string') return null
return sortQueryParams(uri).replace(new RegExp(`^${baseUrl}`), '')
const sorted = sortQueryParams(uri)
const simpleReplace = sorted.replace(new RegExp(`^${baseUrl}`), '')
if (baseUrl && baseUrl.length > 2 && simpleReplace === uri) {
try {
const parsedBaseUrl = new URL(baseUrl)
const uriHasHost = getHostOfUri(uri) !== undefined
if (parsedBaseUrl.host && uriHasHost) {
return simpleReplace
}

const pathname = parsedBaseUrl.pathname.replace(/\/$/, '')
return sorted.replace(new RegExp(`^${pathname}`), '')
} catch (_) {
}
}
return simpleReplace
}

/**
* returns the host of uri if present, or undefined if new URL throws exception.
* @param uri
*/
function getHostOfUri (uri: string): string | undefined {
try {
return new URL(uri).host
} catch (_) {
return undefined
}
}

export default normalizeEntityUri
2 changes: 1 addition & 1 deletion tests/axios.spec.ts
Expand Up @@ -64,7 +64,7 @@ describe('When using baseUrl with axios', () => {
},
expectedFetches: [
'http://localhost:3000/api/',
'http://localhost:3000/api/api/entities'
'http://localhost:3000/api/entities'
]
},
{
Expand Down
15 changes: 15 additions & 0 deletions tests/normalizeUri.spec.js
Expand Up @@ -101,6 +101,21 @@ describe('URI normalizing', () => {
baseUrl: 'http://localhost:3000/api',
uri: 'http://localhost:3000/api/activities',
normalized: '/activities'
},
{
baseUrl: 'http://localhost:3000/api',
uri: '/api/activities',
normalized: '/activities'
},
{
baseUrl: 'http://localhost:3000/api/',
uri: '/api/activities',
normalized: '/activities'
},
{
baseUrl: 'http://localhost:3000/api/',
uri: 'http://localhost:3000/print/activities',
normalized: 'http://localhost:3000/print/activities'
}
]

Expand Down

0 comments on commit 28a768b

Please sign in to comment.