/** * Config route handler * Handles configuration get/update and client-side config */ const fs = require('fs'); const path = require('path'); /** * Handle GET /api/config endpoint * @param {http.IncomingMessage} req - HTTP request object * @param {http.ServerResponse} res - HTTP response object * @param {Object} config - Application configuration */ function handleGetConfig(req, res, config) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(config)); } /** * Handle POST /api/config/update endpoint * @param {http.IncomingMessage} req - HTTP request object * @param {http.ServerResponse} res - HTTP response object * @param {Object} config - Application configuration (will be modified) */ function handleUpdateConfig(req, res, config) { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { try { const newConfig = JSON.parse(body); if (newConfig.sites) { // Update config object (passed by reference) Object.assign(config, newConfig); // Save to file const configPath = path.join('config', 'sites.json'); fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ success: true, message: 'Configuration updated' })); } else { throw new Error('Invalid configuration format'); } } catch (error) { console.error('Error updating configuration:', error); res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: error.message })); } }); } /** * Handle GET /api/config/client endpoint * Returns client-side configuration (API keys, default location) * @param {http.IncomingMessage} req - HTTP request object * @param {http.ServerResponse} res - HTTP response object */ function handleClientConfig(req, res) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ openweathermapApiKey: process.env.OPENWEATHERMAP_API_KEY || '', defaultLocation: { latitude: parseFloat(process.env.DEFAULT_LATITUDE) || 59.3293, longitude: parseFloat(process.env.DEFAULT_LONGITUDE) || 18.0686, name: process.env.DEFAULT_LOCATION_NAME || 'Stockholm' } })); } module.exports = { handleGetConfig, handleUpdateConfig, handleClientConfig };