Skip to content

Commit

Permalink
feat(app): #13 factor validation and serialization to function
Browse files Browse the repository at this point in the history
allows for reuse in other functions
  • Loading branch information
AlexAxthelm committed Jan 31, 2024
1 parent fc8e4e2 commit 000ce0f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 14 deletions.
15 changes: 1 addition & 14 deletions R/process_directory.R
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,7 @@ process_directory <- function(
logger::log_info("Preparing metadata JSON file.")
if (validate) {
logger::log_info("Validating output.")
sch <- jsonvalidate::json_schema[["new"]](
schema = schema_file,
strict = TRUE,
engine = "ajv"
)
summaries_json <- jsonlite::prettify(
sch[["serialise"]](all_summaries)
)
json_is_valid <- sch[["validate"]](summaries_json, verbose = TRUE)
if (json_is_valid) {
logger::log_debug("JSON is valid.")
} else {
logger::log_error("JSON is not valid.")
}
summaries_json <- schema_serialize(all_summaries)
} else {
logger::log_warn("Skipping JSON validation.")
summaries_json <- jsonlite::toJSON(
Expand Down
38 changes: 38 additions & 0 deletions R/schema_serialize.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
schema_serialize <- function(
object,
schema_file = system.file(
"extdata", "schema", "metadata.json",
package = "workflow.portfolio.parsing"
),
reference = NULL
) {
sch <- jsonvalidate::json_schema[["new"]](
schema = readLines(schema_file),
strict = TRUE,
engine = "ajv",
reference = reference
)
json <- sch[["serialise"]](object)
json_is_valid <- sch[["validate"]](json, verbose = TRUE)
if (json_is_valid) {
logger::log_trace("JSON is valid.")
} else {
json_errors <- attributes(json_is_valid)[["errors"]]
logger::log_warn(
"Portfolio metadata could not be validated against ",
"JSON schema: \"", schema_file, "\"."
)
logger::log_trace(
logger::skip_formatter(paste("JSON string: ", json))
)
logger::log_trace("Validation errors:")
for (i in seq(from = 1L, to = nrow(json_errors), by = 1L)) {
logger::log_trace(
"instancePath: ", json_errors[i, "instancePath"],
" message: ", json_errors[i, "message"]
)
}
warning("Portfolio metadata could not be validated against schema.")
}
return(json)
}

0 comments on commit 000ce0f

Please sign in to comment.