feat: implement weather fetching API and update frontend components for improved user experience
This commit is contained in:
63
backend/routes/api.js
Normal file
63
backend/routes/api.js
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import { Router } from "express";
|
||||||
|
import dotenv from "dotenv";
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
router.get("/fetchWeather", async (req, res) => {
|
||||||
|
const city = req.query.city;
|
||||||
|
const units = req.query.units;
|
||||||
|
const apiKey = process.env.API_KEY;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const locationResponse = await fetch(
|
||||||
|
`https://api.openweathermap.org/geo/1.0/direct?q=${city}&appid=${apiKey}`
|
||||||
|
);
|
||||||
|
if (!locationResponse.ok) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error: "Error fetching location data. (Error: x32)",
|
||||||
|
success: "false",
|
||||||
|
data: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const location = await locationResponse.json();
|
||||||
|
if (!location || !location[0]) {
|
||||||
|
return res.status(404).json({
|
||||||
|
error: "Location not found.",
|
||||||
|
success: "false",
|
||||||
|
data: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lat = location[0].lat;
|
||||||
|
const lon = location[0].lon;
|
||||||
|
|
||||||
|
const weatherResponse = await fetch(
|
||||||
|
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=${units}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!weatherResponse.ok) {
|
||||||
|
return res.status(500).json({
|
||||||
|
error: "Unexpected error! (Error: x33)",
|
||||||
|
success: "false",
|
||||||
|
data: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const weather = await weatherResponse.json();
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
error: "false",
|
||||||
|
success: "Weather data fetched successfully!",
|
||||||
|
data: weather,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({
|
||||||
|
error: "Server error",
|
||||||
|
success: "false",
|
||||||
|
data: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
@@ -1,7 +1,7 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import cors from "cors";
|
import cors from "cors";
|
||||||
import env from "dotenv";
|
import apiRouter from "./routes/api.js";
|
||||||
env.config();
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const port = 7001;
|
const port = 7001;
|
||||||
|
|
||||||
@@ -10,6 +10,8 @@ app.use(express.urlencoded({ extended: true }));
|
|||||||
app.set("view engine", "ejs");
|
app.set("view engine", "ejs");
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
|
app.use("/api", apiRouter);
|
||||||
|
|
||||||
app.get("/", (req, res) => {
|
app.get("/", (req, res) => {
|
||||||
res.render("index.ejs", { title: port });
|
res.render("index.ejs", { title: port });
|
||||||
});
|
});
|
||||||
|
@@ -1,11 +1,12 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Backend | <%= title %></title>
|
<title>Backend | <%= title %></title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
You have reached the backend views index page.
|
<h1>You have reached the backend views index page!</h1>
|
||||||
</body>
|
<p>Currently, there is nothing to display!</p>
|
||||||
</html>
|
</body>
|
||||||
|
</html>
|
||||||
|
@@ -1,26 +1,26 @@
|
|||||||
services:
|
services:
|
||||||
frontend:
|
# frontend:
|
||||||
container_name: weather-frontend
|
# container_name: weather-frontend
|
||||||
build: ./frontend
|
# build: ./frontend
|
||||||
|
# ports:
|
||||||
|
# - "7002:7002"
|
||||||
|
# # networks:
|
||||||
|
# # - proxynet
|
||||||
|
# environment:
|
||||||
|
# - CHOKIDAR_USEPOLLING=true
|
||||||
|
# volumes:
|
||||||
|
# - ./frontend:/app
|
||||||
|
# - /app/node_modules
|
||||||
|
# restart: unless-stopped
|
||||||
|
backend:
|
||||||
|
container_name: weather-backend
|
||||||
|
build: ./backend
|
||||||
ports:
|
ports:
|
||||||
- "7002:7002"
|
- "7001:7001"
|
||||||
networks:
|
|
||||||
- proxynet
|
|
||||||
environment:
|
|
||||||
- CHOKIDAR_USEPOLLING=true
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./frontend:/app
|
- ./backend:/app
|
||||||
- /app/node_modules
|
- /app/node_modules
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
# backend:
|
#networks:
|
||||||
# container_name: backend
|
# proxynet:
|
||||||
# build: ./backend
|
# external: true
|
||||||
# ports:
|
|
||||||
# - "7001:7001"
|
|
||||||
#volumes:
|
|
||||||
# - ./backend:/bikelane-backend
|
|
||||||
# restart: unless-stopped
|
|
||||||
|
|
||||||
networks:
|
|
||||||
proxynet:
|
|
||||||
external: true
|
|
||||||
|
@@ -47,7 +47,7 @@ const ChangePreferences: React.FC<Props> = ({ onClose }) => {
|
|||||||
Temperature Unit
|
Temperature Unit
|
||||||
</label>
|
</label>
|
||||||
<select
|
<select
|
||||||
className="w-full border-2 border-blue-200 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 transition"
|
className="cursor-pointer w-full border-2 border-blue-200 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 transition"
|
||||||
value={unit}
|
value={unit}
|
||||||
onChange={(e) => setUnit(e.target.value)}
|
onChange={(e) => setUnit(e.target.value)}
|
||||||
>
|
>
|
||||||
@@ -58,12 +58,12 @@ const ChangePreferences: React.FC<Props> = ({ onClose }) => {
|
|||||||
</div>
|
</div>
|
||||||
{/* Theme */}
|
{/* Theme */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-semibold text-gray-700 mb-2 items-center gap-2">
|
<label className="cursor-pointer block text-sm font-semibold text-gray-700 mb-2 items-center gap-2">
|
||||||
<SunMoon />
|
<SunMoon />
|
||||||
Theme
|
Theme
|
||||||
</label>
|
</label>
|
||||||
<select
|
<select
|
||||||
className="w-full border-2 border-blue-200 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 transition"
|
className="cursor-pointer w-full border-2 border-blue-200 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 transition"
|
||||||
value={theme}
|
value={theme}
|
||||||
onChange={(e) => setTheme(e.target.value)}
|
onChange={(e) => setTheme(e.target.value)}
|
||||||
>
|
>
|
||||||
@@ -77,7 +77,7 @@ const ChangePreferences: React.FC<Props> = ({ onClose }) => {
|
|||||||
{/* Submit */}
|
{/* Submit */}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="w-full bg-gradient-to-r from-blue-600 to-blue-400 text-white py-3 rounded-xl font-bold text-lg shadow-lg hover:from-blue-700 hover:to-blue-500 transition-all focus:outline-none focus:ring-2 focus:ring-blue-400"
|
className="cursor-pointer w-full bg-gradient-to-r from-blue-600 to-blue-400 text-white py-3 rounded-xl font-bold text-lg shadow-lg hover:from-blue-700 hover:to-blue-500 transition-all focus:outline-none focus:ring-2 focus:ring-blue-400"
|
||||||
>
|
>
|
||||||
Save Preferences
|
Save Preferences
|
||||||
</button>
|
</button>
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import ChangeAPI from "./ChangeAPI";
|
import ChangeAPI from "./ChangeAPI";
|
||||||
import ChangePreferences from "./ChangePreferences";
|
import ChangePreferences from "./ChangePreferences";
|
||||||
|
import { myToast } from "../utils/toastify";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import Cookies from "js-cookie";
|
import Cookies from "js-cookie";
|
||||||
import logo from "../assets/cloud-sun-fill.png";
|
import logo from "../assets/cloud-sun-fill.png";
|
||||||
@@ -21,15 +22,15 @@ const Header: React.FC = () => {
|
|||||||
className="w-10 h-10 drop-shadow-lg"
|
className="w-10 h-10 drop-shadow-lg"
|
||||||
/>
|
/>
|
||||||
<h1 className="text-4xl font-extrabold tracking-wide drop-shadow-lg">
|
<h1 className="text-4xl font-extrabold tracking-wide drop-shadow-lg">
|
||||||
Weather App
|
Weather App - <strong>Web</strong>
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
{" "}
|
{" "}
|
||||||
{/* Added container for buttons */}
|
{/* Added container for buttons */}
|
||||||
<button
|
<button
|
||||||
className="bg-white text-blue-700 font-bold px-6 py-3 rounded-xl shadow-lg hover:bg-blue-100 transition-all border border-blue-200 flex items-center gap-2"
|
className="bg-gray-200 text-gray-400 font-bold px-6 py-3 rounded-xl shadow-lg border border-gray-300 flex items-center gap-2 cursor-not-allowed opacity-60"
|
||||||
onClick={() => setApiCard(true)}
|
onClick={() => myToast("You don't need to set an API Key!", "info")}
|
||||||
>
|
>
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<KeyRound />
|
<KeyRound />
|
||||||
@@ -37,7 +38,7 @@ const Header: React.FC = () => {
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
className="bg-white text-blue-700 font-bold px-6 py-3 rounded-xl shadow-lg hover:bg-blue-100 transition-all border border-blue-200 flex items-center gap-2"
|
className="cursor-pointer bg-white text-blue-700 font-bold px-6 py-3 rounded-xl shadow-lg hover:bg-blue-100 transition-all border border-blue-200 flex items-center gap-2"
|
||||||
onClick={() => setPreferencesCard(true)}
|
onClick={() => setPreferencesCard(true)}
|
||||||
>
|
>
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
@@ -50,7 +51,7 @@ const Header: React.FC = () => {
|
|||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
>
|
>
|
||||||
<button className="bg-white text-blue-700 font-bold px-6 py-3 rounded-xl shadow-lg hover:bg-blue-100 transition-all border border-blue-200 flex items-center gap-2">
|
<button className="cursor-help bg-white text-blue-700 font-bold px-6 py-3 rounded-xl shadow-lg hover:bg-blue-100 transition-all border border-blue-200 flex items-center gap-2">
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
<Github /> Docs
|
<Github /> Docs
|
||||||
</span>
|
</span>
|
||||||
|
@@ -1,7 +1,6 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { fetchWeather } from "../utils/apiFunc";
|
import { fetchWeather } from "../utils/apiFunc";
|
||||||
import Cookies from "js-cookie";
|
|
||||||
import { toast } from "react-toastify";
|
import { toast } from "react-toastify";
|
||||||
import WeatherData from "./WeatherData";
|
import WeatherData from "./WeatherData";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
@@ -10,7 +9,6 @@ import { X } from "lucide-react";
|
|||||||
const WeatherCard: React.FC = () => {
|
const WeatherCard: React.FC = () => {
|
||||||
const [city, setCity] = useState("");
|
const [city, setCity] = useState("");
|
||||||
const [weatherData, setWeatherData] = useState(false);
|
const [weatherData, setWeatherData] = useState(false);
|
||||||
const getAPIKey = () => Cookies.get("apiKey") || "";
|
|
||||||
const getUnit = () => localStorage.getItem("unit") || "metric";
|
const getUnit = () => localStorage.getItem("unit") || "metric";
|
||||||
|
|
||||||
const handleCityChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
const handleCityChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
@@ -19,8 +17,9 @@ const WeatherCard: React.FC = () => {
|
|||||||
|
|
||||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
setWeatherData(false);
|
||||||
toast
|
toast
|
||||||
.promise(fetchWeather(city, getAPIKey(), getUnit()), {
|
.promise(fetchWeather(city, getUnit()), {
|
||||||
pending: "Fetching weather data...",
|
pending: "Fetching weather data...",
|
||||||
success: "Weather data loaded successfully!",
|
success: "Weather data loaded successfully!",
|
||||||
error:
|
error:
|
||||||
@@ -52,6 +51,9 @@ const WeatherCard: React.FC = () => {
|
|||||||
<p className="mb-2 text-gray-600">
|
<p className="mb-2 text-gray-600">
|
||||||
Current weather will be displayed here.
|
Current weather will be displayed here.
|
||||||
</p>
|
</p>
|
||||||
|
<p className="mb-2 text-gray-600">
|
||||||
|
<strong>You don't need an API Key!</strong>
|
||||||
|
</p>
|
||||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4 mt-4">
|
<form onSubmit={handleSubmit} className="flex flex-col gap-4 mt-4">
|
||||||
<label htmlFor="city" className="font-medium text-gray-700">
|
<label htmlFor="city" className="font-medium text-gray-700">
|
||||||
Enter City:
|
Enter City:
|
||||||
@@ -66,10 +68,10 @@ const WeatherCard: React.FC = () => {
|
|||||||
required
|
required
|
||||||
className="border border-blue-300 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-400 bg-blue-50 text-blue-900 font-mono"
|
className="border border-blue-300 rounded-xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-400 bg-blue-50 text-blue-900 font-mono"
|
||||||
/>
|
/>
|
||||||
<div className="flex items-center gap-2">
|
<div className="cursor-pointer flex items-center gap-2">
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
className="flex-1 bg-gradient-to-r from-blue-600 to-blue-400 text-white font-bold px-4 py-3 rounded-xl shadow-lg hover:from-blue-700 hover:to-blue-500 transition-all"
|
className="cursor-pointer flex-1 bg-gradient-to-r from-blue-600 to-blue-400 text-white font-bold px-4 py-3 rounded-xl shadow-lg hover:from-blue-700 hover:to-blue-500 transition-all"
|
||||||
>
|
>
|
||||||
Get Weather
|
Get Weather
|
||||||
</button>
|
</button>
|
||||||
@@ -80,7 +82,7 @@ const WeatherCard: React.FC = () => {
|
|||||||
setWeatherData(false);
|
setWeatherData(false);
|
||||||
localStorage.removeItem("weather");
|
localStorage.removeItem("weather");
|
||||||
}}
|
}}
|
||||||
className="flex-shrink-0 bg-red-500 hover:bg-red-600 text-white rounded-xl p-3 shadow-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-red-400"
|
className="cursor-pointer flex-shrink-0 bg-red-500 hover:bg-red-600 text-white rounded-xl p-3 shadow-lg transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-red-400"
|
||||||
aria-label="Close weather data"
|
aria-label="Close weather data"
|
||||||
>
|
>
|
||||||
<X />
|
<X />
|
||||||
|
@@ -1,36 +1,30 @@
|
|||||||
import { myToast } from "./toastify";
|
import { myToast } from "./toastify";
|
||||||
import Cookies from "js-cookie";
|
|
||||||
|
|
||||||
export const fetchWeather = async (
|
export const fetchWeather = async (city: string, units: string) => {
|
||||||
city: string,
|
try {
|
||||||
apiKey: string,
|
const response = await fetch(
|
||||||
units: string
|
`http://localhost:7001/api/fetchWeather?city=${encodeURIComponent(
|
||||||
) => {
|
city
|
||||||
// Get location data
|
)}&units=${encodeURIComponent(units)}`,
|
||||||
const location = await fetch(
|
{
|
||||||
`https://api.openweathermap.org/geo/1.0/direct?q=${city}&appid=${apiKey}`
|
method: "GET",
|
||||||
).then((response) => {
|
headers: {
|
||||||
if (response.status === 401) {
|
"Content-Type": "application/json",
|
||||||
if (Cookies.get("apiKey") === undefined || Cookies.get("apiKey") === "") {
|
},
|
||||||
myToast("You have to enter an API key!", "error");
|
|
||||||
} else {
|
|
||||||
myToast(
|
|
||||||
"You are not authorized to access this resource. Please check your API key. (Error: x4010)",
|
|
||||||
"error"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
} else if (response.ok) {
|
);
|
||||||
return response.json();
|
|
||||||
} else {
|
|
||||||
myToast("Error fetching location data. (Error: x32)", "error");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const lat = location[0].lat;
|
|
||||||
const lon = location[0].lon;
|
|
||||||
|
|
||||||
// Get weather data
|
const responseData = await response.json();
|
||||||
const weather = await fetch(
|
|
||||||
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=${units}`
|
if (!response.ok) {
|
||||||
).then((response) => response.json());
|
myToast(responseData.error, "error");
|
||||||
localStorage.setItem("weather", JSON.stringify(weather));
|
return;
|
||||||
|
}
|
||||||
|
localStorage.setItem("weather", JSON.stringify(responseData.data));
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
const errorMsg = JSON.stringify(error);
|
||||||
|
myToast(errorMsg, "error");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user