R/utils.R

Defines functions check_internet check_http_status check_API_response check_input_class

# Helper functions

# Check for internet connection
check_internet <- function(){
  assertthat::assert_that(
    curl::has_internet(),
    msg = "Please check your internet connection"
  )
}


# Check http status
check_http_status <- function(resp){
  assertthat::assert_that(
    httr::status_code(resp) == 200,
    msg = paste0("Status code ", httr::status_code(resp))
  )
}

# Check content is json
# check_content_type <- function(resp){
#   attempt::stop_if_not(
#     .x = httr::http_type(resp),
#     .p = ~ .x == "application/json",
#     msg = paste0("Error: API did not return json. \n", resp$url)
#     )
# }

# Check API request errors
check_API_response <- function(content){
  assertthat::assert_that(
    content$status == "OK",
    msg = content$alert$message
  )
}

# Check input file class, API return or local path to json
check_input_class <- function(input, class){

  if (any(class(input) == class)) {
    input_class <- class
    input_class
  } else if (assertthat::has_extension(input[1], "json")) {
    input_class <- "json"
    input_class
  } else {
    class
  }
}


# URLs for API requests
base_url <- "https://api.legiscan.com/"
fanghuiz/legiscanrr documentation built on Jan. 13, 2020, 4:51 a.m.