95 lines
2.3 KiB
TypeScript
95 lines
2.3 KiB
TypeScript
import prisma from './db';
|
|
|
|
export interface AppSettings {
|
|
id: string;
|
|
apiKey: string | null;
|
|
selectedLeague: string;
|
|
leagueId: number;
|
|
season: number;
|
|
siteName: string;
|
|
primaryColor: string;
|
|
secondaryColor: string;
|
|
showLiveMatches: boolean;
|
|
showStandings: boolean;
|
|
showTopScorers: boolean;
|
|
showRecentResults: boolean;
|
|
showUpcoming: boolean;
|
|
refreshInterval: number;
|
|
}
|
|
|
|
const defaultSettings: AppSettings = {
|
|
id: 'main',
|
|
apiKey: null,
|
|
selectedLeague: 'primeira_liga',
|
|
leagueId: 94,
|
|
season: 2024,
|
|
siteName: 'Primeira Liga Stats',
|
|
primaryColor: '#E42518',
|
|
secondaryColor: '#006600',
|
|
showLiveMatches: true,
|
|
showStandings: true,
|
|
showTopScorers: true,
|
|
showRecentResults: true,
|
|
showUpcoming: true,
|
|
refreshInterval: 300,
|
|
};
|
|
|
|
// In-memory cache to avoid a DB round-trip on every API call
|
|
let settingsCache: AppSettings | null = null;
|
|
let settingsCacheAt = 0;
|
|
const SETTINGS_CACHE_TTL = 30_000; // 30 seconds
|
|
|
|
export async function getSettings(): Promise<AppSettings> {
|
|
// Return from cache if still fresh
|
|
if (settingsCache && Date.now() - settingsCacheAt < SETTINGS_CACHE_TTL) {
|
|
return settingsCache;
|
|
}
|
|
|
|
try {
|
|
let settings = await prisma.settings.findUnique({
|
|
where: { id: 'main' },
|
|
});
|
|
|
|
if (!settings) {
|
|
// Create default settings with API key from env
|
|
settings = await prisma.settings.create({
|
|
data: {
|
|
...defaultSettings,
|
|
apiKey: process.env.API_FOOTBALL_API_KEY || null,
|
|
},
|
|
});
|
|
}
|
|
|
|
settingsCache = settings as AppSettings;
|
|
settingsCacheAt = Date.now();
|
|
return settingsCache;
|
|
} catch (error) {
|
|
console.error('Failed to get settings:', error);
|
|
return {
|
|
...defaultSettings,
|
|
apiKey: process.env.API_FOOTBALL_API_KEY || null,
|
|
};
|
|
}
|
|
}
|
|
|
|
/** Call this after any settings update to bust the cache. */
|
|
export function invalidateSettingsCache() {
|
|
settingsCache = null;
|
|
settingsCacheAt = 0;
|
|
}
|
|
|
|
export function getLeagueConfig(selectedLeague: string) {
|
|
if (selectedLeague === 'euro_2026') {
|
|
return {
|
|
leagueId: 4, // EURO Championship
|
|
season: 2024, // Euro 2024 (most recent)
|
|
name: 'UEFA Euro 2024',
|
|
};
|
|
}
|
|
return {
|
|
leagueId: 94, // Portuguese Primeira Liga
|
|
season: 2024,
|
|
name: 'Primeira Liga',
|
|
};
|
|
}
|