R/search_vd.R

Defines functions search_vd

Documented in search_vd

#' @title Search VecDyn by keyword
#' @description Retrieve the IDs for any VecDyn datasets matching the given keywords
#'
#' @author Francis Windram
#'
#' @param keywords either a string of search terms separated by spaces, or a vector of keywords.
#' @param basereq an [httr2 request][httr2::request()] object, as generated by [vb_basereq()]. If `NA`, uses the default request.
#'
#' @return An `ohvbd.ids` vector of VecDyn dataset IDs.
#'
#' @examplesIf interactive()
#' search_vd("Aedes aegypti")
#'
#' search_vd(c("Aedes", "aegypti"))
#'
#' @note
#' [search_hub()] is now preferred for keyword searches:
#'
#' ```
#' # old style
#' search_vd(c("Ixodes", "ricinus")
#'
#' # new style
#' search_hub("Ixodes ricinus", db = "vd")
#' ```
#'
#' `search_vd()` may be deprecated in the future.
#'
#' @concept vecdyn
#'
#' @export
#'

search_vd <- function(keywords, basereq = vb_basereq()) {
  cli::cli_inform(c(
    "i" = "{.fn ohvbd::search_hub} is now preferred for keyword searches:",
    "",
    '{.code search_hub("{paste(keywords, collapse = " ")}", db = "vd")}',
    "",
    "!" = "{.fn search_vd} may be deprecated in the future."),
    .frequency = "regularly",
    .frequency_id = "search_vd_deprecation_info")

  req <- basereq |>
    req_url_path_append("vecdynbyprovider") |>
    req_url_query("format" = "json") |>
    req_url_query("keywords" = keywords, .multi = space_collapse)

  if (getOption("ohvbd_dryrun", default = FALSE)) {
    cli::cli_alert_warning("Debug option {.val ohvbd_dryrun} is TRUE.")
    cli::cli_alert_info("Returning request object...")
    return(req)
  }

  resplist <- tryCatch(
    {
      resp <- req |>
        req_perform()
      list("resp" = resp, "err_code" = 0, "err_obj" = NULL)
    },
    error = function(e) {
      # Get the last response instead
      list("resp" = last_response(), "err_code" = 1, "err_obj" = e)
    }
  )

  if (resplist$err_code == 1) {
    cli::cli_abort("No records found for {.val {keywords}}")
  }
  body <- resplist$resp |> resp_body_json()

  if (length(body) > 2) {
    # This is a bit of a kludge, the API does not return count in the same place if no results are found
    cli::cli_abort("No records found for {.val {keywords}}")
  } else {
    outids <- as.numeric(body$ids)
    outids <- new_ohvbd.ids(v = outids, db = "vd")
    return(outids)
  }
}

Try the ohvbd package in your browser

Any scripts or data that you put into this service are public.

ohvbd documentation built on March 10, 2026, 1:07 a.m.