Skip to content

Commit 36ca127

Browse files
committed
controllers
1 parent f5ef7b1 commit 36ca127

File tree

6 files changed

+126
-50
lines changed

6 files changed

+126
-50
lines changed

controllers/forecastController.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const fetch = require('node-fetch');
2+
3+
const API_KEY = process.env.OPENWEATHER_API_KEY;
4+
5+
const getForecast = async (req, res) => {
6+
const { lat, lon, units } = req.query;
7+
8+
try {
9+
const response = await fetch(
10+
`https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=${units}&appid=${API_KEY}`
11+
);
12+
13+
if (!response.ok) {
14+
throw new Error('Forecast API response was not ok');
15+
}
16+
17+
const data = await response.json();
18+
res.json(data);
19+
} catch (error) {
20+
console.error('Forecast API Error:', error);
21+
res.status(500).json({ error: 'Failed to fetch forecast data' });
22+
}
23+
};
24+
25+
module.exports = {
26+
getForecast
27+
};

controllers/geocodeController.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const fetch = require('node-fetch');
2+
3+
const API_KEY = process.env.OPENWEATHER_API_KEY;
4+
5+
const searchLocations = async (req, res) => {
6+
const { q } = req.query;
7+
8+
try {
9+
const response = await fetch(
10+
`https://api.openweathermap.org/geo/1.0/direct?q=${q}&limit=5&appid=${API_KEY}`
11+
);
12+
13+
if (!response.ok) {
14+
throw new Error('Geocode API response was not ok');
15+
}
16+
17+
const data = await response.json();
18+
res.json(data);
19+
} catch (error) {
20+
console.error('Geocode API Error:', error);
21+
res.status(500).json({ error: 'Failed to fetch location data' });
22+
}
23+
};
24+
25+
module.exports = {
26+
searchLocations
27+
};

controllers/weatherController.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const fetch = require('node-fetch');
2+
3+
const API_KEY = process.env.OPENWEATHER_API_KEY;
4+
5+
const getCurrentWeather = async (req, res) => {
6+
const { lat, lon, units } = req.query;
7+
8+
try {
9+
const response = await fetch(
10+
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=${units}&appid=${API_KEY}`
11+
);
12+
13+
if (!response.ok) {
14+
throw new Error('Weather API response was not ok');
15+
}
16+
17+
const data = await response.json();
18+
res.json(data);
19+
} catch (error) {
20+
console.error('Weather API Error:', error);
21+
res.status(500).json({ error: 'Failed to fetch weather data' });
22+
}
23+
};
24+
25+
module.exports = {
26+
getCurrentWeather
27+
};

public/src/js/script.js

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -449,10 +449,20 @@ function updateTodayForecast() {
449449
const now = getLocationTime(Math.floor(Date.now() / 1000));
450450
const currentHour = now.getHours();
451451
now.setMinutes(0, 0, 0);
452-
const todayForecasts = forecastData.list.filter(forecast => {
452+
let todayForecasts = forecastData.list.filter(forecast => {
453453
const forecastDate = getLocationTime(forecast.dt);
454454
return forecastDate.toDateString() === now.toDateString();
455455
});
456+
if (todayForecasts.length === 0) {
457+
const sortedForecasts = [...forecastData.list].sort((a, b) => b.dt - a.dt);
458+
const lastForecast = sortedForecasts.find(forecast => {
459+
const forecastDate = getLocationTime(forecast.dt);
460+
return forecastDate <= now;
461+
});
462+
if (lastForecast) {
463+
todayForecasts = [lastForecast];
464+
}
465+
}
456466
todayForecasts.forEach(forecast => {
457467
const hourElement = document.createElement("div");
458468
const forecastTime = getLocationTime(forecast.dt);
@@ -507,14 +517,24 @@ function updateForecast() {
507517
const tempUnit = currentUnit === "metric" ? "°C" : "°F";
508518
if (currentDisplayMode === "all") {
509519
forecastDates.forEach((date) => {
510-
const dayData = dailyForecasts[date];
511-
createDayForecastElement(date, dayData.forecasts, dayData.minTemp, dayData.maxTemp, false, tempUnit);
520+
createDayForecastElement(
521+
date,
522+
dailyForecasts[date].forecasts,
523+
dailyForecasts[date].minTemp,
524+
dailyForecasts[date].maxTemp,
525+
false,
526+
tempUnit
527+
);
512528
});
513-
} else {
529+
} else if (currentDisplayMode === "day" && forecastDates[currentSelectedDay]) {
514530
const selectedDate = forecastDates[currentSelectedDay];
515-
if (selectedDate && dailyForecasts[selectedDate]) {
516-
const dayData = dailyForecasts[selectedDate];
517-
createDayForecastElement(selectedDate, dayData.forecasts, dayData.minTemp, dayData.maxTemp, false, tempUnit);
518-
}
531+
createDayForecastElement(
532+
selectedDate,
533+
dailyForecasts[selectedDate].forecasts,
534+
dailyForecasts[selectedDate].minTemp,
535+
dailyForecasts[selectedDate].maxTemp,
536+
false,
537+
tempUnit
538+
);
519539
}
520540
}

routes/api.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const express = require('express');
2+
const router = express.Router();
3+
const { getCurrentWeather } = require('../controllers/weatherController');
4+
const { getForecast } = require('../controllers/forecastController');
5+
const { searchLocations } = require('../controllers/geocodeController');
6+
7+
router.get('/weather', getCurrentWeather);
8+
router.get('/forecast', getForecast);
9+
router.get('/geocode', searchLocations);
10+
11+
module.exports = router;

server.js

Lines changed: 6 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,24 @@
11
const express = require('express');
22
const cors = require('cors');
33
const path = require('path');
4-
const fetch = require('node-fetch');
54
require('dotenv').config();
65

76
const app = express();
87
const port = process.env.PORT || 3000;
98

9+
// Middleware
1010
app.use(cors());
1111
app.use(express.static('public'));
1212

13-
const API_KEY = process.env.OPENWEATHER_API_KEY;
14-
15-
app.get('/api/weather', async (req, res) => {
16-
const { lat, lon, units } = req.query;
17-
try {
18-
const response = await fetch(
19-
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=${units}&appid=${API_KEY}`
20-
);
21-
const data = await response.json();
22-
res.json(data);
23-
} catch (error) {
24-
res.status(500).json({ error: 'Failed to fetch weather data' });
25-
}
26-
});
27-
28-
app.get('/api/forecast', async (req, res) => {
29-
const { lat, lon, units } = req.query;
30-
try {
31-
const response = await fetch(
32-
`https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=${units}&appid=${API_KEY}`
33-
);
34-
const data = await response.json();
35-
res.json(data);
36-
} catch (error) {
37-
res.status(500).json({ error: 'Failed to fetch forecast data' });
38-
}
39-
});
40-
41-
app.get('/api/geocode', async (req, res) => {
42-
const { q } = req.query;
43-
try {
44-
const response = await fetch(
45-
`https://api.openweathermap.org/geo/1.0/direct?q=${q}&limit=5&appid=${API_KEY}`
46-
);
47-
const data = await response.json();
48-
res.json(data);
49-
} catch (error) {
50-
res.status(500).json({ error: 'Failed to fetch location data' });
51-
}
52-
});
13+
// API Routes
14+
const apiRoutes = require('./routes/api');
15+
app.use('/api', apiRoutes);
5316

17+
// Handle 404s
5418
app.use((req, res) => {
5519
res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
5620
});
5721

5822
app.listen(port, () => {
5923
console.log(`Server running on port ${port}`);
60-
});
24+
});

0 commit comments

Comments
 (0)