R/other.R

Defines functions fetch_other fetch_other_info

Documented in fetch_other fetch_other_info

#' Fetches other series from DataHub
#'
#' @param code the code of the serie
#' @param source_code the source code of the serie
#' @param query optional, availible list(from = yyyy-mm-dd, to = yyyy-mm-dd, bridge = 'linear' or 'last')
#'
#' @return dataframe \describe{
#'   \item{code}{serie code}
#'   \item{source_code}{source code}
#'   \item{date}{series date}
#'   \item{value}{value of the serie}
#'   \item{unit}{unit of the value}
#' }
#'
#' @examples
#' fetch_commodity('STORF', 'HS')
#' fetch_commodity('KRAN-M', 'VE', query = list(from = '2018-01-01', bridge = 'last'))
#'
#' @export
fetch_other <- function(code, source_code, query = list()) {

  # Check input arguments
  collection <- checkmate::makeAssertCollection()
  checkmate::assertString(code, na.ok = FALSE, min.chars = 1, add = collection)
  checkmate::assertString(source_code, na.ok = FALSE, min.chars = 1, add = collection)
  checkmate::assertList(query, add = collection)
  checkmate::reportAssertions(collection)

  # Create url
  url <- paste0(
    getOption("base_path", default = "https://api.datahub.is"),
    "/other/",
    toupper(code),
    "/source/",
    toupper(source_code),
    "/value")

  # Make API call and parse
  resp <- httr::GET(
    url,
    httr::add_headers("Authorization" = getOption("authentication_key", default = "")),
    httr::accept_json(),
    query = query)

  parsed <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))

  #* Stop if errors
  if (httr::http_error(resp)) {
    stop(
      sprintf(
        "DataHub API request failed [%s]\n%s\n<%s>",
        httr::status_code(resp),
        parsed$message,
        parsed$errors
      ),
      call. = FALSE
    )
  }

  tryCatch({
    parsed$date = as.Date(parsed$date)
    return(parsed)
  },
    error=function(error_message) {
      return(setNames(data.frame(matrix(ncol = 5, nrow = 0)), c("code", "source_code", "date", "value", "unit")))
  })
}

#' Fetches all available other series
#'
#' @return dataframe \describe{
#'   \item{code}{other code}
#'   \item{name}{other name}
#'   \item{source_code}{source code}
#'   \item{source_name}{source name, use this for caption}
#'   \item{description}{description of this series}
#'   \item{last_update}{date this series was last updated}
#'   \item{usage}{code example on how to call for the dataseries}
#' }
#'
#' @examples
#' fetch_other_info()
#' fetch_other_info() %>%
#'    filter(stringr::str_detect(name, stringr::fixed('störf', ignore_case = T)))
#'
#' @export
fetch_other_info <- function(.x = NULL) {
  # Create url
  url <- paste0(
    getOption("base_path", default = "https://api.datahub.is"),
    "/other")

  # Make API call and parse
  resp <- httr::GET(
    url,
    httr::add_headers("Authorization" = getOption("authentication_key", default = "")),
    httr::accept_json())

  parsed <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))

  #* Stop if errors
  if (httr::http_error(resp)) {
    stop(
      sprintf(
        "DataHub API request failed [%s]\n%s\n<%s>",
        httr::status_code(resp),
        parsed$message,
        parsed$errors
      ),
      call. = FALSE
    )
  }

  parsed <- parsed %>%
    select(code, name, source_code, source_name, description, last_update) %>%
    mutate(usage = paste0("fetch_other('", code, "','", source_code, "')"))

  if (is.data.frame(.x)) rbind(.x, parsed)
  else parsed
}
palmargisla/datahub-r documentation built on Sept. 18, 2019, 9:50 p.m.