-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
170 lines (145 loc) · 5.1 KB
/
server.js
File metadata and controls
170 lines (145 loc) · 5.1 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"use strict";
require('dotenv').config();
const express = require("express");
const app = express();
const path = require("path");
const port = 1776;
const cors = require("cors");
app.use(cors());
const api_key = process.env.WEATHER_API_KEY; // Getting API key from .env
// Define the API URL for the weather forecast
const apiUrl = "https://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid={your-api-key}&units=imperal";
// Serve front-end content in the public directory
app.use("", express.static(path.join(__dirname, "./public")));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
// A demo Current weather object to testing & debugging
let demoCurrentWeather = {
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
],
"main": {
"temp": 22.08,
"feels_like": 13.62,
"temp_min": 20.48,
"temp_max": 24.03,
"pressure": 1028,
"humidity": 68
},
"visibility": 10000,
"wind": {
"speed": 6.91,
"deg": 350
},
"clouds": {
"all": 100
},
"dt": 1740000984,
"sys": {
"type": 2,
"id": 2020758,
"country": "US",
"sunrise": 1739968039,
"sunset": 1740007475
},
"timezone": -18000,
"id": 4304058,
"name": "Bardstown",
"cod": 200
};
// Calls external weather api using lattitude and longitude parameters -- returns weather Data or error
async function getWeather(lat, lon) {
var apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=imperial&appid=${api_key}`;
try {
let response = await fetch(apiUrl);
let data = await response.json();
return data; // Returns JSON Weather Data
} catch (error) {
console.error("Error fetching weather data:", error);
}
}
// Calls external weather api using city -- returns weather Data or error
async function getWeatherByCity(city){
var apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&appid=${api_key}`;
try{
let response = await fetch(apiUrl);
let data = await response.json();
return data;
}
catch (error){
console.error(`Error fetching Weather for ${city}`)
}
}
// Calls external weather API for 5-day forecast using latitude and longitude -- returns weather Data or error
async function getFiveDayForecast(lat, lon) {
const apiUrl = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=imperial&appid=${api_key}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
return data; // Returns 5-day weather forecast data
} catch (error) {
console.error("Error fetching 5-day forecast data:", error);
throw error; // Propagate the error to the calling function
}
}
// Calls external weather API for 5-day forecast using city -- returns weather Data or error
async function getFiveDayForecastByCity(city) {
const apiUrl = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&units=imperial&appid=${api_key}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
return data; // Returns weather data for the next 5 days (every 3 hours)
} catch (error) {
console.error(`Error fetching 5-day forecast for ${city}:`, error);
throw error; // Propagate the error to the calling function
}
}
// Define the routes
// Returns 5-day forecast based on Latitude and Longitude values
app.get('/api/forecast', async function (req, res) {
const { lat, lon } = req.query;
try {
const forecastData = await getFiveDayForecast(lat, lon);
res.status(200).json(forecastData);
} catch (error) {
res.status(500).json({ error: 'Failed to get weather data' });
}
});
// Returns 5-day forecast based on City
app.get('/api/forecast_by_city', async function (req, res) {
const city = req.query.city;
try {
const forecastData = await getFiveDayForecastByCity(city);
res.status(200).json(forecastData);
} catch (error) {
res.status(500).json({ error: 'Failed to get 5-day forecast data' });
}
});
// Returns Current Weather Based on Latitude and Longitude values
app.get('/api/weather', async function (req, res) {
try {
let weatherData = await getWeather(req.query.lat, req.query.lon);
res.status(200).json(weatherData);
} catch {
res.status(500).json({ error: 'Failed to get weather Data' });
}
});
// Returns Current Weather Based on City
app.get('/api/weather_by_city', async function (req, res) {
try {
let weatherData = await getWeatherByCity(req.query.city);
res.status(200).json(weatherData);
} catch {
res.status(500).json({ error: 'Failed to get weather Data' });
}
});
// Serve the whole app
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
console.log("Press Ctrl+C to end this process.");
});