Skip to content
GitLab
    • Explore Projects Groups Snippets
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • O openapi-generator
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 3,476
    • Issues 3,476
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 402
    • Merge requests 402
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Packages and registries
    • Packages and registries
    • Package Registry
    • Infrastructure Registry
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • OpenAPI Tools
  • openapi-generator
  • Merge requests
  • !12387

[R] improve code format

  • Review changes

  • Download
  • Email patches
  • Plain diff
Merged William Cheng requested to merge r-code-improve into master 3 years ago
  • Overview 0
  • Commits 3
  • Pipelines 0
  • Changes 19

improve code format based on reports by https://github.com/r-lib/lintr

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package 
    ./bin/generate-samples.sh
    ./bin/utils/export_docs_generators.sh
    Commit all changed files. This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master. These must match the expectations made by your contribution. You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*. For Windows users, please run the script in Git BASH.
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

cc @Ramanth (2019/07) @saigiridhar21 (2019/07)

Compare
  • master (base)

and
  • latest version
    6004e4df
    3 commits, 2 years ago

19 files
+ 704
- 721

    Preferences

    File browser
    Compare changes
modules/openapi-‎generator/…/…/…/r‎
ApiRespons‎e.mustache‎ +2 -2
api.mu‎stache‎ +60 -60
api_clien‎t.mustache‎ +83 -80
api_test‎.mustache‎ +2 -3
model_tes‎t.mustache‎ +2 -3
partial_hea‎der.mustache‎ +6 -2
samples/clie‎nt/petstore/R‎
‎R‎
api_cl‎ient.R‎ +82 -80
api_res‎ponse.R‎ +2 -2
categ‎ory.R‎ +0 -1
fake_‎api.R‎ +26 -31
model_api_‎response.R‎ +0 -1
ord‎er.R‎ +0 -1
pe‎t.R‎ +0 -1
pet_‎api.R‎ +172 -179
store‎_api.R‎ +84 -85
ta‎g.R‎ +0 -1
use‎r.R‎ +0 -1
user_‎api.R‎ +160 -165
tests/t‎estthat‎
test_pe‎tstore.R‎ +23 -23
modules/openapi-generator/src/main/resources/r/ApiResponse.mustache
+ 2
- 2
  • View file @ 6004e4df

  • Edit in single-file editor

  • Open in Web IDE


