Implemented api for google places call
All checks were successful
Docker Build & Publish / Build Docker (push) Successful in 1m6s

This commit is contained in:
ChrQR 2024-05-18 01:57:46 +02:00
parent 31f633e982
commit 68ffdb26f7
2 changed files with 62 additions and 12 deletions

View File

@ -1,36 +1,59 @@
"use server";
import { NextRequest, NextResponse } from "next/server";
import { coordType, LocationType } from "@/types/types";
import { Forecast, LocationType, coordType } 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 }
);
}
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");
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`);
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`);
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");
throw new Error(`Unable to find the address`);
return NextResponse.json(
{ error: "Unable to find the address" },
{ status: 404 }
);
}
return {
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);
throw new Error("Error fetching location");
return NextResponse.json(
{ error: "Error fetching location" },
{ status: 500 }
);
}
}

View File

@ -1,12 +1,13 @@
"use client";
import React, { useContext, useState } from "react";
import { LocationContext } from "@/context/LocationContext";
import { getLocation } from "@/app/actions/actions";
import { coordType } from "@/types/types";
export default function LocationSearch() {
const [searchLocation, setSearchLocation] = useState("");
const { setGeoLocation } = useContext(LocationContext);
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchLocation(e.target.value);
@ -15,13 +16,38 @@ export default function LocationSearch() {
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setPending(true);
setError(null);
try {
const coordinates = await getLocation(searchLocation);
if (coordinates) {
setGeoLocation(coordinates);
}
} catch (error) {
console.error("Error fetching location:", error);
}
setError("Error fetching location");
} finally {
setPending(false);
}
};
const getLocation = async (
searchLocation: string
): Promise<coordType | null> => {
try {
const response = await fetch(
`/api/location?location=${encodeURIComponent(searchLocation)}`
);
if (!response.ok) {
throw new Error("Failed to fetch the location data");
}
const data = await response.json();
return data;
} catch (error: any) {
console.error("Error fetching location:", error);
setError(error.message);
return null;
}
};
return (
@ -37,6 +63,7 @@ export default function LocationSearch() {
disabled={pending}
aria-label="Enter location to query the weather"
/>
{error && <p className="text-red-500">{error}</p>}
</form>
);
}