R/get_feature_server_details.R

Defines functions get_feature_server_details

Documented in get_feature_server_details

#' Get Server Details
#'
#' Get the details of a feature or map server
#'
#' @param endpoint the server endpoint
#' @param my_token an access token generated by get_token, if neccessary for service
#' @return a list
#' @importFrom stringr str_detect
#' @importFrom httr GET
#' @importFrom httr content
#' @importFrom httr status_code
#' @importFrom stringr str_remove_all
#' @importFrom httr oauth_callback

#' @export get_feature_server_details
get_feature_server_details <-
  function(endpoint, my_token = NULL){

    # If a layer endpoint has been passed - remove it
    if(stringr::str_detect(endpoint, "MapServer$|FeatureServer$")){
      warning("Endpoint does not end with MapServer or FeatureServer, automatically fixing endpoint...")
      endpoint <- stringr::str_remove_all(endpoint, "[^(MapServer|FeatureServer)]*$")
    }

    query_string <- query_string(my_token = my_token)

    query_url <- paste0(endpoint, query_string)

    response <-
      httr::GET(query_url, httr::add_headers(referer = httr::oauth_callback()))

    # Fail if api Error
    # This does not fail properly if the layer is not found
    # because api still returns a 200 code
    stopifnot(httr::status_code(response) == 200)

    # Convert the json to a list
    parsed_content <- RcppSimdJson::fparse(response$content, max_simplify_lvl = "list")
    

    # This code is added to catch an error where the api doesn't return a failed code but
    # should still error (where the layer wasn't found)
    #Add all clause to avoid R warning message
    if (all(names(parsed_content) == "error")) {
      stop(paste0("\n", paste0(paste0("- ",
                                      names(parsed_content$error), ": ", parsed_content$error
      ), collapse = "\n")))
    }
    return(parsed_content)

  }
MatthewJWhittle/getarc documentation built on April 22, 2023, 12:16 p.m.