Skip to content

Commit

Permalink
Add a function for cleanly merging URLs.
Browse files Browse the repository at this point in the history
  • Loading branch information
jonthegeek committed Mar 28, 2024
1 parent f9f8b01 commit fae426a
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 1 deletion.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export(req_perform)
export(req_prepare)
export(security_api_key)
export(stabilize_string)
export(url_path_append)
importFrom(fs,path)
importFrom(httr2,req_perform)
importFrom(rlang,":=")
28 changes: 28 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,31 @@ compact_nested_list <- function(lst) {
}
return(purrr::compact(lst))
}

#' Add path elements to a URL
#'
#' Append zero or more path elements to a URL without duplicating "/"
#' characters. Based on [httr2::req_url_path_append()].
#'
#' @param url A URL to modify.
#' @param ... Path elements to append, as strings.
#'
#' @return A modified URL.
#' @export
#'
#' @examples
#' url_path_append("https://example.com", "api", "v1", "users")
#' url_path_append("https://example.com/", "/api", "/v1", "/users")
#' url_path_append("https://example.com/", "/api/v1/users")
url_path_append <- function(url, ...) {
url <- httr2::url_parse(url)
url$path <- .path_merge(url$path, ...)
return(httr2::url_build(url))
}

.path_merge <- function(...) {
path <- paste(c(...), collapse = "/")
path <- sub("^([^/])", "/\\1", path)
path <- gsub("/+", "/", path)
return(sub("/$", "", path))
}
25 changes: 25 additions & 0 deletions man/url_path_append.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion tests/testthat/test-req_query.R
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ test_that("req_prepare() uses query parameters", {
)
})

test_that("req_prepare() smushes and concatenates multi-value query parameters", {
test_that("req_prepare() smushes & concatenates multi-value query parameters", {
test_result <- req_prepare(
base_url = "https://example.com",
query = list(
Expand Down
15 changes: 15 additions & 0 deletions tests/testthat/test-utils.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
test_that("Can build clean urls", {
expected_result <- "https://example.com/api/v1/users"
expect_identical(
url_path_append("https://example.com", "api", "v1", "users"),
expected_result
)
expect_identical(
url_path_append("https://example.com/", "/api", "/v1", "/users"),
expected_result
)
expect_identical(
url_path_append("https://example.com/", "/api/v1/users"),
expected_result
)
})

0 comments on commit fae426a

Please sign in to comment.