feat: default web API calls to same origin
This commit is contained in:
@@ -7,7 +7,8 @@
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "bun test ./test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codexdash/shared-types": "workspace:*",
|
||||
|
||||
22
apps/web/src/lib/api-base.ts
Normal file
22
apps/web/src/lib/api-base.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
const LOCALHOST_API_ORIGIN = 'http://localhost:3001';
|
||||
|
||||
function trimTrailingSlashes(value: string): string {
|
||||
return value.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export function getApiBaseUrl(
|
||||
configuredApiBaseUrl?: string,
|
||||
windowOrigin?: string,
|
||||
): string {
|
||||
const configured = configuredApiBaseUrl?.trim();
|
||||
if (configured) {
|
||||
return trimTrailingSlashes(configured);
|
||||
}
|
||||
|
||||
const origin = windowOrigin?.trim();
|
||||
if (origin) {
|
||||
return trimTrailingSlashes(origin);
|
||||
}
|
||||
|
||||
return LOCALHOST_API_ORIGIN;
|
||||
}
|
||||
@@ -10,9 +10,13 @@ import type {
|
||||
UsageSummary,
|
||||
UserProfile,
|
||||
} from '@codexdash/shared-types';
|
||||
import { getApiBaseUrl } from './api-base';
|
||||
import { clearToken, getToken } from './storage';
|
||||
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3001';
|
||||
const API_BASE_URL = getApiBaseUrl(
|
||||
import.meta.env.VITE_API_BASE_URL,
|
||||
typeof window === 'undefined' ? undefined : window.location.origin,
|
||||
);
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const token = getToken();
|
||||
|
||||
20
apps/web/test/api-base.test.js
Normal file
20
apps/web/test/api-base.test.js
Normal file
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { getApiBaseUrl } from '../src/lib/api-base.ts';
|
||||
|
||||
describe('getApiBaseUrl', () => {
|
||||
test('uses the configured API base when provided', () => {
|
||||
expect(getApiBaseUrl('https://api.example.com/', 'https://app.example.com')).toBe(
|
||||
'https://api.example.com',
|
||||
);
|
||||
});
|
||||
|
||||
test('defaults to the current window origin when no API base is configured', () => {
|
||||
expect(getApiBaseUrl(undefined, 'https://app.example.com/')).toBe(
|
||||
'https://app.example.com',
|
||||
);
|
||||
});
|
||||
|
||||
test('falls back to localhost in non-browser contexts without configuration', () => {
|
||||
expect(getApiBaseUrl(undefined, undefined)).toBe('http://localhost:3001');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user