diff --git a/R/layer.R b/R/layer.R index c214b08..15afede 100644 --- a/R/layer.R +++ b/R/layer.R @@ -10,13 +10,16 @@ #' #' @export Layer <- function(type, id, source = NULL, paint = NULL, layout = NULL, ...) { - list( - type = type, - id = id, - source = source, - paint = paint, - layout = layout - ) |> + types <- list(type = is.character, id = is.character, source = is.list, paint = is.list, layout = is.list) + c(rdantic( + list( + type = type, + id = id, + source = source, + paint = paint, + layout = layout + ), types + ), ...) |> purrr::compact() |> set_maplibre_class("MapLibreLayer") } @@ -44,7 +47,7 @@ add_layer <- function(.map, layer) { #' @export #' #' @example examples/layers.R -add_popup <- function(.map, layer_id, prop){ +add_popup <- function(.map, layer_id, prop) { .map |> add_call("addPopup", layer_id, prop) } @@ -60,6 +63,6 @@ add_popup <- function(.map, layer_id, prop){ #' #' @examples #' @example examples/layers.R -add_tooltip <- function(.map, layer_id, prop){ +add_tooltip <- function(.map, layer_id, prop) { .map |> add_call("addTooltip", layer_id, prop) } diff --git a/R/utils.R b/R/utils.R index e5a170f..e6e9f13 100644 --- a/R/utils.R +++ b/R/utils.R @@ -2,3 +2,15 @@ set_maplibre_class <- function(.obj, class_name) { class(.obj) <- c(class(.obj), class_name) return(.obj) } + +rdantic <- function(.obj, types, test = 1L) { + for (k in names(.obj)) { + type_check <- types[[k]] + value <- .obj[[k]] + if (xor(!type_check(value), is.null(value))) { + stop(value, " is not ", deparse(substitute(type_check)) , call.=FALSE) + } + } + + return(.obj) +} diff --git a/tests/testthat/test-rdantic.R b/tests/testthat/test-rdantic.R new file mode 100644 index 0000000..0ed6226 --- /dev/null +++ b/tests/testthat/test-rdantic.R @@ -0,0 +1,12 @@ +test_that("rdantic", { + # Prepare + l <- list(a = 1, b = "test", d = NULL) + types <- list(a = is.numeric, b = is.character, d = is.numeric) + + # Act + l <- rdantic(l, types) + + # Assert + expect_equal(l$a, 1) + expect_equal(l$b, "test") +})