local-weather/app/actions.ts

42 lines
1.6 KiB
TypeScript

'use server'
import { Forecast, HourlyForecast, LocationType, coordType } from "@/types/types";
//takes address and returns coords in obj as {lat: number, lng: number}
export async function getLocation(searchLocation: string): Promise<coordType>{
const placesKey = process.env.PLACES_API;
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${placesKey}`;
const res = await fetch(url);
if (!res.ok) {
throw new Error(`There was an error fetching the data`);
}
const data: LocationType = await res.json();
return data.results[0].geometry.location;
}
// takes coordinates in coordType format and returns json with weather forecast.
export async function getForecast(geoLocation: coordType): Promise<Forecast> {
const { lat, lng } = geoLocation;
const appId = process.env.WEATHER_API;
const res = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${appId}`
);
if (!res.ok) {
throw new Error(`Failed to fetch the weather data`);
}
const data: Forecast = await res.json();
return data;
}
export async function getHourlyForecast(geoLocation: coordType): Promise<HourlyForecast> {
const { lat, lng } = geoLocation;
const appId = process.env.WEATHER_API;
const res = await fetch(
`https://pro.openweathermap.org/data/2.5/forecast/hourly?lat=${lat}&lon=${lng}&appid=${appId}&mode=json&`
);
if (!res.ok) {
throw new Error(`Failed to fetch the weather data`);
}
const data: HourlyForecast = await res.json();
return data;
}