Add configurable internal API URL

This commit is contained in:
Mike Cao committed 2026-05-09 01:06:52 -07:00
1 parent fa182d0947
commit 2fd319f910
6 files changed
+124 -4

No files matched your search

+2 -3
View File
@@ -1,6 +1,7 @@
import { useMutation, useQuery } from '@tanstack/react-query';
import { usePathname } from 'next/navigation';
import { useCallback } from 'react';
import { getApiUrl } from '@/lib/api-url';
import { getClientAuthToken } from '@/lib/client';
import { SHARE_CONTEXT_HEADER, SHARE_TOKEN_HEADER } from '@/lib/constants';
import { type FetchResponse, httpDelete, httpGet, httpPost, httpPut } from '@/lib/fetch';
@@ -31,10 +32,8 @@ export function useApi() {
authorization: `Bearer ${getClientAuthToken()}`,
...shareHeaders,
};
const basePath = process.env.basePath;
const getUrl = (url: string) => {
return url.startsWith('http') ? url : `${basePath || ''}/api${url}`;
return getApiUrl(url);
};
const getHeaders = (headers: any = {}) => {
+36
View File
@@ -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',
);
});
+39
View File
@@ -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);
}