diff --git a/src/api.test.ts b/src/api.test.ts new file mode 100644 index 0000000000..912d4f3fa0 --- /dev/null +++ b/src/api.test.ts @@ -0,0 +1,19 @@ +import { getRootPath } from './api'; + +describe('API', () => { + beforeAll(() => { + globalThis.window = Object.create(window); + }); + + it('Calculates the correct API root URL based on window', () => { + Object.defineProperty(window, 'location', { + value: { + pathname: '/api/nested/admin' + }, + writable: true + }); + + const result = getRootPath(); + expect(result).toBe('/api/nested/'); + }); +}); diff --git a/src/api.ts b/src/api.ts new file mode 100644 index 0000000000..a99565b3de --- /dev/null +++ b/src/api.ts @@ -0,0 +1,15 @@ +import axios from 'axios'; + +const api = axios.create({ + baseURL: getRootPath() +}); + +export function getRootPath(): string { + const path = window.location.pathname; + const parts = path.split('/'); + const adminIndex = parts.indexOf('admin'); + const rootPath = parts.slice(0, adminIndex).join('/') + '/'; + return rootPath; +} + +export default api;