R/onLoad.R

Defines functions .onLoad

Documented in .onLoad

#' onLoad hook
#'
#' @param libname A character string giving the library directory where the package defining the namespace was found.
#' @param pkgname A character string giving the name of the package.
#'
#' @return Side effects only. Defines options.
#' @importFrom jsonlite read_json
#' @importFrom magrittr %>% %<>%
.onLoad <- function(libname, pkgname){

  options(
    pkgname = pkgname,
    httr_oauth_cache = TRUE,
    stringsAsFactors = FALSE
  )
  
  # Helper functions for reading and parsing json config files
  readConfig <- function(configFile){
    read_json(system.file(file.path("config",configFile), package = pkgname), simplifyVector = TRUE)  
  }
  # Unnest data.frames and fill with emtpy columns with NAs
  unnestAndFill <- function(df) {
    for(column in names(df)) {
      if(class(df[[column]]) == "list") {
        df[[column]] %<>% lapply(function(x) ifelse(length(x) == 0, NA, x)) %>% unlist
      } else if (class(df[[column]]) == "data.frame") {
        df[[column]] %<>% unnestAndFill
      }
    }
    df
  }
  
  # Read Etsy API configuration
  etsy <- c(
    readConfig("etsy.json"),
    methods = readConfig("etsyApiReference.json") %>% unnestAndFill %>% list,
    permissionScopes = readConfig("etsyPermissionScopes.json") %>% list
  )

  # Export configuration options
  assign("etsy", etsy, envir = .GlobalEnv)
}
agpknitweardesign/festotuAPIs documentation built on Feb. 2, 2020, 12:20 p.m.