@@ -6,11 +6,11 @@
#' @field response The raw response from the endpoint.
#' @export
ApiResponse <- R6::R6Class(
'ApiResponse',
"ApiResponse",
public = list(
content = NULL,
response = NULL,
initialize = function(content, response){
initialize = function(content, response) {
self$content <- content
self$response <- response
}
modules/openapi-generator/src/main/resources/r/api.mustache
+ 60
- 60
  • View file @ 6004e4df

  • Edit in single-file editor

  • Open in Web IDE


@@ -4,7 +4,7 @@
#' @title {{baseName}} operations
#' @description {{importPath}}
#' @format An \code{R6Class} generator object
#' @field apiClient Handles the client-server communication.
#' @field api_client Handles the client-server communication.
#'
#' @section Methods:
{{! Adding the below changes for generating documentation for the api methods. }}
@@ -97,17 +97,17 @@
{{#isBasic}}
#' #Configure HTTP basic authorization: {{{name}}}
#' # provide your username in the user-serial format
#' api.instance$apiClient$username <- '<user-serial>';
#' api.instance$api_client$username <- '<user-serial>';
#' # provide your api key generated using the developer portal
#' api.instance$apiClient$password <- '<api_key>';
#' api.instance$api_client$password <- '<api_key>';
{{/isBasic}}
{{#isApiKey}}
#' #Configure API key authorization: {{{name}}}
#' api.instance$apiClient$apiKeys['{{{keyParamName}}}'] <- 'TODO_YOUR_API_KEY';
#' api.instance$api_client$api_keys['{{{keyParamName}}}'] <- 'TODO_YOUR_API_KEY';
{{/isApiKey}}
{{#isOAuth}}
#' # Configure OAuth2 access token for authorization: {{{name}}}
#' api.instance$apiClient$accessToken <- 'TODO_YOUR_ACCESS_TOKEN';
#' api.instance$api_client$access_token <- 'TODO_YOUR_ACCESS_TOKEN';
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
@@ -147,36 +147,36 @@
{{/useRlangExceptionHandling}}
#' @export
{{classname}} <- R6::R6Class(
'{{classname}}',
"{{classname}}",
public = list(
apiClient = NULL,
initialize = function(apiClient){
if (!missing(apiClient)) {
self$apiClient <- apiClient
api_client = NULL,
initialize = function(api_client) {
if (!missing(api_client)) {
self$api_client <- api_client
}
else {
self$apiClient <- ApiClient$new()
self$api_client <- ApiClient$new()
}
},
{{#operation}}
{{{operationId}}} = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#returnType}}data_file=NULL, {{/returnType}}...){
apiResponse <- self${{{operationId}}}WithHttpInfo({{#allParams}}{{paramName}}, {{/allParams}}{{#returnType}}data_file=data_file, {{/returnType}}...)
resp <- apiResponse$response
{{{operationId}}} = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#returnType}}data_file=NULL, {{/returnType}}...) {
api_response <- self${{{operationId}}}WithHttpInfo({{#allParams}}{{paramName}}, {{/allParams}}{{#returnType}}data_file = data_file, {{/returnType}}...)
resp <- api_response$response
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
apiResponse$content
api_response$content
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
apiResponse
api_response
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
apiResponse
api_response
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
apiResponse
api_response
}
},
{{{operationId}}}WithHttpInfo = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#returnType}}data_file=NULL, {{/returnType}}...){
{{{operationId}}}WithHttpInfo = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{{defaultValue}}}, {{/optionalParams}}{{#returnType}}data_file = NULL, {{/returnType}}...) {
args <- list(...)
queryParams <- list()
headerParams <- c()
query_params <- list()
header_params <- c()
{{#requiredParams}}
if (missing(`{{paramName}}`)) {
@@ -189,14 +189,14 @@
}
{{/requiredParams}}
{{#headerParams}}
headerParams['{{baseName}}'] <- `{{paramName}}`
{{#header_params}}
header_params["{{baseName}}"] <- `{{paramName}}`
{{/headerParams}}
{{#queryParams}}
queryParams['{{baseName}}'] <- {{paramName}}
{{/header_params}}
{{#query_params}}
query_params["{{baseName}}"] <- {{paramName}}
{{/queryParams}}
{{/query_params}}
{{#hasFormParams}}
body <- list(
{{#formParams}}
@@ -214,8 +214,8 @@
{{#bodyParams}}
if (!missing(`{{paramName}}`)) {
{{#isArray}}
body.items = paste(unlist(lapply({{paramName}}, function(param){param$toJSONString()})), collapse = ",")
body <- paste0('[', body.items, ']')
body.items = paste(unlist(lapply({{paramName}}, function(param) {param$toJSONString()})), collapse = ",")
body <- paste0("[", body.items, "]")
{{/isArray}}
{{^isArray}}
body <- `{{paramName}}`$toJSONString()
@@ -231,11 +231,11 @@
body <- NULL
{{/hasFormParams}}
{{/hasBodyParam}}
urlPath <- "{{path}}"
url_path <- "{{path}}"
{{#hasPathParams}}
{{#pathParams}}
if (!missing(`{{paramName}}`)) {
urlPath <- gsub(paste0("\\{", "{{baseName}}", "\\}"), URLencode(as.character(`{{paramName}}`), reserved = TRUE), urlPath)
url_path <- gsub(paste0("\\{", "{{baseName}}", "\\}"), URLencode(as.character(`{{paramName}}`), reserved = TRUE), url_path)
}
{{/pathParams}}
@@ -244,32 +244,32 @@
{{#isBasic}}
{{#isBasicBasic}}
# HTTP basic auth
headerParams['Authorization'] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$apiClient$username, self$apiClient$password, sep=":"))))
header_params["Authorization"] <- paste("Basic", base64enc::base64encode(charToRaw(paste(self$api_client$username, self$api_client$password, sep = ":"))))
{{/isBasicBasic}}
{{/isBasic}}
{{#isApiKey}}
# API key authentication
{{#isKeyInHeader}}
if ("{{{keyParamName}}}" %in% names(self$apiClient$apiKeys) && nchar(self$apiClient$apiKeys["{{{keyParamName}}}"]) > 0) {
headerParams['{{keyParamName}}'] <- paste(unlist(self$apiClient$apiKeys["{{keyParamName}}"]), collapse='')
if ("{{{keyParamName}}}" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["{{{keyParamName}}}"]) > 0) {
header_params["{{keyParamName}}"] <- paste(unlist(self$api_client$api_keys["{{keyParamName}}"]), collapse = "")
}
{{/isKeyInHeader}}
{{#isKeyInQuery}}
if ("{{{keyParamName}}}" %in% names(self$apiClient$apiKeys) && nchar(self$apiClient$apiKeys["{{{keyParamName}}}"]) > 0) {
queryParams['{{keyParamName}}'] <- paste(unlist(self$apiClient$apiKeys["{{keyParamName}}"]), collapse='')
if ("{{{keyParamName}}}" %in% names(self$api_client$api_keys) && nchar(self$api_client$api_keys["{{{keyParamName}}}"]) > 0) {
query_params["{{keyParamName}}"] <- paste(unlist(self$api_client$api_keys["{{keyParamName}}"]), collapse = "")
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{#isOAuth}}
# OAuth token
headerParams['Authorization'] <- paste("Bearer", self$apiClient$accessToken, sep=" ")
header_params["Authorization"] <- paste("Bearer", self$api_client$access_token, sep = " ")
{{/isOAuth}}
{{/authMethods}}
resp <- self$apiClient$CallApi(url = paste0(self$apiClient$basePath, urlPath),
resp <- self$api_client$CallApi(url = paste0(self$api_client$base_path, url_path),
method = "{{httpMethod}}",
queryParams = queryParams,
headerParams = headerParams,
query_params = query_params,
header_params = header_params,
body = body,
...)
@@ -292,9 +292,9 @@
write(httr::content(resp, "text", encoding = "UTF-8", simplifyVector = FALSE), data_file)
}
deserializedRespObj <- tryCatch(
self$apiClient$deserialize(resp, "{{returnType}}", loadNamespace("{{packageName}}")),
error = function(e){
deserialized_resp_obj <- tryCatch(
self$api_client$deserialize(resp, "{{returnType}}", loadNamespace("{{packageName}}")),
error = function(e) {
{{#useDefaultExceptionHandling}}
stop("Failed to deserialize response")
{{/useDefaultExceptionHandling}}
@@ -303,7 +303,7 @@
{{/useRlangExceptionHandling}}
}
)
ApiResponse$new(deserializedRespObj, resp)
ApiResponse$new(deserialized_resp_obj, resp)
{{/isPrimitiveType}}
{{/returnType}}
{{^returnType}}
@@ -312,31 +312,31 @@
{{/returnType}}
} else if (httr::status_code(resp) >= 300 && httr::status_code(resp) <= 399) {
{{#returnExceptionOnFailure}}
errorMsg <- toString(content(resp))
if(errorMsg == ""){
errorMsg <- paste("Server returned " , httr::status_code(resp) , " response status code.")
error_msg <- toString(content(resp))
if(error_msg == "") {
error_msg <- paste("Server returned ", httr::status_code(resp), " response status code.")
}
{{#useDefaultExceptionHandling}}
stop(errorMsg)
stop(error_msg)
{{/useDefaultExceptionHandling}}
{{#useRlangExceptionHandling}}
rlang::abort(message = errorMsg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
rlang::abort(message = error_msg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
{{/useRlangExceptionHandling}}
{{/returnExceptionOnFailure}}
{{^returnExceptionOnFailure}}
ApiResponse$new(paste("Server returned " , httr::status_code(resp) , " response status code."), resp)
ApiResponse$new(paste("Server returned ", httr::status_code(resp), " response status code."), resp)
{{/returnExceptionOnFailure}}
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
{{#returnExceptionOnFailure}}
errorMsg <- toString(content(resp))
if(errorMsg == ""){
errorMsg <- "Api client exception encountered."
error_msg <- toString(content(resp))
if(error_msg == "") {
error_msg <- "Api client exception encountered."
}
{{#useDefaultExceptionHandling}}
stop(errorMsg)
stop(error_msg)
{{/useDefaultExceptionHandling}}
{{#useRlangExceptionHandling}}
rlang::abort(message = errorMsg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
rlang::abort(message = error_msg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
{{/useRlangExceptionHandling}}
{{/returnExceptionOnFailure}}
{{^returnExceptionOnFailure}}
@@ -344,15 +344,15 @@
{{/returnExceptionOnFailure}}
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
{{#returnExceptionOnFailure}}
errorMsg <- toString(content(resp))
if(errorMsg == ""){
errorMsg <- "Api server exception encountered."
error_msg <- toString(content(resp))
if(error_msg == "") {
error_msg <- "Api server exception encountered."
}
{{#useDefaultExceptionHandling}}
stop(errorMsg)
stop(error_msg)
{{/useDefaultExceptionHandling}}
{{#useRlangExceptionHandling}}
rlang::abort(message = errorMsg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
rlang::abort(message = error_msg, .subclass = "ApiException", ApiException = ApiException$new(http_response = resp))
{{/useRlangExceptionHandling}}
{{/returnExceptionOnFailure}}
{{^returnExceptionOnFailure}}
modules/openapi-generator/src/main/resources/r/api_client.mustache
+ 83
- 80
  • View file @ 6004e4df

  • Edit in single-file editor

  • Open in Web IDE


@@ -16,52 +16,55 @@
#' @title ApiClient
#' @description ApiClient Class
#' @format An \code{R6Class} generator object
#' @field basePath Base url
#' @field userAgent Default user agent
#' @field defaultHeaders
#' @field base_path Base url
#' @field user_agent Default user agent
#' @field default_headers
#' @field username Username for HTTP basic authentication
#' @field password Password for HTTP basic authentication
#' @field apiKeys
#' @field accessToken
#' @field api_keys
#' @field access_token
#' @field timeout Default timeout in seconds
#' @field retryStatusCodes vector of status codes to retry
#' @field maxRetryAttempts maximum number of retries for the status codes
#' @field retry_status_codes vector of status codes to retry
#' @field max_retry_attempts maximum number of retries for the status codes
#' @importFrom httr add_headers accept timeout content
{{#useRlangExceptionHandling}}
#' @importFrom rlang abort
{{/useRlangExceptionHandling}}
#' @export
ApiClient <- R6::R6Class(
'ApiClient',
"ApiClient",
public = list(
# base path of all requests
basePath = "{{{basePath}}}",
base_path = "{{{basePath}}}",
# user agent in the HTTP request
userAgent = "{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/r{{/httpUserAgent}}",
user_agent = "{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/r{{/httpUserAgent}}",
# default headers in the HTTP request
defaultHeaders = NULL,
default_headers = NULL,
# username (HTTP basic authentication)
username = NULL,
# password (HTTP basic authentication)
password = NULL,
# API keys
apiKeys = NULL,
api_keys = NULL,
# Access token
accessToken = NULL,
access_token = NULL,
# Time Out (seconds)
timeout = NULL,
# Vector of status codes to retry
retryStatusCodes=NULL,
retry_status_codes = NULL,
# Maximum number of retry attempts for the retry status codes
maxRetryAttempts = NULL,
max_retry_attempts = NULL,
# constructor
initialize = function(basePath=NULL, userAgent=NULL, defaultHeaders=NULL, username=NULL, password=NULL, apiKeys=NULL, accessToken=NULL, timeout=NULL, retryStatusCodes=NULL, maxRetryAttempts=NULL){
if (!is.null(basePath)) {
self$basePath <- basePath
initialize = function(base_path=NULL, user_agent=NULL, default_headers=NULL,
username=NULL, password=NULL, api_keys=NULL,
access_token=NULL, timeout=NULL,
retry_status_codes=NULL, max_retry_attempts=NULL) {
if (!is.null(base_path)) {
self$base_path <- base_path
}
if (!is.null(defaultHeaders)) {
self$defaultHeaders <- defaultHeaders
if (!is.null(default_headers)) {
self$default_headers <- default_headers
}
if (!is.null(username)) {
@@ -72,49 +75,49 @@ ApiClient <- R6::R6Class(
self$password <- password
}
if (!is.null(accessToken)) {
self$accessToken <- accessToken
if (!is.null(access_token)) {
self$access_token <- access_token
}
if (!is.null(apiKeys)) {
self$apiKeys <- apiKeys
if (!is.null(api_keys)) {
self$api_keys <- api_keys
} else {
self$apiKeys <- list()
self$api_keys <- list()
}
if (!is.null(userAgent)) {
self$`userAgent` <- userAgent
if (!is.null(user_agent)) {
self$`user_agent` <- user_agent
}
if (!is.null(timeout)) {
self$timeout <- timeout
}
if (!is.null(retryStatusCodes)) {
self$retryStatusCodes <- retryStatusCodes
if (!is.null(retry_status_codes)) {
self$retry_status_codes <- retry_status_codes
}
if (!is.null(maxRetryAttempts)) {
self$maxRetryAttempts <- maxRetryAttempts
if (!is.null(max_retry_attempts)) {
self$max_retry_attempts <- max_retry_attempts
}
},
CallApi = function(url, method, queryParams, headerParams, body, ...){
CallApi = function(url, method, query_params, header_params, body, ...) {
resp <- self$Execute(url, method, queryParams, headerParams, body, ...)
statusCode <- httr::status_code(resp)
resp <- self$Execute(url, method, query_params, header_params, body, ...)
status_code <- httr::status_code(resp)
if (is.null(self$maxRetryAttempts)) {
self$maxRetryAttempts = 3
if (is.null(self$max_retry_attempts)) {
self$max_retry_attempts <- 3
}
if (!is.null(self$retryStatusCodes)) {
if (!is.null(self$retry_status_codes)) {
for (i in 1 : self$maxRetryAttempts) {
if (statusCode %in% self$retryStatusCodes) {
for (i in 1 : self$max_retry_attempts) {
if (status_code %in% self$retry_status_codes) {
Sys.sleep((2 ^ i) + stats::runif(n = 1, min = 0, max = 1))
resp <- self$Execute(url, method, queryParams, headerParams, body, ...)
statusCode <- httr::status_code(resp)
resp <- self$Execute(url, method, query_params, header_params, body, ...)
status_code <- httr::status_code(resp)
} else {
break;
}
@@ -124,78 +127,78 @@ ApiClient <- R6::R6Class(
resp
},
Execute = function(url, method, queryParams, headerParams, body, ...){
headers <- httr::add_headers(c(headerParams, self$defaultHeaders))
Execute = function(url, method, query_params, header_params, body, ...) {
headers <- httr::add_headers(c(header_params, self$default_headers))
{{! Adding timeout that can be set at the apiClient object level}}
httpTimeout <- NULL
http_timeout <- NULL
if (!is.null(self$timeout)) {
httpTimeout <- httr::timeout(self$timeout)
http_timeout <- httr::timeout(self$timeout)
}
if (method == "GET") {
httr::GET(url, query = queryParams, headers, httpTimeout, httr::user_agent(self$`userAgent`), ...)
httr::GET(url, query = query_params, headers, http_timeout, httr::user_agent(self$`user_agent`), ...)
} else if (method == "POST") {
httr::POST(url, query = queryParams, headers, body = body, httr::content_type("application/json"), httpTimeout, httr::user_agent(self$`userAgent`), ...)
httr::POST(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, httr::user_agent(self$`user_agent`), ...)
} else if (method == "PUT") {
httr::PUT(url, query = queryParams, headers, body = body, httr::content_type("application/json"), httpTimeout, httpTimeout, httr::user_agent(self$`userAgent`), ...)
httr::PUT(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
} else if (method == "PATCH") {
httr::PATCH(url, query = queryParams, headers, body = body, httr::content_type("application/json"), httpTimeout, httpTimeout, httr::user_agent(self$`userAgent`), ...)
httr::PATCH(url, query = query_params, headers, body = body, httr::content_type("application/json"), http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
} else if (method == "HEAD") {
httr::HEAD(url, query = queryParams, headers, httpTimeout, httpTimeout, httr::user_agent(self$`userAgent`), ...)
httr::HEAD(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
} else if (method == "DELETE") {
httr::DELETE(url, query = queryParams, headers, httpTimeout, httpTimeout, httr::user_agent(self$`userAgent`), ...)
httr::DELETE(url, query = query_params, headers, http_timeout, http_timeout, httr::user_agent(self$`user_agent`), ...)
} else {
errMsg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`."
err_msg <- "Http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`."
{{#useDefaultExceptionHandling}}
stop(errMsg)
stop(err_msg)
{{/useDefaultExceptionHandling}}
{{#useRlangExceptionHandling}}
rlang::abort(message = errMsg, .subclass = "ApiException", ApiException = ApiException$new(status = 0, reason = errMsg))
rlang::abort(message = err_msg, .subclass = "ApiException", ApiException = ApiException$new(status = 0, reason = err_msg))
{{/useRlangExceptionHandling}}
}
},
# Deserialize the content of api response to the given type.
deserialize = function(resp, returnType, pkgEnv) {
respObj <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))
self$deserializeObj(respObj, returnType, pkgEnv)
deserialize = function(resp, return_type, pkg_env) {
resp_obj <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))
self$deserializeObj(resp_obj, return_type, pkg_env)
},
# 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.,
# Example return_types will be like "array[integer]", "map(Pet)", "array[map(Tag)]", etc.,
deserializeObj = function(obj, returnType, pkgEnv) {
returnObj <- NULL
primitiveTypes <- c("character", "numeric", "integer", "logical", "complex")
deserializeObj = function(obj, return_type, pkg_env) {
return_obj <- NULL
primitive_types <- 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)
if (startsWith(return_type, "map(")) {
inner_return_type <- regmatches(return_type, regexec(pattern = "map\\((.*)\\)", return_type))[[1]][2]
return_obj <- lapply(names(obj), function(name) {
self$deserializeObj(obj[[name]], inner_return_type, pkg_env)
})
names(returnObj) <- names(obj)
names(return_obj) <- 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) {
returnObj <- vector("list", length = length(obj))
else if (startsWith(return_type, "array[")) {
inner_return_type <- regmatches(return_type, regexec(pattern = "array\\[(.*)\\]", return_type))[[1]][2]
if (c(inner_return_type) %in% primitive_types) {
return_obj <- vector("list", length = length(obj))
if (length(obj) > 0) {
for (row in 1:length(obj)) {
returnObj[[row]] <- self$deserializeObj(obj[row], innerReturnType, pkgEnv)
return_obj[[row]] <- self$deserializeObj(obj[row], inner_return_type, pkg_env)
}
}
} else {
if(!is.null(nrow(obj))){
returnObj <- vector("list", length = nrow(obj))
if (!is.null(nrow(obj))) {
return_obj <- vector("list", length = nrow(obj))
if (nrow(obj) > 0) {
for (row in 1:nrow(obj)) {
returnObj[[row]] <- self$deserializeObj(obj[row, , drop = FALSE], innerReturnType, pkgEnv)
return_obj[[row]] <- self$deserializeObj(obj[row, , drop = FALSE], inner_return_type, pkg_env)
}
}
}
@@ -203,19 +206,19 @@ ApiClient <- R6::R6Class(
}
# 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(
else if (exists(return_type, pkg_env) && !(c(return_type) %in% primitive_types)) {
return_type <- get(return_type, envir = as.environment(pkg_env))
return_obj <- return_type$new()
return_obj$fromJSON(
jsonlite::toJSON(obj, digits = NA, auto_unbox = TRUE)
)
}
# To handle primitive type
else {
returnObj <- obj
return_obj <- obj
}
returnObj
return_obj
}
)
)
modules/openapi-generator/src/main/resources/r/api_test.mustache
+ 2
- 3
  • View file @ 6004e4df

  • Edit in single-file editor

  • Open in Web IDE


@@ -3,10 +3,10 @@
context("Test {{{classname}}}")
api.instance <- {{{classname}}}$new()
api_instance <- {{{classname}}}$new()
{{#operations}}
{{#operation}}
test_that("{{{operationId}}}", {
# tests for {{operationId}}
# base path: {{{basePath}}}
@@ -24,6 +24,5 @@ test_that("{{{operationId}}}", {
# uncomment below to test the operation
#expect_equal(result, "EXPECTED_RESULT")
})
{{/operation}}
{{/operations}}
modules/openapi-generator/src/main/resources/r/model_test.mustache
+ 2
- 3
  • View file @ 6004e4df

  • Edit in single-file editor

  • Open in Web IDE


@@ -8,9 +8,9 @@ context("Test {{{classname}}}")
{{#vars}}
{{#-first}}
model.instance <- {{{classname}}}$new()
model_instance <- {{{classname}}}$new()
{{/-first}}
test_that("{{{name}}}", {
# tests for the property `{{{name}}}` ({{dataType}})
{{#description}}
@@ -20,7 +20,6 @@ test_that("{{{name}}}", {
# uncomment below to test the property
#expect_equal(model.instance$`{{{name}}}`, "EXPECTED_RESULT")
})
{{/vars}}
{{/isEnum}}
{{/model}}
0 Assignees
None
Assign to
0 Reviewers
None
Request review from
Labels
4
Breaking change (without fallback) Client: R Enhancement: Code Cleanup Enhancement: Code format
4
Breaking change (without fallback) Client: R Enhancement: Code Cleanup Enhancement: Code format
    Assign labels
  • Manage project labels

Milestone
6.0.0
6.0.0 (expired)
None
Time tracking
No estimate or time spent
Lock merge request
Unlocked
1
1 participant
William Cheng
Reference: OpenAPITools/openapi-generator!12387
Source branch: r-code-improve

Menu

Explore Projects Groups Snippets