-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
83 lines (68 loc) · 2.39 KB
/
Copy pathserver.js
File metadata and controls
83 lines (68 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
const OPENWEATHER_KEY = process.env.OPENWEATHER_KEY;
if (!OPENWEATHER_KEY) {
console.error('Error: OPENWEATHER_KEY not found in .env');
process.exit(1);
}
console.log('OpenWeather Key Loaded:', OPENWEATHER_KEY ? 'Yes' : 'No');
// Serve static files from public/
app.use(express.static(path.join(__dirname, 'public')));
// In-memory cache
const cache = {};
// Validate city names
function isValidCity(value) {
return /^[a-zA-Z0-9\s,.'-]{1,100}$/.test(value);
}
// API endpoint
app.get('/api/weather', async (req, res) => {
const city = (req.query.city || '').trim();
if (!isValidCity(city)) {
return res.status(400).json({ error: 'Invalid city name' });
}
const cityKey = city.toLowerCase();
// Return cached response if available and fresh
if (cache[cityKey] && Date.now() - cache[cityKey].timestamp < 60_000) {
return res.json({ ...cache[cityKey].data, fromCache: true });
}
try {
// Use the official OpenWeatherMap API endpoint and the configured key
const response = await axios.get('https://api.openweathermap.org/data/2.5/weather', {
params: {
q: city,
appid: OPENWEATHER_KEY,
units: 'metric'
}
});
const data = {
name: response.data.name,
country: response.data.sys.country,
weather: {
main: response.data.weather[0].main,
description: response.data.weather[0].description,
icon: response.data.weather[0].icon
},
main: response.data.main,
wind: response.data.wind
};
cache[cityKey] = { data, timestamp: Date.now() };
res.json(data);
} catch (err) {
const status = err.response?.status || 502;
const msg = err.response?.data?.message || err.message;
// Provide clearer message when the API key is invalid
if (status === 401) {
console.error('OpenWeatherMap API unauthorized (check OPENWEATHER_KEY):', msg);
return res.status(401).json({ error: 'Invalid OpenWeather API key. Check your OPENWEATHER_KEY in .env' });
}
console.error('OpenWeatherMap API error:', status, msg);
res.status(status).json({ error: `OpenWeatherMap API error: ${msg}` });
}
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});