36 lines
832 B
JavaScript
36 lines
832 B
JavaScript
const express = require("express");
|
|
const axios = require("axios");
|
|
const config = require("../config/api");
|
|
|
|
const router = express.Router();
|
|
|
|
router.get("/", async (req, res) => {
|
|
try {
|
|
const { apiKey, baseUrl, city, units, language } = config.weather;
|
|
if (!apiKey) {
|
|
return res.status(400).json({ message: "OPENWEATHER_API_KEY is not set" });
|
|
}
|
|
|
|
const { q, lat, lon } = req.query;
|
|
const params = {
|
|
appid: apiKey,
|
|
units,
|
|
lang: language,
|
|
};
|
|
|
|
if (lat && lon) {
|
|
params.lat = lat;
|
|
params.lon = lon;
|
|
} else {
|
|
params.q = q || city;
|
|
}
|
|
|
|
const response = await axios.get(`${baseUrl}/weather`, { params });
|
|
res.json(response.data);
|
|
} catch (error) {
|
|
res.status(500).json({ message: "Failed to fetch weather" });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|