ropensci / vcr

Record and replay HTTP requests
https://docs.ropensci.org/vcr
Other
77 stars 12 forks source link

Implement new Compressed serializer #187

Open sckott opened 4 years ago

sckott commented 4 years ago

maybe use zip pkg, or maybe stick with utils::zip

sckott commented 4 years ago

might bump to next milestone

sckott commented 4 years ago

code so far:

#' @title The compressed serializer
#' @description class with methods for serializing via zip compression
#' @keywords internal
#' @examples \dontrun{
#' ww <- Compressed$new(path = "stuff3")
#' ww
#' ww$file_extension
#' fun <- ww$serialize()
#' fun(list(http_interactions = list(response = list(body = "bar"))),
#'   path = ww$path, bytes = FALSE)
#' ww$deserialize()
#' }
Compressed <- R6::R6Class("Compressed",
  inherit = Serializer,
  public = list(
    #' @description Create a new `Compressed` object
    #' @param path (character) full path to the yaml file
    #' @return A new `Compressed` object
    initialize = function(path = NULL) {
      super$initialize(".zz", path)
    },

    #' @description Serializes the given hash using internal fxn write_json
    #' @param x (list) the object to serialize
    #' @param path (character) the file path
    #' @param bytes (logical) whether to preserve exact body bytes or not
    #' @return (character) the json string to write to disk
    serialize = function(x, path, bytes) {
      function(x, path, bytes) {
        z <- write_yaml2(x, path, bytes)
        zip::zip()
      }
    },

    #' @description Deserializes the given string using jsonlite::fromJSON
    #' @return (list) the deserialized object, an R list
    deserialize = function() {
      str <- sensitive_put_back(readLines(self$path))
      tmp <- jsonlite::fromJSON(str, FALSE)
      private$process_body(tmp)
    }
  )
)

# return list of yaml strings
write_yaml2 <- function(x, file, bytes) {
  write_header(file)
  lapply(x, write_interactions_yaml, bytes = bytes)
}
# return a string of yaml
write_interactions_yaml <- function(x, bytes) {
  z <- prep_interaction(x, file, bytes)
  ## hmm, not sure what to do here, need to remove separate write_header step
  ## and need to do probably list(http_interactions = z)
  ## but how do I do appending?
  tmp <- yaml::as.yaml(z)
  sensitive_remove(tmp)
}