weather.astro.mjs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. globalThis.process ??= {}; globalThis.process.env ??= {};
  2. export { r as renderers } from '../../chunks/_@astro-renderers_DpxbEuk7.mjs';
  3. const GET = async ({ request }) => {
  4. const url = new URL(request.url);
  5. const city = url.searchParams.get("city");
  6. const lat = url.searchParams.get("lat");
  7. const lon = url.searchParams.get("lon");
  8. const apiKey = url.searchParams.get("apiKey");
  9. const units = url.searchParams.get("units") || "metric";
  10. if (!apiKey) {
  11. return new Response(JSON.stringify({ error: "Missing apiKey parameter" }), {
  12. status: 400,
  13. headers: {
  14. "Content-Type": "application/json"
  15. }
  16. });
  17. }
  18. if (!city && (!lat || !lon)) {
  19. return new Response(
  20. JSON.stringify({ error: "Missing city or lat/lon parameters" }),
  21. {
  22. status: 400,
  23. headers: {
  24. "Content-Type": "application/json"
  25. }
  26. }
  27. );
  28. }
  29. try {
  30. let weatherUrl;
  31. if (lat && lon) {
  32. weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(lon)}&appid=${apiKey}&units=${units}`;
  33. } else {
  34. const req = await fetch(
  35. `http://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=${apiKey}`
  36. );
  37. const json = await req.json();
  38. const lata = json[0]?.lat | 0;
  39. const longa = json[0]?.lon | 0;
  40. weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${encodeURIComponent(lata)}&lon=${encodeURIComponent(longa)}&appid=${apiKey}&units=${units}`;
  41. }
  42. const response = await fetch(weatherUrl);
  43. if (!response.ok) {
  44. console.log(response);
  45. return new Response(
  46. JSON.stringify({ error: "Failed to fetch weather data" }),
  47. {
  48. status: response.status,
  49. headers: {
  50. "Content-Type": "application/json"
  51. }
  52. }
  53. );
  54. }
  55. const data = await response.json();
  56. return new Response(JSON.stringify(data), {
  57. status: 200,
  58. headers: {
  59. "Content-Type": "application/json",
  60. "Cache-Control": "public, max-age=300"
  61. // Cache for 5 minutes
  62. }
  63. });
  64. } catch (error) {
  65. console.error("Weather API error:", error);
  66. return new Response(JSON.stringify({ error: "Internal server error" }), {
  67. status: 500,
  68. headers: {
  69. "Content-Type": "application/json"
  70. }
  71. });
  72. }
  73. };
  74. const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  75. __proto__: null,
  76. GET
  77. }, Symbol.toStringTag, { value: 'Module' }));
  78. const page = () => _page;
  79. export { page };