Skip to content

Commit 9c815d4

Browse files
committed
refactor(api_helpers.R): improve error handling and streamline API request functions
1 parent 5d433a2 commit 9c815d4

2 files changed

Lines changed: 69 additions & 96 deletions

File tree

R/api_helpers.R

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,9 @@ build_widget_url <- function(
265265
#' @return Logical indicating if this is a category-only search
266266
#' @noRd
267267
is_category_only_search <- function(widget) {
268-
if (is.null(unlist(widget$request$comparisonItem))) {}
268+
if (is.null(unlist(widget$request$comparisonItem))) {
269+
return(TRUE)
270+
}
269271

270272
if (
271273
!any(grepl(

R/zzz.R

Lines changed: 66 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,45 @@ check_time <- function(time_ranges) {
148148
TRUE
149149
}
150150

151-
# Legacy get_widget function - maintained for backward compatibility
152-
# New code should use get_widget_enhanced
153151
get_widget <- function(comparison_item, category, gprop, hl, cookie_url, tz) {
154-
# Wrapper for legacy compatibility - delegates to enhanced version
155-
get_widget_enhanced(comparison_item, category, gprop, hl, cookie_url, tz)
152+
# Initialize cookies if needed
153+
if (!exists("cookie_handler", envir = .pkgenv)) {
154+
tryCatch(
155+
{
156+
get_api_cookies(cookie_url)
157+
},
158+
error = function(e) {
159+
stop(
160+
"Failed to initialize Google Trends session during cookie acquisition:\n",
161+
"Could not obtain required authentication cookies from Google.\n",
162+
"\nPossible causes:\n",
163+
" - Network connectivity issues\n",
164+
" - Proxy server configuration problems\n",
165+
" - Firewall blocking Google Trends access\n",
166+
" - Invalid cookie URL: ",
167+
cookie_url,
168+
"\n",
169+
"\nOriginal error: ",
170+
e$message,
171+
call. = FALSE
172+
)
173+
}
174+
)
175+
}
176+
177+
# Build API URL
178+
url <- build_explore_url(comparison_item, category, gprop, hl, tz)
179+
180+
# Make API request
181+
response <- make_api_request(url, "widget initialization")
182+
183+
# Parse response
184+
parsed_response <- parse_api_response(response)
185+
186+
# Fix geographic encoding issues
187+
parsed_response <- fix_geo_encoding(parsed_response, comparison_item)
188+
189+
return(parsed_response$widgets)
156190
}
157191

158192
interest_over_time <- function(widget, comparison_item, tz) {
@@ -176,27 +210,28 @@ build_interest_over_time_url <- function(widget, tz) {
176210
if (onlyCategory) {
177211
# Handle category-only searches
178212
payload_data <- create_category_payload(widget)
179-
return(build_trends_url(
180-
"https://www.google.com/trends/api/widgetdata/multiline/csv?req=",
181-
c(payload2, payload_data$payload),
182-
payload_data$token,
183-
tz
184-
))
213+
return(
214+
build_widget_url(
215+
"multiline",
216+
c(payload2, payload_data$payload),
217+
payload_data$token,
218+
tz
219+
)
220+
)
185221
} else if (has_multiple_timeframes(widget)) {
186222
# Handle multi-timeframe searches
187223
payload_data <- create_multirange_payload(widget)
188-
return(build_trends_url(
189-
"https://trends.google.com/trends/api/widgetdata/multirange/csv?req=",
224+
return(build_widget_url(
225+
"multirange",
190226
c(payload2, payload_data$payload),
191227
payload_data$token,
192-
tz,
193-
use_encode_payload = TRUE
228+
tz
194229
))
195230
} else {
196231
# Handle standard multiline searches
197232
payload_data <- create_multiline_payload(widget)
198-
return(build_trends_url(
199-
"https://www.google.com/trends/api/widgetdata/multiline/csv?req=",
233+
return(build_widget_url(
234+
"multiline",
200235
c(payload2, payload_data$payload),
201236
payload_data$token,
202237
tz
@@ -206,21 +241,7 @@ build_interest_over_time_url <- function(widget, tz) {
206241

207242
# Helper function to fetch data with error handling
208243
fetch_trends_data <- function(url) {
209-
res <- curl::curl_fetch_memory(url, handle = .pkgenv[["cookie_handler"]])
210-
211-
if (res$status_code != 200L) {
212-
stop(
213-
"Google Trends API request failed with status code: ",
214-
res$status_code,
215-
"\nThis could indicate:\n",
216-
" - Invalid search parameters\n",
217-
" - Rate limiting by Google\n",
218-
" - Temporary service unavailability",
219-
call. = FALSE
220-
)
221-
}
222-
223-
return(res)
244+
make_api_request(url, "trends data download")
224245
}
225246

226247
# Helper function to process API response
@@ -354,22 +375,22 @@ create_geo_payload <- function(
354375
payload2$dataMode <- "PERCENTAGES"
355376
}
356377

357-
url <- paste0(
358-
URLencode(
359-
"https://www.google.com/trends/api/widgetdata/comparedgeo/csv?req="
360-
),
361-
URLencode(
362-
jsonlite::toJSON(payload2, auto_unbox = TRUE, null = "list"),
363-
reserved = TRUE
364-
),
365-
URLencode(paste0("&token=", widget$token[i], "&tz=", tz, "&hl=en-US"))
378+
url <- build_widget_url(
379+
"comparedgeo",
380+
payload2,
381+
widget$token[i],
382+
tz,
383+
extra_params = list(hl = "en-US")
366384
)
367385

368-
res <- curl::curl_fetch_memory(url, handle = .pkgenv[["cookie_handler"]])
369-
370-
if (res$status_code != 200L) {
371-
return(NULL)
372-
}
386+
res <- tryCatch(
387+
{
388+
make_api_request(url, "geo data download")
389+
},
390+
error = function(e) {
391+
return(NULL)
392+
}
393+
)
373394

374395
con <- textConnection(rawToChar(res$content))
375396
df <- read.csv(con, skip = 1L, stringsAsFactors = FALSE, encoding = "UTF-8")
@@ -522,56 +543,6 @@ encode_payload <- function(URL, reserved = FALSE, repeated = FALSE) {
522543
#' Enhanced wrapper functions with improved error handling
523544
#' These functions provide better error messages and more robust error handling
524545

525-
#' Enhanced get_widget with better error handling
526-
#' @noRd
527-
get_widget_enhanced <- function(
528-
comparison_item,
529-
category,
530-
gprop,
531-
hl,
532-
cookie_url,
533-
tz
534-
) {
535-
# Initialize cookies if needed
536-
if (!exists("cookie_handler", envir = .pkgenv)) {
537-
tryCatch(
538-
{
539-
get_api_cookies(cookie_url)
540-
},
541-
error = function(e) {
542-
stop(
543-
"Failed to initialize Google Trends session during cookie acquisition:\n",
544-
"Could not obtain required authentication cookies from Google.\n",
545-
"\nPossible causes:\n",
546-
" - Network connectivity issues\n",
547-
" - Proxy server configuration problems\n",
548-
" - Firewall blocking Google Trends access\n",
549-
" - Invalid cookie URL: ",
550-
cookie_url,
551-
"\n",
552-
"\nOriginal error: ",
553-
e$message,
554-
call. = FALSE
555-
)
556-
}
557-
)
558-
}
559-
560-
# Build API URL
561-
url <- build_explore_url(comparison_item, category, gprop, hl, tz)
562-
563-
# Make API request
564-
response <- make_api_request(url, "widget initialization")
565-
566-
# Parse response
567-
parsed_response <- parse_api_response(response)
568-
569-
# Fix geographic encoding issues
570-
parsed_response <- fix_geo_encoding(parsed_response, comparison_item)
571-
572-
return(parsed_response$widgets)
573-
}
574-
575546
#' Enhanced interest over time with better error handling
576547
#' @noRd
577548
get_interest_over_time_enhanced <- function(widget, comparison_item, tz) {

0 commit comments

Comments
 (0)