diff --git a/R/read_package.R b/R/read_package.R index 8af3fd3..ca30b81 100644 --- a/R/read_package.R +++ b/R/read_package.R @@ -8,6 +8,8 @@ #' Data Package standard. #' #' @param file Path or URL to a `datapackage.json` file. +#' @param attach Attach the resources' data to the package object rather than keeping the path. See +#' [data location](https://specs.frictionlessdata.io/data-resource/#data-location). #' @return A Data Package object, see [create_package()]. #' @family read functions #' @export @@ -22,7 +24,7 @@ #' # Access the Data Package properties #' package$name #' package$created -read_package <- function(file = "datapackage.json") { +read_package <- function(file = "datapackage.json", attach = FALSE) { # Read file if (!is.character(file)) { cli::cli_abort( @@ -48,5 +50,19 @@ read_package <- function(file = "datapackage.json") { descriptor$directory <- dirname(file) # Also works for URLs # Create package - create_package(descriptor) + package <- create_package(descriptor) + + # Attach path and url to package + if (attach) { + package$resources <- purrr::map(package$resources, ~ { + resource <- get_resource(package, .x$name) + if (resource$read_from %in% c("path", "url")) { + .x$data <- read_from_path(package, .x$name, col_select = NULL) + .x$path <- NULL + } + .x + }) + } + + return(package) } diff --git a/tests/testthat/test-read_package.R b/tests/testthat/test-read_package.R index 072dee8..02045bd 100644 --- a/tests/testthat/test-read_package.R +++ b/tests/testthat/test-read_package.R @@ -131,3 +131,17 @@ test_that("read_package() converts JSON null to NULL", { # { "image": null } is read as NULL (use chuck() to force error if missing) expect_null(purrr::chuck(p, "image")) }) + + +test_that("read_package() with `attach=TRUE`", { + p_path <- system.file("extdata", "v1", "datapackage.json", package = "frictionless") + p <- read_package(p_path, attach = TRUE) + expect_s3_class(p$resources[[1]]$data, "data.frame") + + p_url <- file.path( + "https://raw.githubusercontent.com/frictionlessdata/frictionless-r/", + "main/inst/extdata/v1/datapackage.json" + ) + p_remote <- read_package(p_url, attach = TRUE) + expect_s3_class(p_remote$resources[[1]]$data, "data.frame") +})