R/helpers.R

#' Checks for valid date format
#' @param somedate String category
#' @param date.format String language
#' @return boolean that checks for valid date

is_date <- function(somedate, date.format = "%Y-%m-%d") {
  tryCatch(!is.na(as.Date(somedate, date.format)), error = function(err) {
    FALSE
  })
}
#------------------------------------------------------------------------------#
#' Load api key if present. If not append apikey to .Renviron
#' @param apikey Character sring api key
#' @return apikey
#' @importFrom httr http_error GET  status_code

newsapi_key <- function(apikey) {

  if (missing(apikey)) {

    apikey <- Sys.getenv("NEWSAPIKEY")

    if (identical(apikey, "")) {
      stop("No valid apikey detected. Please put your key into the Renviron OR pass it to this function as formal argument",
        call. = FALSE)
    }
  } else {
    test_key <- paste0("https://newsapi.org/v2/sources?apiKey=", apikey, "&")
    resp <- httr::GET(test_key)
    if (httr::http_error(resp)) {
      stop("Newsapi request failed. Please validate your apikey.", httr::status_code(resp))
      call. = FALSE
    } else {
      cat(paste0("NEWSAPIKEY=", apikey), append = TRUE, fill = TRUE, file = file.path("~",
        ".Renviron"))
    }
  }
  return(apikey)
}
#------------------------------------------------------------------------------#
#' Helper function to create URLs. Hidden from user.

#' @param endpoint String article sources
#' @param apikey String default api key
#' @param par List of parameters
#' @return string url

create_url <- function(endpoint, par, apikey = newsapi_key()) {
  plan <- match.arg(toupper(endpoint), c("TOP-HEADLINES", "SOURCES", "EVERYTHING"))
  base_url <- paste0("https://newsapi.org/", "v2", "/", tolower(plan), "?", "apiKey=",
    apikey, "&")
  par <- paste(names(par), par, sep = "=")
  p <- paste(par, collapse = "&")
  finel_url <- paste(base_url, p, sep = "")
  return(finel_url)
}
data-atelier/newsExploreR documentation built on May 22, 2019, 11:51 p.m.