2024-05-17 22:54:39 +00:00
|
|
|
"use server";
|
2024-05-17 23:02:29 +00:00
|
|
|
|
2024-05-12 05:32:14 +00:00
|
|
|
import { Forecast, LocationType, coordType } from "@/types/types";
|
2024-05-05 20:55:51 +00:00
|
|
|
|
2024-05-17 22:54:39 +00:00
|
|
|
export async function getLocation(searchLocation: string): Promise<coordType> {
|
2024-05-17 23:02:29 +00:00
|
|
|
const placesKey = process.env.PLACES_API;
|
|
|
|
if (!placesKey) {
|
|
|
|
console.error("PLACES_API environment variable is not set");
|
|
|
|
throw new Error("PLACES_API environment variable is not set");
|
2024-05-06 21:22:57 +00:00
|
|
|
}
|
2024-05-17 23:02:29 +00:00
|
|
|
|
|
|
|
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${placesKey}`;
|
2024-05-17 23:12:41 +00:00
|
|
|
console.log(`Fetching location`);
|
2024-05-17 23:02:29 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
const res = await fetch(url);
|
|
|
|
if (!res.ok) {
|
|
|
|
console.error(`Fetch error: ${res.statusText}`);
|
|
|
|
throw new Error(`There was an error fetching the data`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const data: LocationType = await res.json();
|
|
|
|
if (!data.results[0]?.formatted_address) {
|
|
|
|
console.error("Unable to find the address in the response");
|
|
|
|
throw new Error(`Unable to find the address`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
name: data.results[0].formatted_address,
|
|
|
|
geo: data.results[0].geometry.location,
|
|
|
|
};
|
|
|
|
} catch (error) {
|
|
|
|
console.error("Error fetching location:", error);
|
|
|
|
throw new Error("Error fetching location");
|
2024-05-17 22:54:39 +00:00
|
|
|
}
|
|
|
|
}
|
2024-05-06 21:22:57 +00:00
|
|
|
|
2024-05-17 22:54:39 +00:00
|
|
|
export async function getHourlyForecast(
|
|
|
|
geoLocation: coordType
|
|
|
|
): Promise<Forecast> {
|
|
|
|
const { lat, lng } = geoLocation.geo;
|
|
|
|
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
|
|
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}¤t=temperature_2m,apparent_temperature,is_day,precipitation,rain,showers,snowfall,weather_code,cloud_cover,wind_speed_10m,wind_direction_10m&hourly=temperature_2m,apparent_temperature,precipitation_probability,precipitation,weather_code,wind_speed_10m,is_day&daily=weather_code,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,sunrise,sunset,daylight_duration,sunshine_duration,uv_index_max,precipitation_sum,precipitation_hours,wind_speed_10m_max&timezone=${tz}`;
|
|
|
|
const res = await fetch(url);
|
|
|
|
if (!res.ok) {
|
|
|
|
throw new Error(`Failed to fetch the weather data`);
|
|
|
|
}
|
|
|
|
const data: Forecast = await res.json();
|
|
|
|
return data;
|
2024-05-09 21:40:14 +00:00
|
|
|
}
|