Skip to content

Commit 8f3ac49

Browse files
committed
test: cover initial api url resolution
1 parent e7045a1 commit 8f3ac49

3 files changed

Lines changed: 44 additions & 12 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import {describe, expect, it} from 'vitest'
2+
3+
import {resolveInitialApiUrl} from './apiUrl'
4+
5+
describe('resolveInitialApiUrl', () => {
6+
it('keeps the injected api url when a stale stored url exists', () => {
7+
const apiUrl = resolveInitialApiUrl('/api/v1', 'https://tasks.example.com/api/v1')
8+
9+
expect(apiUrl).toBe('/api/v1')
10+
})
11+
12+
it('uses the stored api url when no api url was injected', () => {
13+
const apiUrl = resolveInitialApiUrl('', 'https://tasks.example.com/api/v1')
14+
15+
expect(apiUrl).toBe('https://tasks.example.com/api/v1')
16+
})
17+
18+
it('removes a trailing slash from the selected api url', () => {
19+
const apiUrl = resolveInitialApiUrl('/api/v1/', 'https://tasks.example.com/api/v1/')
20+
21+
expect(apiUrl).toBe('/api/v1')
22+
})
23+
24+
it('keeps an empty api url when neither source provides one', () => {
25+
const apiUrl = resolveInitialApiUrl('', null)
26+
27+
expect(apiUrl).toBe('')
28+
})
29+
})

frontend/src/helpers/apiUrl.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
export function resolveInitialApiUrl(injectedApiUrl: string, storedApiUrl: string | null): string {
2+
let apiUrl = injectedApiUrl
3+
4+
if (storedApiUrl !== null && apiUrl === '') {
5+
apiUrl = storedApiUrl
6+
}
7+
8+
if (apiUrl.endsWith('/')) {
9+
apiUrl = apiUrl.slice(0, -1)
10+
}
11+
12+
return apiUrl
13+
}

frontend/src/main.ts

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import pinia from './pinia'
44
import router from './router'
55
import App from './App.vue'
66
import {error, success} from './message'
7+
import {resolveInitialApiUrl} from '@/helpers/apiUrl'
78

89
// Notifications
910
import Notifications from '@kyvg/vue3-notification'
@@ -24,18 +25,7 @@ declare global {
2425
}
2526
}
2627

27-
// Check if we have an api url in local storage and use it if the bundled
28-
// frontend did not provide one. This prevents stale values from another host
29-
// from overriding the same-origin default and causing CORS failures.
30-
const apiUrlFromStorage = localStorage.getItem('API_URL')
31-
if (apiUrlFromStorage !== null && window.API_URL === '') {
32-
window.API_URL = apiUrlFromStorage
33-
}
34-
35-
// Make sure the api url does not contain a / at the end
36-
if (window.API_URL.endsWith('/')) {
37-
window.API_URL = window.API_URL.slice(0, -1)
38-
}
28+
window.API_URL = resolveInitialApiUrl(window.API_URL, localStorage.getItem('API_URL'))
3929

4030
// directives
4131
import focus from '@/directives/focus'

0 commit comments

Comments
 (0)