R/api_client.R

# mzTab-M reference implementation and validation API.
#
# This is the mzTab-M reference implementation and validation API service.
#
# The version of the OpenAPI document: 2.0.0
# Contact: nils.hoffmann@cebitec.uni-bielefeld.de
# Generated by: https://openapi-generator.tech


#' ApiClient Class
#'
#' Generic API client for OpenAPI client library builds.
#' OpenAPI generic API client. This client handles the client-
#' server communication, and is invariant across implementations. Specifics of
#' the methods and models for each application are generated from the OpenAPI Generator
#' templates.
#'
#' NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
#' Ref: https://openapi-generator.tech
#' Do not edit the class manually.
#'
#' @docType class
#' @title ApiClient
#' @description ApiClient Class
#' @format An \code{R6Class} generator object
#' @field basePath Base url
#' @field userAgent Default user agent
#' @field defaultHeaders Default HTTP headers
#' @field username Username for HTTP basic authentication
#' @field password Password for HTTP basic authentication
#' @field apiKeys API keys - not used
#' @field accessToken HTTP Access token - not used
#' @field timeout Default timeout in seconds
#' @importFrom httr add_headers accept timeout content
#' @export
ApiClient  <- R6::R6Class(
  'ApiClient',
  public = list(
    # base path of all requests
    basePath = "https://apps.lifs-tools.org/mztabvalidator/rest/v2",
    # user agent in the HTTP request
    userAgent = "OpenAPI-Generator/1.0.0/r",
    # default headers in the HTTP request
    defaultHeaders = NULL,
    # username (HTTP basic authentication)
    username = NULL,
    # password (HTTP basic authentication)
    password = NULL,
    # API keys
    apiKeys = NULL,
    # Access token
    accessToken = NULL,
    # Time Out (seconds)
    timeout = NULL,
    # constructor
    #' @description
    #' Create an ApiClient
    #' @param basePath HTTP call base path to the end point
    #' @param userAgent User agent string to access endpoint with
    #' @param defaultHeaders default headers in the HTTP request
    #' @param username User name (HTTP basic authentication)
    #' @param password User password (HTTP basic authentication)
    #' @param apiKeys API keys
    #' @param accessToken Access token
    #' @param timeout Time Out (seconds)
    initialize = function(basePath=NULL, userAgent=NULL, defaultHeaders=NULL, username=NULL, password=NULL, apiKeys=NULL, accessToken=NULL, timeout=NULL){
      if (!is.null(basePath)) {
        self$basePath <- basePath
      }

      if (!is.null(defaultHeaders)) {
        self$defaultHeaders <- defaultHeaders
      }

      if (!is.null(username)) {
        self$username <- username
      }

      if (!is.null(password)) {
        self$password <- password
      }

      if (!is.null(accessToken)) {
        self$accessToken <- accessToken
      }

      if (!is.null(apiKeys)) {
        self$apiKeys <- apiKeys
      } else {
        self$apiKeys <- list()
      }

      if (!is.null(userAgent)) {
        self$`userAgent` <- userAgent
      }

      if (!is.null(timeout)) {
        self$timeout <- timeout
      }
      
      httr::set_config(httr::config(ssl_verifypeer = 0L))
    },
    #' @description CallApi
    #' @param url URL to call
    #' @param method One of GET, POST, PUT, PATCH, HEAD, DELETE
    #' @param queryParams Query parameters
    #' @param headerParams Additional header parameters
    #' @param body The call body (only in POST, PUT, PATCH)
    #' @param contentType Defaults to application/json
    #' @param ... Pass through to httr method call
    #'
    CallApi = function(url, method, queryParams, headerParams, body, contentType = "application/json", ...){
      headers <- httr::add_headers(c(headerParams, self$defaultHeaders))

      httpTimeout <- NULL
      if (!is.null(self$timeout)) {
        httpTimeout <- httr::timeout(self$timeout)
      }

      if (method == "GET") {
        httr::GET(url, query = queryParams, headers, httpTimeout, httr::user_agent(self$`userAgent`), ...)
      } else if (method == "POST") {
        httr::POST(url, query = queryParams, headers, body = body, httr::content_type(contentType), httpTimeout, httr::user_agent(self$`userAgent`), ...)
      } else if (method == "PUT") {
        httr::PUT(url, query = queryParams, headers, body = body, httr::content_type(contentType), httpTimeout, httpTimeout, httr::user_agent(self$`userAgent`), ...)
      } else if (method == "PATCH") {
        httr::PATCH(url, query = queryParams, headers, body = body, httr::content_type(contentType), httpTimeout, httpTimeout, httr::user_agent(self$`userAgent`), ...)
      } else if (method == "HEAD") {
        httr::HEAD(url, query = queryParams, headers, httpTimeout, httpTimeout, httr::user_agent(self$`userAgent`), ...)
      } else if (method == "DELETE") {
        httr::DELETE(url, query = queryParams, headers, httpTimeout, httpTimeout, httr::user_agent(self$`userAgent`), ...)
      } else {
        errMsg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`."
        stop(errMsg)
      }
    },

    #' @description Deserialize the content of api response to the given type.
    #' @param resp HTTP response, compatible to be read as httr::content text
    #' @param returnType Target type to deserialize into
    #' @param pkgEnv Current package environment
    deserialize = function(resp, returnType, pkgEnv) {
      respObj <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))
      self$deserializeObj(respObj, returnType, pkgEnv)
    },


    #' @description
    #' Deserialize the response from jsonlite object based on the given type
    #' by handling complex and nested types by iterating recursively
    #' Example returnTypes will be like "array[integer]", "map(Pet)", "array[map(Tag)]", etc.,
    #' @param obj Object to deserialize
    #' @param returnType Target type to deserialize into
    #' @param pkgEnv Current package environment
    deserializeObj = function(obj, returnType, pkgEnv) {
      returnObj <- NULL
      primitiveTypes <- c("character", "numeric", "integer", "logical", "complex")
      # To handle the "map" type 
      if (startsWith(returnType, "map(")) {
        innerReturnType <- regmatches(returnType, regexec(pattern = "map\\((.*)\\)", returnType))[[1]][2]
        returnObj <- lapply(names(obj), function(name) {
          self$deserializeObj(obj[[name]], innerReturnType, pkgEnv)
        })
        names(returnObj) <- names(obj)
      }

      # To handle the "array" type
      else if (startsWith(returnType, "array[")) {
        innerReturnType <- regmatches(returnType, regexec(pattern = "array\\[(.*)\\]", returnType))[[1]][2]
        if (c(innerReturnType) %in% primitiveTypes) {
          if (length(obj) > 0) {
            returnObj <- vector("list", length = length(obj))
            for (row in 1:length(obj)) {
              returnObj[[row]] <- unlist(self$deserializeObj(obj[row], innerReturnType, pkgEnv))
            }
          }
        } else { # handle nested arrays
          if (!is.null(nrow(obj))){ # data frame with multiple rows
            if (nrow(obj) > 0) {
              returnObj <- vector("list", length = nrow(obj))
              for (row in 1:nrow(obj)) {
                returnObj[[row]] <- self$deserializeObj(obj[row, , drop = FALSE], innerReturnType, pkgEnv)
              }
            } else if (exists(innerReturnType, pkgEnv) && !(c(innerReturnType) %in% primitiveTypes)) {
                innerReturnType <- get(innerReturnType, envir = as.environment(pkgEnv))
                returnObj <- innerReturnType$new()
                returnObj$fromJSON(jsonlite::toJSON(obj, auto_unbox  = FALSE, digits = NA))
            }
          } else if(!is.null(length(obj))) { # handle lists
            if (length(obj) > 0) {
              if (is.null(nrow(obj[[1]]))) { # handle list of primitives
                returnObj <- vector("list", length = length(obj))
                for (row in 1:length(obj)) {
                  if (typeof(obj[[row]]) %in% primitiveTypes) {
                    returnObj[[row]] <- obj
                  }
                }
              } else {
                if (exists(innerReturnType, pkgEnv) && !(c(innerReturnType) %in% primitiveTypes)) { # handle list of model objects
                  if (length(obj) > 0) {
                    idx <- 1
                    returnObj <- vector("list", length = length(obj))
                    for (row in 1:length(obj)) {
                      if (is.data.frame(obj[[row]])) { # resolve model objects in nested data frame
                        for (dfrow in 1:nrow(obj[[row]])) {
                          returnObj[[idx]] <- self$deserializeObj(obj[[row]][dfrow, ], innerReturnType, pkgEnv)  
                          idx <- idx + 1
                        }
                      } else {
                        returnObj[[idx]] <- self$deserializeObj(obj[[row]], innerReturnType, pkgEnv)
                        idx <- idx + 1
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      # To handle model objects which are not array or map containers. Ex:"Pet"
      else if (exists(returnType, pkgEnv) && !(c(returnType) %in% primitiveTypes)) {
        returnType <- get(returnType, envir = as.environment(pkgEnv))
        returnObj <- returnType$new()
        returnObj$fromJSON(jsonlite::toJSON(obj, auto_unbox  = FALSE, digits = NA))
      } 

      # To handle primitive type
      else {
        returnObj <- obj
      }
      returnObj
    }
  )
)
lifs-tools/rmzTab-m documentation built on Jan. 26, 2023, 4:45 p.m.