MolinoPro

places-integration_akill

Master Codebase Guidebook
Markdown + HTML Dev-Docs Renderer - Frontend Client Module

Default Index
Open README.md
Root: README.mdintegrations
Milestones

To adapt your fetchPlaces() function for use in a Next.js 14 environment or within a Google Apps Script (GAS) environment through Next.js, we’ll need to break down the task into two parts: adapting the function for Next.js 14 API deployment and using it within a Next.js app.

Option 1: Running as a Next.js API Route (Server-side):

If you want to use Next.js as your backend and trigger the Google Places API call server-side, you would do this by creating an API route. You can utilize fetch to call Google Maps API and then send the response back to the frontend.

Here’s an example of how you can adapt your function for Next.js API route:

Step 1: Create API route in Next.js (API Route for fetchPlaces) 1. Create a new file for your API route at pages/api/fetchPlaces.js. 2. Write the adapted function for calling Google Places API.

// pages/api/fetchPlaces.js import fetch from 'node-fetch'; // Using native node-fetch to make HTTP requests in Next.js

const GOOGLE_MAPS_API_KEY = 'AIzaSyA27TInoDorHBCM3K5kMlox90bzKaZ3k90';

export default async function handler(req, res) { if (req.method === 'GET') { const query = req.query.query || ''; // Query is passed as a query parameter

const baseUrl = 'https://maps.googleapis.com/maps/api/place/textsearch/json';

const params = {
  key: GOOGLE_MAPS_API_KEY,
  query: query
};

try {
  // Fetch places data from Google Places API
  const response = await fetch(`${baseUrl}?${new URLSearchParams(params)}`);
  const data = await response.json();

  if (data.status !== 'OK') {
    return res.status(400).json({ error: 'Failed to fetch places', details: data });
  }

  // Process results
  const places = data.results.map(place => {
    const name = place.name;
    const location = place.formatted_address || 'Not Available';
    const url = place.place_id ? `https://www.google.com/maps/place/?q=place_id:${place.place_id}` : 'Not Available';
    const details = getPlaceDetails(place.place_id);  // Add the logic for detailed data fetching

    return {
      name,
      location,
      url,
      details
    };
  });

  // Send processed places data back to the client
  return res.status(200).json(places);
} catch (error) {
  console.error('Error fetching places:', error);
  return res.status(500).json({ error: 'Internal Server Error' });
}

} else { return res.status(405).json({ error: 'Method Not Allowed' }); } }

async function getPlaceDetails(placeId) { const baseUrl = 'https://maps.googleapis.com/maps/api/place/details/json'; const params = { place_id: placeId, key: GOOGLE_MAPS_API_KEY, fields: 'name,rating,formatted_phone_number,website,formatted_address' };

try { const response = await fetch(${baseUrl}?${new URLSearchParams(params)}); const data = await response.json();

if (data.status !== 'OK') {
  console.warn('Failed to fetch details for place_id:', placeId);
  return null;
}

const place = data.result;
const phone = place.formatted_phone_number || 'Not Available';
const website = place.website || 'Not Available';
return { phone, website };

} catch (e) { console.error('Error fetching place details for place_id:', placeId, e.message); return null; } }

Key Points: • We’re using node-fetch to make HTTP requests in Next.js. • The fetchPlaces API route accepts a GET request, fetches data from Google Places API, and processes the results. • The API responds with a list of places along with basic details (name, location, etc.).

Step 2: Call API route from the Frontend (Client-side in Next.js) To call this API from the frontend, you can use fetch on your client-side component.

// Example React component in Next.js import { useState, useEffect } from 'react';

function Places() { const [places, setPlaces] = useState([]); const [query, setQuery] = useState(''); // Query input

const fetchPlacesData = async () => { const response = await fetch(/api/fetchPlaces?query=${query}); const data = await response.json(); setPlaces(data); };

useEffect(() => { if (query) { fetchPlacesData(); } }, [query]);

return (

<div> <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search places..." /> <ul> {places.map((place, index) => ( <li key={index}> <a href={place.url} target="_blank" rel="noopener noreferrer">{place.name}</a> <p>{place.location}</p> {place.details && ( <div> <p>Phone: {place.details.phone}</p> <p>Website: {place.details.website}</p> </div> )} </li> ))} </ul> </div> ); }

export default Places;

Option 2: Using Google Apps Script in Next.js Environment:

If you want to keep Google Apps Script running from the backend (which is great for serverless functions), you could deploy your Google Apps Script (GAS) function as an API via Google Apps Script Web App. 1. Deploy your GAS script as a Web App. 2. Invoke the Web App via HTTP requests from Next.js:

const GAS_URL = 'YOUR_GAS_WEB_APP_URL';

async function fetchPlacesFromGAS(query) { const response = await fetch(${GAS_URL}?query=${query}); const data = await response.json(); return data; }

In this case, GAS handles the fetching and processing of data, and Next.js calls it via an HTTP request.

Conclusion: 1. Next.js API Route: If you want to fully integrate the process in Next.js, the first approach (using Next.js API routes with fetch) is the most flexible. 2. Google Apps Script Web App: If you prefer to continue using your existing Google Apps Script function, you can deploy it as a Web App and call it from Next.js.

Both methods will allow you to adapt your pipeline to Next.js! Let me know if you’d like further details on either approach!