Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass API errors to R #23

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#' Helper to check if a Request was successful
#'
#' @param parsed_response
#'
#' @return `TRUE` for a successful request, otherwise, an error.
#' @family helper functions
#' @noRd
check_request_success <- function(parsed_response) {
# If the request is successful, the response will have `error$FALSE`otherwise,
# it'll contain a message
assertthat::assert_that(isFALSE(purrr::pluck(parsed_response, "error")),
msg = paste0(
"Something went wrong while accessing the API:\n",
purrr::pluck(parsed_response, "error", "error_msg")
)
)
# This will only get evaluated if the above assertion passes.
return(TRUE)
}

#' Helper to assert that the access_token has the right shape
#'
#' @param access_token
#'
#' @return `TRUE` for a string in the shape of an access token,
#' otherwise an error
#' @family helper functions
#' @noRd
is_access_token <- function(access_token) {
assertthat::assert_that(assertthat::is.string(access_token))
assertthat::assert_that(nchar(access_token) == 120)
assertthat::assert_that(grepl("^[-A-Za-z0-9+\\/]*={0,3}$", access_token))
}
17 changes: 17 additions & 0 deletions tests/testthat/test-utils.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
test_that("check_request_success() returns error on bad access token", {
bad_request <-
httr2::request("https://api.iasset.nl/getCustomInspectionFields/") %>%
httr2::req_body_form(
access_token = "NOT AN ACCESS TOKEN"
) %>%
httr2::req_perform() %>%
httr2::resp_body_json(check_type = F)
expect_error(
check_request_success(bad_request),
regexp = "Something went wrong while accessing the API:"
)
})

test_that("check_request_success() returns TRUE on a correct request", {
# TODO: caching some responses without any secrets in them
})