import { Router } from 'express'; import https from 'https'; import db from '../db/db'; const router = Router(); function getSetting(key: string): string { return (db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as any)?.value ?? ''; } router.get('/', (_req, res) => { const apiKey = getSetting('weather_api_key').trim(); const location = getSetting('weather_location').trim(); const units = getSetting('weather_units').trim() || 'imperial'; if (!apiKey || !location) { return res.json({ configured: false }); } const url = `https://api.openweathermap.org/data/2.5/weather` + `?q=${encodeURIComponent(location)}` + `&appid=${encodeURIComponent(apiKey)}` + `&units=${encodeURIComponent(units)}`; https.get(url, (apiRes) => { let raw = ''; apiRes.on('data', (chunk: Buffer) => { raw += chunk.toString(); }); apiRes.on('end', () => { try { const data = JSON.parse(raw); if (apiRes.statusCode !== 200) { return res.json({ configured: true, error: data.message ?? 'Weather API error' }); } res.json({ configured: true, city: data.name as string, temp: Math.round(data.main.temp as number), feels_like: Math.round(data.main.feels_like as number), humidity: data.main.humidity as number, description: (data.weather?.[0]?.description ?? '') as string, icon: (data.weather?.[0]?.icon ?? '') as string, units, }); } catch { res.json({ configured: true, error: 'Failed to parse weather response' }); } }); }).on('error', (err: Error) => { res.json({ configured: true, error: err.message }); }); }); export default router;