AzureRMR/R/call_azure_rm.R

76 строки
2.3 KiB
R
Исходник Обычный вид История

2018-05-01 23:24:41 +03:00
#' @export
2018-05-07 15:37:08 +03:00
call_azure_rm <- function(token, subscription, operation, ...,
options=list(),
api_version=getOption("azure_api_version"))
2018-05-06 20:00:52 +03:00
{
url <- httr::parse_url(token$credentials$resource)
url$path <- file.path("subscriptions", subscription, operation, fsep="/")
2018-05-07 16:40:05 +03:00
url$query <- modifyList(list(`api-version`=api_version), options)
2018-05-06 20:00:52 +03:00
2018-05-06 21:07:45 +03:00
call_azure_url(token, httr::build_url(url), ...)
2018-05-06 20:00:52 +03:00
}
#' @export
call_azure_url <- function(token, url, ...,
2018-05-10 21:11:20 +03:00
http_verb=c("GET", "DELETE", "PUT", "POST", "HEAD", "PATCH"),
2018-05-06 20:00:52 +03:00
http_status_handler=c("stop", "warn", "message", "pass"),
auto_refresh=TRUE)
{
headers <- process_headers(token, ..., auto_refresh=auto_refresh)
verb <- get(match.arg(http_verb), getNamespace("httr"))
# do actual API call
res <- verb(url, headers, ...)
process_response(res, match.arg(http_status_handler))
}
process_headers <- function(token, ..., auto_refresh)
2018-05-01 16:40:40 +03:00
{
2018-05-01 23:24:41 +03:00
# if token has expired, renew it
if(auto_refresh && !token$validate())
{
message("Access token has expired or is no longer valid; refreshing")
token$refresh()
}
2018-05-01 16:40:40 +03:00
2018-05-01 23:24:41 +03:00
creds <- token$credentials
2018-05-06 20:00:52 +03:00
host <- httr::parse_url(creds$resource)$host
headers <- c(Host=host, Authorization=paste(creds$token_type, creds$access_token))
2018-05-04 04:43:14 +03:00
# default content-type is json, set this if encoding not specified
dots <- list(...)
if(is_empty(dots) || !("encode" %in% names(dots)))
headers <- c(headers, `Content-type`="application/json")
2018-05-06 20:00:52 +03:00
httr::add_headers(.headers=headers)
}
2018-05-01 23:24:41 +03:00
2018-05-01 18:40:47 +03:00
2018-05-06 20:00:52 +03:00
process_response <- function(response, handler)
{
if(handler != "pass")
2018-05-01 18:40:47 +03:00
{
2018-05-06 20:00:52 +03:00
handler <- get(paste0(handler, "_for_status"), getNamespace("httr"))
handler(response, paste0("complete Resource Manager operation. Message:\n",
sub("\\.$", "", arm_error_message(response))))
cont <- httr::content(response)
2018-05-06 17:56:31 +03:00
if(is.null(cont))
cont <- list()
2018-05-06 20:00:52 +03:00
attr(cont, "status") <- httr::status_code(response)
2018-05-06 17:56:31 +03:00
cont
2018-05-01 18:40:47 +03:00
}
2018-05-06 20:00:52 +03:00
else response
2018-05-01 16:40:40 +03:00
}
2018-05-06 20:00:52 +03:00
# provide complete error messages from Resource Manager
2018-05-05 14:25:59 +03:00
arm_error_message <- function(response)
{
cont <- httr::content(response)
2018-05-05 19:26:20 +03:00
paste0(strwrap(cont$error$message), collapse="\n")
}
2018-05-04 04:43:14 +03:00