local-weather/app/api/location/route.ts
ChrQR 68ffdb26f7
All checks were successful
Docker Build & Publish / Build Docker (push) Successful in 1m6s
Implemented api for google places call
2024-05-18 01:57:46 +02:00

60 lines
1.7 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { coordType, LocationType } from "@/types/types";
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 }
);
}
const placesKey = process.env.PLACES_API;
if (!placesKey) {
console.error("PLACES_API environment variable is not set");
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}`;
console.log("Fetching location");
try {
const res = await fetch(url);
if (!res.ok) {
console.error(`Fetch error: ${res.statusText}`);
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");
return NextResponse.json(
{ error: "Unable to find the address" },
{ status: 404 }
);
}
const locationData: coordType = {
name: data.results[0].formatted_address,
geo: data.results[0].geometry.location,
};
return NextResponse.json(locationData);
} catch (error) {
console.error("Error fetching location:", error);
return NextResponse.json(
{ error: "Error fetching location" },
{ status: 500 }
);
}
}