Perplexica/ui/lib/serverEnvironment.ts

36 lines
1 KiB
TypeScript
Raw Normal View History

2024-08-15 23:05:14 +01:00
import { NextResponse } from 'next/server';
2024-08-15 23:40:42 +01:00
import process from 'process';
2024-08-15 23:05:14 +01:00
// In-memory cache for configuration data
2024-08-15 23:40:42 +01:00
let cachedConfig: { [key: string]: string } ;
2024-08-15 23:05:14 +01:00
let cacheTimestamp: number | null = null;
const CACHE_DURATION_MS = 5 * 60 * 1000; // Cache duration: 5 minutes
async function fetchConfig() {
try {
const response = await fetch('/api/config');
if (response.ok) {
const data = await response.json();
cachedConfig = data;
cacheTimestamp = Date.now();
} else {
throw new Error('Failed to fetch config');
}
} catch (error) {
console.error('Error fetching config:', error);
throw error;
}
}
2024-08-15 23:40:42 +01:00
export async function await getServerEnv(envVar: string): Promise<string> {
2024-08-15 23:05:14 +01:00
// Check if the cache is still valid
if (cachedConfig && cacheTimestamp && Date.now() - cacheTimestamp < CACHE_DURATION_MS) {
2024-08-15 23:40:42 +01:00
return cachedConfig[envVar] || process.env[envVar];
2024-08-15 23:05:14 +01:00
}
// Fetch and cache the config if not in cache or cache is expired
await fetchConfig();
2024-08-15 23:40:42 +01:00
return cachedConfig[envVar];
2024-08-15 23:05:14 +01:00
}