From d2d557e64d4cb8c99647096eb942a5c8df6cc0ed Mon Sep 17 00:00:00 2001 From: Bruno Tremblay Date: Thu, 16 Nov 2023 16:03:05 -0500 Subject: [PATCH 1/2] Add a zip attachment example --- inst/plumber/16-attachment/plumber.R | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/inst/plumber/16-attachment/plumber.R b/inst/plumber/16-attachment/plumber.R index 87108148d..a19d57d81 100644 --- a/inst/plumber/16-attachment/plumber.R +++ b/inst/plumber/16-attachment/plumber.R @@ -21,3 +21,32 @@ function() { function() { Sys.time() } + + +#* Write and return multiple files as an archive. Ex: `datasets.zip` +#* @serializer octet +#* @get /datasets +function() { + + # Create temporary directory structure + rnd_dir <- rawToChar(as.raw(sample(65:90, size = 5, replace = TRUE))) + tmp_dir <- file.path(tempdir(), rnd_dir) + dir.create(tmp_dir, showWarnings = FALSE) + on.exit(unlink(tmp_dir, recursive = TRUE), add = TRUE) + + # Save datasets to csv + csv_files <- character() + for (dataset in c("mtcars", "iris", "airquality")) { + csv_file <- file.path(tmp_dir, paste0(dataset, ".csv")) + csv_files <- c(csv_files, csv_file) + write.csv(get(dataset), csv_file) + } + + # Create archive + zip_file <- file.path(tmp_dir, "datasets.zip") + zip(zip_file, csv_files, flags = "-jq9X") + val <- readBin(zip_file, "raw", file.info(zip_file)$size) + + as_attachment(val, "datasets.zip") + +} From e26b5017eb4dc04da4a9b138c98f4577474c429f Mon Sep 17 00:00:00 2001 From: Barret Schloerke Date: Fri, 17 Nov 2023 11:02:55 -0500 Subject: [PATCH 2/2] Apply suggestions from code review --- inst/plumber/16-attachment/plumber.R | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/inst/plumber/16-attachment/plumber.R b/inst/plumber/16-attachment/plumber.R index a19d57d81..a4e825e1f 100644 --- a/inst/plumber/16-attachment/plumber.R +++ b/inst/plumber/16-attachment/plumber.R @@ -29,18 +29,16 @@ function() { function() { # Create temporary directory structure - rnd_dir <- rawToChar(as.raw(sample(65:90, size = 5, replace = TRUE))) - tmp_dir <- file.path(tempdir(), rnd_dir) + tmp_dir <- tempfile() dir.create(tmp_dir, showWarnings = FALSE) on.exit(unlink(tmp_dir, recursive = TRUE), add = TRUE) # Save datasets to csv - csv_files <- character() - for (dataset in c("mtcars", "iris", "airquality")) { + csv_files <- lapply(c("mtcars", "quakes", "airquality"), function(dataset) { csv_file <- file.path(tmp_dir, paste0(dataset, ".csv")) - csv_files <- c(csv_files, csv_file) write.csv(get(dataset), csv_file) - } + csv_file + }) # Create archive zip_file <- file.path(tmp_dir, "datasets.zip")