local-weather/app/api/location/route.ts
ChrQR 31f633e982
Some checks failed
Docker Build & Publish / Build Docker (push) Failing after 51s
Implemented api for the weather call.
2024-05-18 01:50:05 +02:00

37 lines
1.1 KiB
TypeScript

"use server";
import { Forecast, LocationType, coordType } from "@/types/types";
export async function getLocation(searchLocation: string): Promise<coordType> {
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");
}
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${placesKey}`;
console.log(`Fetching location`);
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");
}
}