Use model as body param for generateAliasAsModel (#4569)

* generateAliasAsModel: Use model name as body param

* Update samples
This commit is contained in:
Bodo Graumann 2020-04-17 07:36:27 +02:00 committed by GitHub
parent 5acbbf8878
commit 896867b5e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 207 additions and 171 deletions

View File

@ -5300,132 +5300,7 @@ public class DefaultCodegen implements CodegenConfig {
return codegenParameter;
}
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
if (body == null) {
LOGGER.error("body in fromRequestBody cannot be null!");
throw new RuntimeException("body in fromRequestBody cannot be null!");
}
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
codegenParameter.baseName = "UNKNOWN_BASE_NAME";
codegenParameter.paramName = "UNKNOWN_PARAM_NAME";
codegenParameter.description = escapeText(body.getDescription());
codegenParameter.required = body.getRequired() != null ? body.getRequired() : Boolean.FALSE;
codegenParameter.isBodyParam = Boolean.TRUE;
String name = null;
LOGGER.debug("Request body = " + body);
Schema schema = ModelUtils.getSchemaFromRequestBody(body);
if (schema == null) {
throw new RuntimeException("Request body cannot be null. Possible cause: missing schema in body parameter (OAS v2): " + body);
}
if (StringUtils.isNotBlank(schema.get$ref())) {
name = ModelUtils.getSimpleRef(schema.get$ref());
}
schema = ModelUtils.getReferencedSchema(this.openAPI, schema);
ModelUtils.syncValidationProperties(schema, codegenParameter);
if (ModelUtils.isMapSchema(schema)) {
// Schema with additionalproperties: true (including composed schemas with additionalproperties: true)
Schema inner = ModelUtils.getAdditionalProperties(schema);
if (inner == null) {
LOGGER.error("No inner type supplied for map parameter `{}`. Default to type:string", schema.getName());
inner = new StringSchema().description("//TODO automatically added by openapi-generator");
schema.setAdditionalProperties(inner);
}
CodegenProperty codegenProperty = fromProperty("property", schema);
imports.add(codegenProperty.baseType);
CodegenProperty innerCp = codegenProperty;
while (innerCp != null) {
if (innerCp.complexType != null) {
imports.add(innerCp.complexType);
}
innerCp = innerCp.items;
}
if (StringUtils.isEmpty(bodyParameterName)) {
codegenParameter.baseName = "request_body";
} else {
codegenParameter.baseName = bodyParameterName;
}
codegenParameter.paramName = toParamName(codegenParameter.baseName);
codegenParameter.items = codegenProperty.items;
codegenParameter.mostInnerItems = codegenProperty.mostInnerItems;
codegenParameter.dataType = getTypeDeclaration(schema);
codegenParameter.baseType = getSchemaType(inner);
codegenParameter.isContainer = Boolean.TRUE;
codegenParameter.isMapContainer = Boolean.TRUE;
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
} else if (ModelUtils.isArraySchema(schema)) {
final ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = getSchemaItems(arraySchema);
CodegenProperty codegenProperty = fromProperty("property", arraySchema);
imports.add(codegenProperty.baseType);
CodegenProperty innerCp = codegenProperty;
CodegenProperty mostInnerItem = innerCp;
// loop through multidimensional array to add proper import
// also find the most inner item
while (innerCp != null) {
if (innerCp.complexType != null) {
imports.add(innerCp.complexType);
}
mostInnerItem = innerCp;
innerCp = innerCp.items;
}
if (StringUtils.isEmpty(bodyParameterName)) {
if (StringUtils.isEmpty(mostInnerItem.complexType)) {
codegenParameter.baseName = "request_body";
} else {
codegenParameter.baseName = mostInnerItem.complexType;
}
} else {
codegenParameter.baseName = bodyParameterName;
}
codegenParameter.paramName = toArrayModelParamName(codegenParameter.baseName);
codegenParameter.items = codegenProperty.items;
codegenParameter.mostInnerItems = codegenProperty.mostInnerItems;
codegenParameter.dataType = getTypeDeclaration(arraySchema);
codegenParameter.baseType = getSchemaType(inner);
codegenParameter.isContainer = Boolean.TRUE;
codegenParameter.isListContainer = Boolean.TRUE;
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
while (codegenProperty != null) {
imports.add(codegenProperty.baseType);
codegenProperty = codegenProperty.items;
}
} else if (ModelUtils.isFreeFormObject(schema)) {
// HTTP request body is free form object
CodegenProperty codegenProperty = fromProperty("FREE_FORM_REQUEST_BODY", schema);
if (codegenProperty != null) {
if (StringUtils.isEmpty(bodyParameterName)) {
codegenParameter.baseName = "body"; // default to body
} else {
codegenParameter.baseName = bodyParameterName;
}
codegenParameter.isPrimitiveType = true;
codegenParameter.baseType = codegenProperty.baseType;
codegenParameter.dataType = codegenProperty.dataType;
codegenParameter.description = codegenProperty.description;
codegenParameter.paramName = toParamName(codegenParameter.baseName);
}
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
} else if (ModelUtils.isObjectSchema(schema) || ModelUtils.isComposedSchema(schema)) {
private void addBodyModelSchema(CodegenParameter codegenParameter, String name, Schema schema, Set<String> imports, String bodyParameterName, boolean forceSimpleRef) {
CodegenModel codegenModel = null;
if (StringUtils.isNotBlank(name)) {
schema.setName(name);
@ -5435,7 +5310,7 @@ public class DefaultCodegen implements CodegenConfig {
codegenParameter.isModel = true;
}
if (codegenModel != null && !codegenModel.emptyVars) {
if (codegenModel != null && (codegenModel.hasVars || forceSimpleRef)) {
if (StringUtils.isEmpty(bodyParameterName)) {
codegenParameter.baseName = codegenModel.classname;
} else {
@ -5500,7 +5375,142 @@ public class DefaultCodegen implements CodegenConfig {
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
}
}
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
if (body == null) {
LOGGER.error("body in fromRequestBody cannot be null!");
throw new RuntimeException("body in fromRequestBody cannot be null!");
}
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
codegenParameter.baseName = "UNKNOWN_BASE_NAME";
codegenParameter.paramName = "UNKNOWN_PARAM_NAME";
codegenParameter.description = escapeText(body.getDescription());
codegenParameter.required = body.getRequired() != null ? body.getRequired() : Boolean.FALSE;
codegenParameter.isBodyParam = Boolean.TRUE;
String name = null;
LOGGER.debug("Request body = " + body);
Schema schema = ModelUtils.getSchemaFromRequestBody(body);
if (schema == null) {
throw new RuntimeException("Request body cannot be null. Possible cause: missing schema in body parameter (OAS v2): " + body);
}
if (StringUtils.isNotBlank(schema.get$ref())) {
name = ModelUtils.getSimpleRef(schema.get$ref());
}
schema = ModelUtils.getReferencedSchema(this.openAPI, schema);
ModelUtils.syncValidationProperties(schema, codegenParameter);
if (ModelUtils.isMapSchema(schema)) {
// Schema with additionalproperties: true (including composed schemas with additionalproperties: true)
if (ModelUtils.isGenerateAliasAsModel() && StringUtils.isNotBlank(name)) {
this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true);
} else {
Schema inner = ModelUtils.getAdditionalProperties(schema);
if (inner == null) {
LOGGER.error("No inner type supplied for map parameter `{}`. Default to type:string", schema.getName());
inner = new StringSchema().description("//TODO automatically added by openapi-generator");
schema.setAdditionalProperties(inner);
}
CodegenProperty codegenProperty = fromProperty("property", schema);
imports.add(codegenProperty.baseType);
CodegenProperty innerCp = codegenProperty;
while (innerCp != null) {
if (innerCp.complexType != null) {
imports.add(innerCp.complexType);
}
innerCp = innerCp.items;
}
if (StringUtils.isEmpty(bodyParameterName)) {
codegenParameter.baseName = "request_body";
} else {
codegenParameter.baseName = bodyParameterName;
}
codegenParameter.paramName = toParamName(codegenParameter.baseName);
codegenParameter.items = codegenProperty.items;
codegenParameter.mostInnerItems = codegenProperty.mostInnerItems;
codegenParameter.dataType = getTypeDeclaration(schema);
codegenParameter.baseType = getSchemaType(inner);
codegenParameter.isContainer = Boolean.TRUE;
codegenParameter.isMapContainer = Boolean.TRUE;
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
}
} else if (ModelUtils.isArraySchema(schema)) {
if (ModelUtils.isGenerateAliasAsModel() && StringUtils.isNotBlank(name)) {
this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true);
} else {
final ArraySchema arraySchema = (ArraySchema) schema;
Schema inner = getSchemaItems(arraySchema);
CodegenProperty codegenProperty = fromProperty("property", arraySchema);
imports.add(codegenProperty.baseType);
CodegenProperty innerCp = codegenProperty;
CodegenProperty mostInnerItem = innerCp;
// loop through multidimensional array to add proper import
// also find the most inner item
while (innerCp != null) {
if (innerCp.complexType != null) {
imports.add(innerCp.complexType);
}
mostInnerItem = innerCp;
innerCp = innerCp.items;
}
if (StringUtils.isEmpty(bodyParameterName)) {
if (StringUtils.isEmpty(mostInnerItem.complexType)) {
codegenParameter.baseName = "request_body";
} else {
codegenParameter.baseName = mostInnerItem.complexType;
}
} else {
codegenParameter.baseName = bodyParameterName;
}
codegenParameter.paramName = toArrayModelParamName(codegenParameter.baseName);
codegenParameter.items = codegenProperty.items;
codegenParameter.mostInnerItems = codegenProperty.mostInnerItems;
codegenParameter.dataType = getTypeDeclaration(arraySchema);
codegenParameter.baseType = getSchemaType(inner);
codegenParameter.isContainer = Boolean.TRUE;
codegenParameter.isListContainer = Boolean.TRUE;
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
while (codegenProperty != null) {
imports.add(codegenProperty.baseType);
codegenProperty = codegenProperty.items;
}
}
} else if (ModelUtils.isFreeFormObject(schema)) {
// HTTP request body is free form object
CodegenProperty codegenProperty = fromProperty("FREE_FORM_REQUEST_BODY", schema);
if (codegenProperty != null) {
if (StringUtils.isEmpty(bodyParameterName)) {
codegenParameter.baseName = "body"; // default to body
} else {
codegenParameter.baseName = bodyParameterName;
}
codegenParameter.isPrimitiveType = true;
codegenParameter.baseType = codegenProperty.baseType;
codegenParameter.dataType = codegenProperty.dataType;
codegenParameter.description = codegenProperty.description;
codegenParameter.paramName = toParamName(codegenParameter.baseName);
}
setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty);
// set nullable
setParameterNullable(codegenParameter, codegenProperty);
} else if (ModelUtils.isObjectSchema(schema) || ModelUtils.isComposedSchema(schema)) {
this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, false);
} else {
// HTTP request body is primitive type (e.g. integer, string, etc)
CodegenProperty codegenProperty = fromProperty("PRIMITIVE_REQUEST_BODY", schema);

View File

@ -11,6 +11,7 @@ part 'auth/authentication.dart';
part 'auth/api_key_auth.dart';
part 'auth/oauth.dart';
part 'auth/http_basic_auth.dart';
part 'auth/http_bearer_auth.dart';
part 'api/pet_api.dart';
part 'api/store_api.dart';

View File

@ -0,0 +1,25 @@
part of openapi.api;
class HttpBearerAuth implements Authentication {
dynamic _accessToken;
HttpBearerAuth() { }
@override
void applyToParams(List<QueryParam> queryParams, Map<String, String> headerParams) {
if (_accessToken is String) {
headerParams["Authorization"] = "Bearer " + _accessToken;
} else if (_accessToken is String Function()){
headerParams["Authorization"] = "Bearer " + _accessToken();
} else {
throw ArgumentError('Type of Bearer accessToken should be String or String Function().');
}
}
void setAccessToken(dynamic accessToken) {
if (!((accessToken is String) | (accessToken is String Function()))){
throw ArgumentError('Type of Bearer accessToken should be String or String Function().');
}
this._accessToken = accessToken;
}
}

View File

@ -231,7 +231,7 @@ Optional parameters are passed through a map[string]interface{}.
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**string** | [**string**](string.md)| |
**another_xml_array** | [**AnotherXmlArray**](AnotherXmlArray.md)| |
### Return type
@ -263,7 +263,7 @@ Optional parameters are passed through a map[string]interface{}.
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**string** | [**string**](string.md)| |
**xml_array** | [**XmlArray**](XmlArray.md)| |
### Return type

View File

@ -95,16 +95,16 @@ impl<C> Api<C> for Server<C> where C: Has<XSpanIdString>{
}
fn xml_other_put(&self, string: Option<models::AnotherXmlArray>, context: &C) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>> {
fn xml_other_put(&self, another_xml_array: Option<models::AnotherXmlArray>, context: &C) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>> {
let context = context.clone();
println!("xml_other_put({:?}) - X-Span-ID: {:?}", string, context.get().0.clone());
println!("xml_other_put({:?}) - X-Span-ID: {:?}", another_xml_array, context.get().0.clone());
Box::new(futures::failed("Generic failure".into()))
}
/// Post an array
fn xml_post(&self, string: Option<models::XmlArray>, context: &C) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>> {
fn xml_post(&self, xml_array: Option<models::XmlArray>, context: &C) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>> {
let context = context.clone();
println!("xml_post({:?}) - X-Span-ID: {:?}", string, context.get().0.clone());
println!("xml_post({:?}) - X-Span-ID: {:?}", xml_array, context.get().0.clone());
Box::new(futures::failed("Generic failure".into()))
}

View File

@ -987,7 +987,7 @@ impl<F, C> Api<C> for Client<F> where
}
fn xml_other_put(&self, param_string: Option<models::AnotherXmlArray>, context: &C) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>> {
fn xml_other_put(&self, param_another_xml_array: Option<models::AnotherXmlArray>, context: &C) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>> {
let mut uri = format!(
"{}/xml_other",
self.base_path
@ -1009,7 +1009,7 @@ impl<F, C> Api<C> for Client<F> where
let mut request = hyper::Request::new(hyper::Method::Put, uri);
let body = param_string.map(|ref body| {
let body = param_another_xml_array.map(|ref body| {
body.to_xml()
});
@ -1066,7 +1066,7 @@ impl<F, C> Api<C> for Client<F> where
}
fn xml_post(&self, param_string: Option<models::XmlArray>, context: &C) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>> {
fn xml_post(&self, param_xml_array: Option<models::XmlArray>, context: &C) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>> {
let mut uri = format!(
"{}/xml",
self.base_path
@ -1088,7 +1088,7 @@ impl<F, C> Api<C> for Client<F> where
let mut request = hyper::Request::new(hyper::Method::Post, uri);
let body = param_string.map(|ref body| {
let body = param_xml_array.map(|ref body| {
body.to_xml()
});

View File

@ -199,10 +199,10 @@ pub trait Api<C> {
fn xml_other_post(&self, another_xml_object: Option<models::AnotherXmlObject>, context: &C) -> Box<dyn Future<Item=XmlOtherPostResponse, Error=ApiError>>;
fn xml_other_put(&self, string: Option<models::AnotherXmlArray>, context: &C) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>>;
fn xml_other_put(&self, another_xml_array: Option<models::AnotherXmlArray>, context: &C) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>>;
/// Post an array
fn xml_post(&self, string: Option<models::XmlArray>, context: &C) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>>;
fn xml_post(&self, xml_array: Option<models::XmlArray>, context: &C) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>>;
fn xml_put(&self, xml_object: Option<models::XmlObject>, context: &C) -> Box<dyn Future<Item=XmlPutResponse, Error=ApiError>>;
@ -237,10 +237,10 @@ pub trait ApiNoContext {
fn xml_other_post(&self, another_xml_object: Option<models::AnotherXmlObject>) -> Box<dyn Future<Item=XmlOtherPostResponse, Error=ApiError>>;
fn xml_other_put(&self, string: Option<models::AnotherXmlArray>) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>>;
fn xml_other_put(&self, another_xml_array: Option<models::AnotherXmlArray>) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>>;
/// Post an array
fn xml_post(&self, string: Option<models::XmlArray>) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>>;
fn xml_post(&self, xml_array: Option<models::XmlArray>) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>>;
fn xml_put(&self, xml_object: Option<models::XmlObject>) -> Box<dyn Future<Item=XmlPutResponse, Error=ApiError>>;
@ -302,13 +302,13 @@ impl<'a, T: Api<C>, C> ApiNoContext for ContextWrapper<'a, T, C> {
}
fn xml_other_put(&self, string: Option<models::AnotherXmlArray>) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>> {
self.api().xml_other_put(string, &self.context())
fn xml_other_put(&self, another_xml_array: Option<models::AnotherXmlArray>) -> Box<dyn Future<Item=XmlOtherPutResponse, Error=ApiError>> {
self.api().xml_other_put(another_xml_array, &self.context())
}
/// Post an array
fn xml_post(&self, string: Option<models::XmlArray>) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>> {
self.api().xml_post(string, &self.context())
fn xml_post(&self, xml_array: Option<models::XmlArray>) -> Box<dyn Future<Item=XmlPostResponse, Error=ApiError>> {
self.api().xml_post(xml_array, &self.context())
}

View File

@ -687,19 +687,19 @@ where
match result {
Ok(body) => {
let mut unused_elements = Vec::new();
let param_string: Option<models::AnotherXmlArray> = if !body.is_empty() {
let param_another_xml_array: Option<models::AnotherXmlArray> = if !body.is_empty() {
let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body);
match serde_ignored::deserialize(deserializer, |path| {
warn!("Ignoring unknown field in body: {}", path);
unused_elements.push(path.to_string());
}) {
Ok(param_string) => param_string,
Ok(param_another_xml_array) => param_another_xml_array,
Err(_) => None,
}
} else {
None
};
Box::new(api_impl.xml_other_put(param_string, &context)
Box::new(api_impl.xml_other_put(param_another_xml_array, &context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
@ -737,7 +737,7 @@ where
}
))
},
Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter string: {}", e)))),
Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter AnotherXmlArray: {}", e)))),
}
})
) as Box<dyn Future<Item=Response, Error=Error>>
@ -753,19 +753,19 @@ where
match result {
Ok(body) => {
let mut unused_elements = Vec::new();
let param_string: Option<models::XmlArray> = if !body.is_empty() {
let param_xml_array: Option<models::XmlArray> = if !body.is_empty() {
let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body);
match serde_ignored::deserialize(deserializer, |path| {
warn!("Ignoring unknown field in body: {}", path);
unused_elements.push(path.to_string());
}) {
Ok(param_string) => param_string,
Ok(param_xml_array) => param_xml_array,
Err(_) => None,
}
} else {
None
};
Box::new(api_impl.xml_post(param_string, &context)
Box::new(api_impl.xml_post(param_xml_array, &context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
@ -803,7 +803,7 @@ where
}
))
},
Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter string: {}", e)))),
Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter XmlArray: {}", e)))),
}
})
) as Box<dyn Future<Item=Response, Error=Error>>