Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[R] Alternate PR for serialization fixes along with WithHttpInfo method enhancement #3099

Merged
merged 13 commits into from
Jun 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/windows/r-petstore.bat
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ If Not Exist %executable% (
)

REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g r -o samples\client\petstore\R
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g r -o samples\client\petstore\R --additional-properties packageName=petstore

java %JAVA_OPTS% -jar %executable% %ags%
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,10 @@ public RClientCodegen() {
typeMapping.put("file", "data.frame");
typeMapping.put("binary", "data.frame");
typeMapping.put("ByteArray", "character");
typeMapping.put("map", "object");
typeMapping.put("map", "map");
typeMapping.put("object", "object");

importMapping.clear();
cliOptions.clear();
cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "R package name (convention: lowercase).")
.defaultValue("openapi"));
Expand Down Expand Up @@ -288,10 +290,10 @@ public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return getTypeDeclaration(inner);
return getSchemaType(p) + "[" + getTypeDeclaration(inner)+ "]";
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return getTypeDeclaration(inner);
return getSchemaType(p) + "(" + getTypeDeclaration(inner) + ")";
}

// Not using the supertype invocation, because we want to UpperCamelize
Expand Down
22 changes: 18 additions & 4 deletions modules/openapi-generator/src/main/resources/r/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@
},
{{#operation}}
{{{operationId}}} = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{#defaultValue}}{{{.}}}{{/defaultValue}}, {{/optionalParams}}...){
apiResponse <- self${{{operationId}}}WithHttpInfo({{#allParams}}{{paramName}}, {{/allParams}}...)
resp <- apiResponse$response
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
apiResponse$content
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
apiResponse
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
apiResponse
}
},

{{{operationId}}}WithHttpInfo = function({{#requiredParams}}{{paramName}}, {{/requiredParams}}{{#optionalParams}}{{paramName}}={{^defaultValue}}NULL{{/defaultValue}}{{#defaultValue}}{{{.}}}{{/defaultValue}}, {{/optionalParams}}...){
args <- list(...)
queryParams <- list()
headerParams <- c()
Expand Down Expand Up @@ -119,21 +131,23 @@
if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) {
{{#returnType}}
{{#isPrimitiveType}}
httr::content(resp, "text", encoding = "UTF-8"
content <- httr::content(resp, "text", encoding = "UTF-8")
ApiResponse$new(content,resp)
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{returnType}}$new()$fromJSONString(httr::content(resp, "text", encoding = "UTF-8"))
deserializedRespObj <- self$apiClient$deserialize(resp, "{{returnType}}", "package:{{packageName}}")
ApiResponse$new(deserializedRespObj, resp)
{{/isPrimitiveType}}
{{/returnType}}
{{^returnType}}
# void response, no need to return anything
{{! Returning the ApiResponse object with NULL object when the endpoint doesn't return anything}}
ApiResponse$new(NULL, resp)
{{/returnType}}
} else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499) {
ApiResponse$new("API client error", resp)
} else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599) {
ApiResponse$new("API server error", resp)
}

}{{#hasMore}},{{/hasMore}}
{{/operation}}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ ApiClient <- R6::R6Class(
headers <- httr::add_headers(c(headerParams, self$defaultHeaders))

if (method == "GET") {
httr::GET(url, queryParams, headers, ...)
httr::GET(url, query = queryParams, headers, ...)
} else if (method == "POST") {
httr::POST(url, query = queryParams, headers, body = body, httr::content_type("application/json"), ...)
} else if (method == "PUT") {
Expand All @@ -88,6 +88,48 @@ ApiClient <- R6::R6Class(
} else {
stop("http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`.")
}
},

deserialize = function(resp, returnType, pkgEnv) {
respObj <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))
self$deserializeObj(respObj, returnType, pkgEnv)
},

deserializeObj = function(obj, returnType, pkgEnv) {
returnObj <- NULL
primitiveTypes <- c("character", "numeric", "integer", "logical", "complex")

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)
} 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))
if (length(obj) > 0) {
for (row in 1:length(obj)) {
returnObj[[row]] <- self$deserializeObj(obj[row], innerReturnType, pkgEnv)
}
}
} else {
returnObj <- 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)
}
}
}
} else if (exists(returnType, pkgEnv) && !(c(returnType) %in% primitiveTypes)) {
returnType <- get(returnType, envir = as.environment(pkgEnv))
returnObj <- returnType$new()
returnObj$fromJSON(jsonlite::toJSON(obj, digits = NA))
} else {
returnObj <- obj
}
returnObj
}
)
)
98 changes: 39 additions & 59 deletions modules/openapi-generator/src/main/resources/r/model.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -132,99 +132,79 @@
{{classname}}Object <- jsonlite::fromJSON({{classname}}Json)
{{#vars}}
if (!is.null({{classname}}Object$`{{baseName}}`)) {
{{#isListContainer}}
{{#isPrimitiveType}}
self$`{{baseName}}` <- {{classname}}Object$`{{baseName}}`
{{/isPrimitiveType}}
{{^isPrimitiveType}}
self$`{{baseName}}` <- sapply({{classname}}Object$`{{baseName}}`, function(x) {
{{baseName}}Object <- {{dataType}}$new()
{{baseName}}Object$fromJSON(jsonlite::toJSON(x, auto_unbox = TRUE))
{{baseName}}Object
})
{{/isPrimitiveType}}
{{/isListContainer}}
{{^isListContainer}}
{{#isContainer}}
self$`{{baseName}}` <- ApiClient$new()$deserializeObj({{classname}}Object$`{{baseName}}`, "{{dataType}}", "package:{{packageName}}")
{{/isContainer}}
{{^isContainer}}
{{#isPrimitiveType}}
self$`{{baseName}}` <- {{classname}}Object$`{{baseName}}`
{{/isPrimitiveType}}
{{^isPrimitiveType}}
{{baseName}}Object <- {{dataType}}$new()
{{baseName}}Object$fromJSON(jsonlite::toJSON({{classname}}Object${{baseName}}, auto_unbox = TRUE))
{{baseName}}Object$fromJSON(jsonlite::toJSON({{classname}}Object${{baseName}}, auto_unbox = TRUE, digits = NA))
self$`{{baseName}}` <- {{baseName}}Object
{{/isPrimitiveType}}
{{/isListContainer}}
{{/isContainer}}
}
{{/vars}}
},
toJSONString = function() {
sprintf(
'{
{{#vars}}
"{{baseName}}":
{{#isListContainer}}
{{#isPrimitiveType}}
{{#isNumeric}}[%d]{{/isNumeric}}{{^isNumeric}}[%s]{{/isNumeric}}{{#hasMore}},{{/hasMore}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
[%s]{{#hasMore}},{{/hasMore}}
{{/isPrimitiveType}}
{{/isListContainer}}
{{^isListContainer}}
{{#isPrimitiveType}}
{{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}"%s"{{/isNumeric}}{{#hasMore}},{{/hasMore}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}
%s{{#hasMore}},{{/hasMore}}
{{/isPrimitiveType}}
{{/isListContainer}}
{{/vars}}
}',
{{#vars}}
jsoncontent <- c(
{{#vars}}
if (!is.null(self$`{{baseName}}`)) {
sprintf(
'"{{baseName}}":
{{#isListContainer}}
{{#isPrimitiveType}}
{{#isNumeric}}[%d]{{/isNumeric}}{{^isNumeric}}[%s]{{/isNumeric}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}[%s]
{{/isPrimitiveType}}
{{/isListContainer}}
{{^isListContainer}}
{{#isPrimitiveType}}
{{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}"%s"{{/isNumeric}}
{{/isPrimitiveType}}
{{^isPrimitiveType}}%s
{{/isPrimitiveType}}
{{/isListContainer}}',
{{#isListContainer}}
{{#isPrimitiveType}}
paste(unlist(lapply(self$`{{{baseName}}}`, function(x) paste0('"', x, '"'))), collapse=","){{#hasMore}},{{/hasMore}}
paste(unlist(lapply(self$`{{{baseName}}}`, function(x) paste0('"', x, '"'))), collapse=",")
{{/isPrimitiveType}}
{{^isPrimitiveType}}
paste(unlist(lapply(self$`{{{baseName}}}`, function(x) jsonlite::toJSON(x$toJSON(), auto_unbox=TRUE))), collapse=","){{#hasMore}},{{/hasMore}}
paste(unlist(lapply(self$`{{{baseName}}}`, function(x) jsonlite::toJSON(x$toJSON(), auto_unbox=TRUE, digits = NA))), collapse=",")
{{/isPrimitiveType}}
{{/isListContainer}}
{{^isListContainer}}
{{#isPrimitiveType}}
self$`{{baseName}}`{{#hasMore}},{{/hasMore}}
self$`{{baseName}}`
{{/isPrimitiveType}}
{{^isPrimitiveType}}
jsonlite::toJSON(self$`{{baseName}}`$toJSON(), auto_unbox=TRUE){{#hasMore}},{{/hasMore}}
jsonlite::toJSON(self$`{{baseName}}`$toJSON(), auto_unbox=TRUE, digits = NA)
{{/isPrimitiveType}}
{{/isListContainer}}
)}{{#hasMore}},{{/hasMore}}
{{/vars}}
)
jsoncontent <- paste(jsoncontent, collapse = ",")
paste('{', jsoncontent, '}', sep = "")
},
fromJSONString = function({{classname}}Json) {
{{classname}}Object <- jsonlite::fromJSON({{classname}}Json)
{{#vars}}
{{#isListContainer}}
{{#isPrimitiveType}}
self$`{{baseName}}` <- lapply({{classname}}Object$`{{baseName}}`, function (x) x)
{{/isPrimitiveType}}
{{^isPrimitiveType}}
data.frame <- {{classname}}Object$`{{baseName}}`
self$`{{baseName}}` <- vector("list", length = nrow(data.frame))
for (row in 1:nrow(data.frame)) {
{{baseName}}.node <- {{dataType}}$new()
{{baseName}}.node$fromJSON(jsonlite::toJSON(data.frame[row,,drop = TRUE], auto_unbox = TRUE))
self$`{{baseName}}`[[row]] <- {{baseName}}.node
}
{{/isPrimitiveType}}
{{/isListContainer}}
{{^isListContainer}}
{{! AAPI - added condition for handling container type of parameters, map and array}}
{{#isContainer}}
self$`{{baseName}}` <- ApiClient$new()$deserializeObj({{classname}}Object$`{{baseName}}`, "{{dataType}}","package:{{packageName}}")
{{/isContainer}}
{{^isContainer}}
{{#isPrimitiveType}}
self$`{{baseName}}` <- {{classname}}Object$`{{baseName}}`
{{/isPrimitiveType}}
{{^isPrimitiveType}}
self$`{{baseName}}` <- {{dataType}}$new()$fromJSON(jsonlite::toJSON({{classname}}Object${{baseName}}, auto_unbox = TRUE))
self$`{{baseName}}` <- {{dataType}}$new()$fromJSON(jsonlite::toJSON({{classname}}Object${{baseName}}, auto_unbox = TRUE, digits = NA))
{{/isPrimitiveType}}
{{/isListContainer}}
{{/isContainer}}
{{/vars}}
self
}
Expand Down
44 changes: 43 additions & 1 deletion samples/client/petstore/R/R/api_client.R
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ ApiClient <- R6::R6Class(
headers <- httr::add_headers(c(headerParams, self$defaultHeaders))

if (method == "GET") {
httr::GET(url, queryParams, headers, ...)
httr::GET(url, query = queryParams, headers, ...)
} else if (method == "POST") {
httr::POST(url, query = queryParams, headers, body = body, httr::content_type("application/json"), ...)
} else if (method == "PUT") {
Expand All @@ -95,6 +95,48 @@ ApiClient <- R6::R6Class(
} else {
stop("http method must be `GET`, `HEAD`, `OPTIONS`, `POST`, `PATCH`, `PUT` or `DELETE`.")
}
},

deserialize = function(resp, returnType, pkgEnv) {
respObj <- jsonlite::fromJSON(httr::content(resp, "text", encoding = "UTF-8"))
self$deserializeObj(respObj, returnType, pkgEnv)
},

deserializeObj = function(obj, returnType, pkgEnv) {
returnObj <- NULL
primitiveTypes <- c("character", "numeric", "integer", "logical", "complex")

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)
} 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))
if (length(obj) > 0) {
for (row in 1:length(obj)) {
returnObj[[row]] <- self$deserializeObj(obj[row], innerReturnType, pkgEnv)
}
}
} else {
returnObj <- 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)
}
}
}
} else if (exists(returnType, pkgEnv) && !(c(returnType) %in% primitiveTypes)) {
returnType <- get(returnType, envir = as.environment(pkgEnv))
returnObj <- returnType$new()
returnObj$fromJSON(jsonlite::toJSON(obj, digits = NA))
} else {
returnObj <- obj
}
returnObj
}
)
)
24 changes: 16 additions & 8 deletions samples/client/petstore/R/R/category.R
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,24 @@ Category <- R6::R6Class(
}
},
toJSONString = function() {
sprintf(
'{
"id":
%d,
"name":
"%s"
}',
self$`id`,
jsoncontent <- c(
if (!is.null(self$`id`)) {
sprintf(
'"id":
%d
',
self$`id`
)},
if (!is.null(self$`name`)) {
sprintf(
'"name":
"%s"
',
self$`name`
)}
)
jsoncontent <- paste(jsoncontent, collapse = ",")
paste('{', jsoncontent, '}', sep = "")
},
fromJSONString = function(CategoryJson) {
CategoryObject <- jsonlite::fromJSON(CategoryJson)
Expand Down
Loading