Created
August 15, 2024 15:43
-
-
Save NateSkiles/d88d0e59e92ad230f803767ed929b90d to your computer and use it in GitHub Desktop.
Code for Zapier Action
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const { API_KEY, QUERY, LOCATION, LINK_TO_MATCH } = inputData; | |
| // Fetch Google Search Results from SerpApi | |
| async function fetchGoogleSearchResults(query, location) { | |
| try { | |
| const response = await fetch( | |
| `https://serpapi.com/search.json?engine=google&q=${encodeURIComponent( | |
| query | |
| )}&location=${encodeURIComponent( | |
| location | |
| )}&gl=us&hl=en&api_key=${API_KEY}` | |
| ); | |
| if (!response.ok) { | |
| throw new Error(`HTTP error! status: ${response.status}`); | |
| } | |
| const data = await response.json(); | |
| return data; | |
| } catch (error) { | |
| console.error("There was a problem with the fetch operation:", error); | |
| } | |
| } | |
| // Find the first organic result that contains the link to match | |
| function findMatchingLink(searchResults, linkMatch) { | |
| if (!searchResults || !searchResults.organic_results) { | |
| return null; | |
| } | |
| for (let i = 0; i < searchResults.organic_results.length; i++) { | |
| if (searchResults.organic_results[i].link.includes(linkMatch)) { | |
| return searchResults.organic_results[i]; | |
| } | |
| } | |
| return null; | |
| } | |
| const searchResults = await fetchGoogleSearchResults(QUERY, LOCATION); | |
| const searchId = searchResults.search_metadata.id; | |
| const matchingResult = findMatchingLink(searchResults, LINK_TO_MATCH); | |
| // Output object to be used in the next step | |
| output = { | |
| matchingResult: matchingResult || "No Organic Result Found", | |
| query: QUERY, | |
| location: LOCATION, | |
| linkToMatch: LINK_TO_MATCH, | |
| inspectSearchLink: `https://serpapi.com/searches/${searchId}/inspect`, | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment