All Downloads are FREE. Search and download functionalities are using the official Maven repository.

r.modelAnyOf.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
#' @docType class
#' @title {{classname}}
#'
#' @description {{classname}} Class
#'
#' @format An \code{R6Class} generator object
#'
#' @importFrom R6 R6Class
#' @importFrom jsonlite fromJSON toJSON
#' @export
{{classname}} <- R6::R6Class(
  "{{classname}}",
  public = list(
    #' @field actual_instance the object stored in this instance.
    actual_instance = NULL,
    #' @field actual_type the type of the object stored in this instance.
    actual_type = NULL,
    #' @field any_of  a list of object types defined in the anyOf schema.
    any_of = list({{#anyOf}}"{{{.}}}"{{^-last}}, {{/-last}}{{/anyOf}}),

    #' @description
    #' Initialize a new {{{classname}}}.
    #'
    #' @param instance an instance of the object defined in the anyOf schemas: {{#anyOf}}"{{{.}}}"{{^-last}}, {{/-last}}{{/anyOf}}
    initialize = function(instance = NULL) {
      if (is.null(instance)) {
        # do nothing
      } {{#anyOf}}else if (get(class(instance)[[1]], pos = -1)$classname ==  "{{{.}}}") {
        self$actual_instance <- instance
        self$actual_type <- "{{{.}}}"
      } {{/anyOf}}else {
        stop(paste("Failed to initialize {{{classname}}} with anyOf schemas {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Provided class name: ",
                   get(class(instance)[[1]], pos = -1)$classname))
      }
    },

    #' @description
    #' Deserialize JSON string into an instance of {{{classname}}}.
    #' An alias to the method `fromJSON`.
    #'
    #' @param input The input JSON.
    #'
    #' @return An instance of {{{classname}}}.
    fromJSONString = function(input) {
      self$fromJSON(input)
    },

    #' @description
    #' Deserialize JSON string into an instance of {{{classname}}}.
    #'
    #' @param input The input JSON.
    #'
    #' @return An instance of {{{classname}}}.
    fromJSON = function(input) {
      error_messages <- list()

      {{#composedSchemas.anyOf}}
      {{^isNull}}
      `{{{dataType}}}_result` <- tryCatch({
          {{#isPrimitiveType}}
          instance <- jsonlite::fromJSON(input, simplifyVector = FALSE)
          if (typeof(instance) != "{{{dataType}}}") {
            stop(sprintf("Data type doesn't match. Expected: %s. Actual: %s.", "{{{dataType}}}", typeof(instance)))
          }
          {{/isPrimitiveType}}
          {{^isPrimitiveType}}
          `{{{dataType}}}`$public_methods$validateJSON(input)
          `{{{dataType}}}_instance` <- `{{{dataType}}}`$new()
          {{/isPrimitiveType}}
          self$actual_instance <- `{{{dataType}}}_instance`$fromJSON(input)
          self$actual_type <- "{{{dataType}}}"
          return(self)
        },
        error = function(err) err
      )

      if (!is.null(`{{{dataType}}}_result`["error"])) {
        error_messages <- append(error_messages, `{{{dataType}}}_result`["message"])
      }

      {{/isNull}}
      {{/composedSchemas.anyOf}}
      # no match
      stop(paste("No match found when deserializing the input into {{{classname}}} with anyOf schemas {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: >>",
                 paste(error_messages, collapse = " >> ")))
    },

    #' @description
    #' Serialize {{{classname}}} to JSON string.
    #'
    #' @return JSON string representation of the {{{classname}}}.
    toJSONString = function() {
      if (!is.null(self$actual_instance)) {
        as.character(jsonlite::minify((self$actual_instance$toJSONString())))
      } else {
        NULL
      }
    },

    #' @description
    #' Serialize {{{classname}}} to JSON.
    #'
    #' @return JSON representation of the {{{classname}}}.
    toJSON = function() {
      if (!is.null(self$actual_instance)) {
        self$actual_instance$toJSON()
      } else {
        NULL
      }
    },

    #' @description
    #' Validate the input JSON with respect to {{{classname}}} and
    #' throw exception if invalid.
    #'
    #' @param input The input JSON.
    validateJSON = function(input) {
      # backup current values
      actual_instance_bak <- self$actual_instance
      actual_type_bak <- self$actual_type

      # if it's not valid, an error will be thrown
      self$fromJSON(input)

      # no error thrown, restore old values
      self$actual_instance <- actual_instance_bak
      self$actual_type <- actual_type_bak
    },

    #' @description
    #' Returns the string representation of the instance.
    #'
    #' @return The string representation of the instance.
    toString = function() {
      jsoncontent <- c(
        sprintf('"actual_instance": %s', if (is.null(self$actual_instance)) NULL else self$actual_instance$toJSONString()),
        sprintf('"actual_type": "%s"', self$actual_type),
        sprintf('"any_of": "%s"', paste(unlist(self$any_of), collapse = ", "))
      )
      jsoncontent <- paste(jsoncontent, collapse = ",")
      as.character(jsonlite::prettify(paste("{", jsoncontent, "}", sep = "")))
    },

    #' @description
    #' Print the object
    print = function() {
      print(jsonlite::prettify(self$toJSONString()))
      invisible(self)
    }
  ),
  # Lock the class to prevent modifications to the method or field
  lock_class = TRUE
)
## Uncomment below to unlock the class to allow modifications of the method or field
#{{classname}}$unlock()
#
## Below is an example to define the print function
#{{classname}}$set("public", "print", function(...) {
#  print(jsonlite::prettify(self$toJSONString()))
#  invisible(self)
#})
## Uncomment below to lock the class to prevent modifications to the method or field
#{{classname}}$lock()




© 2015 - 2024 Weber Informatics LLC | Privacy Policy