local-weather/app/api/location/route.ts

60 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2024-05-17 23:57:46 +00:00
import { NextRequest, NextResponse } from "next/server";
import { coordType, LocationType } from "@/types/types";
2024-05-17 23:57:46 +00:00
export async function GET(request: NextRequest) {
const searchParams = new URL(request.url).searchParams;
const searchLocation = searchParams.get("location");
if (!searchLocation) {
return NextResponse.json(
{ error: "Location parameter is required" },
{ status: 400 }
);
}
2024-05-05 20:55:51 +00:00
const placesKey = process.env.PLACES_API;
if (!placesKey) {
console.error("PLACES_API environment variable is not set");
2024-05-17 23:57:46 +00:00
return NextResponse.json(
{ error: "PLACES_API environment variable is not set" },
{ status: 500 }
);
}
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${placesKey}`;
2024-05-17 23:57:46 +00:00
console.log("Fetching location");
try {
const res = await fetch(url);
if (!res.ok) {
console.error(`Fetch error: ${res.statusText}`);
2024-05-17 23:57:46 +00:00
return NextResponse.json(
{ error: "There was an error fetching the data" },
{ status: res.status }
);
}
const data: LocationType = await res.json();
if (!data.results[0]?.formatted_address) {
console.error("Unable to find the address in the response");
2024-05-17 23:57:46 +00:00
return NextResponse.json(
{ error: "Unable to find the address" },
{ status: 404 }
);
}
2024-05-17 23:57:46 +00:00
const locationData: coordType = {
name: data.results[0].formatted_address,
geo: data.results[0].geometry.location,
};
2024-05-17 23:57:46 +00:00
return NextResponse.json(locationData);
} catch (error) {
console.error("Error fetching location:", error);
2024-05-17 23:57:46 +00:00
return NextResponse.json(
{ error: "Error fetching location" },
{ status: 500 }
);
2024-05-17 22:54:39 +00:00
}
}