|
| 1 | +/** |
| 2 | + * Runtime Configuration Loader |
| 3 | + * |
| 4 | + * Loads configuration from /config.json at runtime. |
| 5 | + * This allows the API URL to be set during CDK deployment |
| 6 | + * without requiring a frontend rebuild. |
| 7 | + */ |
| 8 | + |
| 9 | +let configPromise = null; |
| 10 | +let cachedConfig = null; |
| 11 | + |
| 12 | +/** |
| 13 | + * Default configuration (used during development) |
| 14 | + */ |
| 15 | +const defaultConfig = { |
| 16 | + apiUrl: '', // Empty string means use relative path (for dev proxy) |
| 17 | +}; |
| 18 | + |
| 19 | +/** |
| 20 | + * Load configuration from /config.json |
| 21 | + * Falls back to environment variable or default config if not available. |
| 22 | + */ |
| 23 | +export async function loadConfig() { |
| 24 | + if (cachedConfig) { |
| 25 | + return cachedConfig; |
| 26 | + } |
| 27 | + |
| 28 | + if (!configPromise) { |
| 29 | + configPromise = (async () => { |
| 30 | + try { |
| 31 | + const response = await fetch('/config.json'); |
| 32 | + if (response.ok) { |
| 33 | + const config = await response.json(); |
| 34 | + console.log('[Config] Loaded from /config.json:', config); |
| 35 | + cachedConfig = config; |
| 36 | + return config; |
| 37 | + } |
| 38 | + } catch (err) { |
| 39 | + console.log('[Config] /config.json not found, using defaults'); |
| 40 | + } |
| 41 | + |
| 42 | + // Fallback to environment variable (for local development) |
| 43 | + const envApiUrl = import.meta.env.VITE_API_URL || ''; |
| 44 | + cachedConfig = { |
| 45 | + ...defaultConfig, |
| 46 | + apiUrl: envApiUrl, |
| 47 | + }; |
| 48 | + console.log('[Config] Using fallback config:', cachedConfig); |
| 49 | + return cachedConfig; |
| 50 | + })(); |
| 51 | + } |
| 52 | + |
| 53 | + return configPromise; |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Get cached config synchronously (returns null if not loaded yet) |
| 58 | + */ |
| 59 | +export function getConfig() { |
| 60 | + return cachedConfig; |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * Get API URL (must call loadConfig first) |
| 65 | + */ |
| 66 | +export function getApiUrl() { |
| 67 | + return cachedConfig?.apiUrl || ''; |
| 68 | +} |
| 69 | + |
| 70 | +export default { loadConfig, getConfig, getApiUrl }; |
0 commit comments