R/emmaRequest.R

emmaRequest <- function(accountID, usr, pw, endPoint, parms=NA, ids=NA, type=NA) {
  
  baseUrl <- "https://api.e2ma.net"
  
  ### BUILD URLS BASED ON SUPPLIED ARGUMENTS ----
  if( all(is.na(ids) & is.na(type)) ) {
    
    url <- paste(baseUrl, accountID, endPoint, sep='/')
  
  } else if( all(!is.na(ids) & is.na(type)) ) {
    
    url <- lapply(ids, function(x) paste(baseUrl, accountID, endPoint, x, sep='/')  )
    
  } else if( all(!is.na(ids) & !is.na(type)) ) {
    
    url <- lapply(ids, function(x) paste(baseUrl, accountID, endPoint, x, type, sep='/')  )
  
  }
  
  
  urlList <- paginate(url, usr, pw, parms)
  
  final <- requestUrls(urlList, url, type, endPoint, parms)
  
  
  ### PARSE RESULTS ---
  
  ## ENCODE SUBLIST AS JSON THEN CHARACTER
  final <- lapply(final, function(x) lapply(x, function(y) {
    
    if(is.list(y)) {
      out <- jsonlite::toJSON(y)
      out <- as.character(out)
    } else {
      out <- y
    }
    
    return(out)
    
    }))
  
  
  #REPLACE NULLS
  
  final <- lapply(final, function(x) lapply(x, function(y) {
    
                if(is.null(y)) {
                  y <- NA
                } else {
                  y <- y
                }
                return(y)
  }
  )
  )

  
  #### DATA FRAME
  final <- lapply(final, function(x) as.data.frame(x, stringsAsFactors = F) )
  
  ### COMBINE
  final <- do.call('rbind',final)
  final$names <- row.names(final)
  row.names(final) <- NULL

  
  return(final)
  
}
andrewgeisler/emmaR documentation built on May 10, 2019, 10:31 a.m.