Skip to content

Commit 8211a6a

Browse files
committed
normalizeEntityUri.ts: also remove base path of api if api does not return host+port
1 parent b216857 commit 8211a6a

File tree

3 files changed

+44
-2
lines changed

3 files changed

+44
-2
lines changed

src/normalizeEntityUri.ts

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,34 @@ function normalizeEntityUri (uriOrEntity: string | ResourceInterface | null = ''
5555
*/
5656
function normalizeUri (uri: unknown, baseUrl: string): string | null {
5757
if (typeof uri !== 'string') return null
58-
return sortQueryParams(uri).replace(new RegExp(`^${baseUrl}`), '')
58+
const sorted = sortQueryParams(uri)
59+
const simpleReplace = sorted.replace(new RegExp(`^${baseUrl}`), '')
60+
if (baseUrl && simpleReplace === uri) {
61+
try {
62+
const parsedBaseUrl = new URL(baseUrl)
63+
const uriHasHost = getHostOfUri(uri) !== undefined
64+
if (parsedBaseUrl.host && uriHasHost) {
65+
return simpleReplace
66+
}
67+
68+
const pathname = parsedBaseUrl.pathname.replace(/\/$/, '')
69+
return sorted.replace(new RegExp(`^${pathname}`), '')
70+
} catch (_) {
71+
}
72+
}
73+
return simpleReplace
74+
}
75+
76+
/**
77+
* returns the host of uri if present, or undefined if new URL throws exception.
78+
* @param uri
79+
*/
80+
function getHostOfUri (uri: string): string | undefined {
81+
try {
82+
return new URL(uri).host
83+
} catch (_) {
84+
return undefined
85+
}
5986
}
6087

6188
export default normalizeEntityUri

tests/axios.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ describe('When using baseUrl with axios', () => {
6464
},
6565
expectedFetches: [
6666
'http://localhost:3000/api/',
67-
'http://localhost:3000/api/api/entities'
67+
'http://localhost:3000/api/entities'
6868
]
6969
},
7070
{

tests/normalizeUri.spec.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,21 @@ describe('URI normalizing', () => {
101101
baseUrl: 'http://localhost:3000/api',
102102
uri: 'http://localhost:3000/api/activities',
103103
normalized: '/activities'
104+
},
105+
{
106+
baseUrl: 'http://localhost:3000/api',
107+
uri: '/api/activities',
108+
normalized: '/activities'
109+
},
110+
{
111+
baseUrl: 'http://localhost:3000/api/',
112+
uri: '/api/activities',
113+
normalized: '/activities'
114+
},
115+
{
116+
baseUrl: 'http://localhost:3000/api/',
117+
uri: 'http://localhost:3000/print/activities',
118+
normalized: 'http://localhost:3000/print/activities'
104119
}
105120
]
106121

0 commit comments

Comments
 (0)