Add configurable internal API URL
This commit is contained in:
1 parent
fa182d0947
commit
2fd319f910
6 files changed
+124
-4
No files matched your search
@@ -0,0 +1,36 @@
|
||||
import { expect, test } from '@jest/globals';
|
||||
import { getApiUrl } from '../api-url';
|
||||
|
||||
test('uses the default api path', () => {
|
||||
expect(getApiUrl('/websites', { apiUrl: '', basePath: '' })).toBe('/api/websites');
|
||||
});
|
||||
|
||||
test('uses basePath with the default api path', () => {
|
||||
expect(getApiUrl('/websites', { apiUrl: '', basePath: '/analytics' })).toBe(
|
||||
'/analytics/api/websites',
|
||||
);
|
||||
});
|
||||
|
||||
test('uses a relative API_URL', () => {
|
||||
expect(getApiUrl('/websites', { apiUrl: '/backend/api', basePath: '' })).toBe(
|
||||
'/backend/api/websites',
|
||||
);
|
||||
});
|
||||
|
||||
test('uses basePath with a relative API_URL', () => {
|
||||
expect(getApiUrl('/websites', { apiUrl: '/backend/api', basePath: '/analytics' })).toBe(
|
||||
'/analytics/backend/api/websites',
|
||||
);
|
||||
});
|
||||
|
||||
test('uses an absolute API_URL directly', () => {
|
||||
expect(getApiUrl('/websites', { apiUrl: 'https://api.example.com/api', basePath: '' })).toBe(
|
||||
'https://api.example.com/api/websites',
|
||||
);
|
||||
});
|
||||
|
||||
test('leaves absolute request URLs unchanged', () => {
|
||||
expect(getApiUrl('https://example.com/custom', { apiUrl: '/backend/api', basePath: '' })).toBe(
|
||||
'https://example.com/custom',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
type ApiUrlOptions = {
|
||||
apiUrl?: string;
|
||||
basePath?: string;
|
||||
};
|
||||
|
||||
function trimTrailingSlash(value: string) {
|
||||
return value.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
function trimLeadingSlash(value: string) {
|
||||
return value.replace(/^\/+/, '');
|
||||
}
|
||||
|
||||
function joinPath(base: string, path: string) {
|
||||
if (!base) {
|
||||
return `/${trimLeadingSlash(path)}`;
|
||||
}
|
||||
|
||||
return `${trimTrailingSlash(base)}/${trimLeadingSlash(path)}`;
|
||||
}
|
||||
|
||||
function isAbsoluteUrl(url: string) {
|
||||
return /^https?:\/\//i.test(url);
|
||||
}
|
||||
|
||||
export function getApiUrl(url: string, options: ApiUrlOptions = {}) {
|
||||
if (isAbsoluteUrl(url)) {
|
||||
return url;
|
||||
}
|
||||
|
||||
const { apiUrl = process.env.apiUrl || '', basePath = process.env.basePath || '' } = options;
|
||||
const baseUrl = apiUrl
|
||||
? isAbsoluteUrl(apiUrl)
|
||||
? apiUrl
|
||||
: joinPath(basePath, apiUrl)
|
||||
: joinPath(basePath, '/api');
|
||||
|
||||
return joinPath(baseUrl, url);
|
||||
}
|
||||
Reference in new issue
Block a user