From 1cd330b025f4d8d6f21ee2f5fa9fba606d21ddad Mon Sep 17 00:00:00 2001 From: Richard Whitehouse Date: Sat, 10 Aug 2024 12:29:39 +0100 Subject: [PATCH 1/6] [Core/Rust Server] Support multiple request body/response body types Support a request / response which can have multiple body content types e.g. requestBody: content: application/json: schema: type: string application/xml: schema: type: string responses: 200: content: application/json: type: string application/xml: type: string --- .../openapitools/codegen/CodegenModel.java | 5 +- .../codegen/CodegenParameter.java | 31 +- .../openapitools/codegen/CodegenResponse.java | 37 +- .../openapitools/codegen/DefaultCodegen.java | 770 ++++++++++++------ .../codegen/DefaultGenerator.java | 2 +- .../languages/AbstractApexCodegen.java | 2 +- .../languages/AbstractJavaCodegen.java | 2 +- .../languages/CppPistacheServerCodegen.java | 2 +- .../languages/CppRestSdkClientCodegen.java | 2 +- .../languages/ElixirClientCodegen.java | 4 +- .../languages/JavaHelidonCommonCodegen.java | 4 +- .../languages/JavaHelidonServerCodegen.java | 4 +- .../codegen/languages/K6ClientCodegen.java | 6 +- .../KotlinWiremockServerCodegen.java | 4 +- .../PhpDataTransferClientCodegen.java | 2 +- .../languages/RustAxumServerCodegen.java | 6 +- .../codegen/languages/RustServerCodegen.java | 422 +++++----- .../codegen/languages/SpringCodegen.java | 2 +- .../TypeScriptFetchClientCodegen.java | 11 +- .../languages/ZapierClientCodegen.java | 4 +- .../codegen/utils/ModelUtils.java | 92 ++- .../rust-server/client-imports.mustache | 3 +- .../rust-server/client-operation.mustache | 9 +- .../client-request-body-instance.mustache | 6 - .../rust-server/client-request-body.mustache | 40 + .../client-response-body-instance.mustache | 1 + .../rust-server/client-response-body.mustache | 30 + .../resources/rust-server/models.mustache | 2 +- .../rust-server/server-imports.mustache | 3 +- .../rust-server/server-operation.mustache | 12 +- .../rust-server/server-request-body.mustache | 103 +++ .../server-response-body-instance.mustache | 5 +- .../rust-server/server-response-body.mustache | 16 + .../codegen/DefaultCodegenTest.java | 22 +- .../codegen/DefaultGeneratorTest.java | 6 +- .../codegen/java/JavaClientCodegenTest.java | 8 +- 36 files changed, 1154 insertions(+), 526 deletions(-) create mode 100644 modules/openapi-generator/src/main/resources/rust-server/client-request-body.mustache create mode 100644 modules/openapi-generator/src/main/resources/rust-server/client-response-body.mustache create mode 100644 modules/openapi-generator/src/main/resources/rust-server/server-request-body.mustache create mode 100644 modules/openapi-generator/src/main/resources/rust-server/server-response-body.mustache diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index 41a3a176ab2a..bbb00d1345fd 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java @@ -124,6 +124,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties { @Getter @Setter public String arrayModelType; public boolean isAlias; // Is this effectively an alias of another simple type + public boolean isVariant; // Does this represent a schema variant? public boolean isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, isDate, isDateTime, isDecimal, isShort, isUnboundedInteger, isPrimitiveType, isBoolean, isFreeFormObject; private boolean additionalPropertiesIsAnyType; @@ -866,6 +867,7 @@ public boolean equals(Object o) { if (!(o instanceof CodegenModel)) return false; CodegenModel that = (CodegenModel) o; return isAlias == that.isAlias && + isVariant == that.isVariant && isString == that.isString && isInteger == that.isInteger && isShort == that.isShort && @@ -978,7 +980,7 @@ public int hashCode() { getInterfaceModels(), getChildren(), anyOf, oneOf, allOf, getName(), getSchemaName(), getClassname(), getTitle(), getDescription(), getClassVarName(), getModelJson(), getDataType(), getXmlPrefix(), getXmlNamespace(), getXmlName(), getClassFilename(), getUnescapedDescription(), getDiscriminator(), getDefaultValue(), - getArrayModelType(), isAlias, isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, + getArrayModelType(), isAlias, isVariant, isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, isDate, isDateTime, isNull, hasValidation, isShort, isUnboundedInteger, isBoolean, getVars(), getAllVars(), getNonNullableVars(), getRequiredVars(), getOptionalVars(), getReadOnlyVars(), getReadWriteVars(), getParentVars(), getAllowableValues(), getMandatory(), getAllMandatory(), getImports(), hasVars, @@ -1023,6 +1025,7 @@ public String toString() { sb.append(", defaultValue='").append(defaultValue).append('\''); sb.append(", arrayModelType='").append(arrayModelType).append('\''); sb.append(", isAlias=").append(isAlias); + sb.append(", isVariant=").append(isVariant); sb.append(", isString=").append(isString); sb.append(", isInteger=").append(isInteger); sb.append(", isShort=").append(isShort); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index 0497bf49c55b..bb6539b7cede 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -125,6 +125,19 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { * See JSON Schema Validation Spec, Section 6.2.1 */ public Number multipleOf; + /** + * If this is a body parameter, we might have several different variants + * depending on which content type is used. + */ + public List schemaVariants; + /** + * If this is a schema variant, this gives the schema variant type + */ + public String variantType; + /** + * If this is a body schema, representing a simple form, these are the form parameters + */ + public List formParams; private Integer maxProperties; private Integer minProperties; public boolean isNull; @@ -241,6 +254,12 @@ public CodegenParameter copy() { if (this.ref != null) { output.setRef(this.ref); } + if (this.schemaVariants != null) { + output.schemaVariants = new ArrayList(this.schemaVariants); + } + if (this.formParams != null) { + output.formParams = new ArrayList(this.formParams); + } output.hasValidation = this.hasValidation; output.isNullable = this.isNullable; output.isDeprecated = this.isDeprecated; @@ -274,6 +293,7 @@ public CodegenParameter copy() { output.isMatrix = this.isMatrix; output.isAllowEmptyValue = this.isAllowEmptyValue; output.contentType = this.contentType; + output.variantType = this.variantType; return output; } @@ -295,7 +315,8 @@ public int hashCode() { additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content, requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties, - nameInPascalCase, nameInCamelCase, nameInLowerCase, nameInSnakeCase); + nameInPascalCase, nameInCamelCase, nameInLowerCase, nameInSnakeCase, + schemaVariants, variantType, formParams); } @Override @@ -401,7 +422,10 @@ public boolean equals(Object o) { Objects.equals(getMaxItems(), that.getMaxItems()) && Objects.equals(getMinItems(), that.getMinItems()) && Objects.equals(contentType, that.contentType) && - Objects.equals(multipleOf, that.multipleOf); + Objects.equals(multipleOf, that.multipleOf) && + Objects.equals(formParams, that.formParams) && + Objects.equals(schemaVariants, that.schemaVariants) && + Objects.equals(variantType, that.variantType); } /** @@ -515,6 +539,9 @@ public String toString() { sb.append(", requiredVarsMap=").append(requiredVarsMap); sb.append(", ref=").append(ref); sb.append(", schemaIsFromAdditionalProperties=").append(schemaIsFromAdditionalProperties); + sb.append(", schemaVariants=").append(schemaVariants); + sb.append(", variantType=").append(variantType); + sb.append(", formParams=").append(formParams); sb.append('}'); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index 9c8dc08aaa5f..b8c5ee0ef83c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -105,6 +105,32 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public CodegenProperty returnProperty; private boolean schemaIsFromAdditionalProperties; + /** + * mime-type of this response. + * + * Null if there are multiple options, in which case schemaVariants + * will contain a CodegenResponse for each option + */ + public String contentType; + + /** + * If the response has multiple possible mime types, this array represents + * the options + */ + public List schemaVariants; + + /** + * Name of the variant type if this is one of multiple variants + */ + public String variantType; + + /** + * This is required if the response is some form of complex body type. + * + * e.g. multipart/related or form parameters + */ + public List formParams = new ArrayList(); + @Override public int hashCode() { return Objects.hash(headers, code, message, examples, dataType, baseType, containerType, containerTypeMapped, hasHeaders, @@ -116,7 +142,8 @@ public int hashCode() { getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern(), is1xx, is2xx, is3xx, is4xx, is5xx, additionalPropertiesIsAnyType, hasVars, hasRequired, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, responseHeaders, content, - requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties); + requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties, + contentType, schemaVariants, variantType); } @Override @@ -200,7 +227,10 @@ public boolean equals(Object o) { Objects.equals(getMinimum(), that.getMinimum()) && Objects.equals(getMaximum(), that.getMaximum()) && Objects.equals(getPattern(), that.getPattern()) && - Objects.equals(getMultipleOf(), that.getMultipleOf()); + Objects.equals(getMultipleOf(), that.getMultipleOf()) && + Objects.equals(schemaVariants, that.schemaVariants) && + Objects.equals(contentType, that.contentType) && + Objects.equals(variantType, that.variantType); } @@ -635,6 +665,9 @@ public String toString() { sb.append(", requiredVarsMap=").append(requiredVarsMap); sb.append(", ref=").append(ref); sb.append(", schemaIsFromAdditionalProperties=").append(schemaIsFromAdditionalProperties); + sb.append(", contentType='").append(contentType).append('\''); + sb.append(", variantType='").append(variantType).append('\''); + sb.append(", schemaVariants=").append(schemaVariants); sb.append('}'); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index eaedf606cade..1dba3ec86a78 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -252,6 +252,14 @@ apiTemplateFiles are for API outputs only (controllers/handlers). */ protected boolean supportsAdditionalPropertiesWithComposedSchema; protected boolean supportsMixins; + /** + * Supports multiple request types (e.g. application/json + application/xml) + */ + protected boolean supportsMultipleRequestTypes; + /** + * Supports multiple response types (e.g. application/json + application/xml) + */ + protected boolean supportsMultipleResponseTypes; protected Map supportedLibraries = new LinkedHashMap<>(); protected String library; @Getter @Setter @@ -435,10 +443,74 @@ private void registerMustacheLambdas() { additionalProperties.put("lambda", lambdas); } + @SuppressWarnings({"static-method"}) + public ModelsMap createModelForVariant(CodegenModel cm) { + // We need to force this not to be an alias, as we need to provide some way + // to know what mime type the caller meant. + cm.isVariant = true; + ModelMap modelMap = new ModelMap(); + modelMap.setModel(cm); + ModelsMap modelsMap = new ModelsMap(); + modelsMap.setModels(Arrays.asList(modelMap)); + LOGGER.debug("Adding model for request/response variant schema: " + cm.name); + + return modelsMap; + } + + public void generateVariantModelsForPathItems(Map items, Map objs) { + if (items != null) { + for (Map.Entry e : items.entrySet()) { + for (Map.Entry op : e.getValue().readOperationsMap().entrySet()) { + generateVariantModelsForOperation(op.getKey(), op.getValue(), e.getKey(), objs); + } + } + } + } + + public void generateVariantModelsForOperation(PathItem.HttpMethod method, Operation op, String key, Map objs) { + if (supportsMultipleRequestTypes || supportsMultipleResponseTypes) { + String opId = getOrGenerateOperationId(op, key, method.toString()); + RequestBody b = ModelUtils.getReferencedRequestBody(openAPI, op.getRequestBody()); + Map requestSchemas = null; + if (b != null) { + requestSchemas = ModelUtils.getSchemasFromRequestBody(b); + } + if (requestSchemas != null) { + if (requestSchemas.size() > 1 && supportsMultipleRequestTypes) { + for (Map.Entry entry : requestSchemas.entrySet()) { + CodegenModel cm = fromModel(opId + "_" + entry.getKey() + "_Request", entry.getValue()); + LOGGER.debug("Created model: " + cm + " from request schema: " + entry.getValue()); + objs.put(cm.name, createModelForVariant(cm)); + } + } + } + if (op.getResponses() != null) { + for (Map.Entry ar : op.getResponses().entrySet()) { + ApiResponse a = ModelUtils.getReferencedApiResponse(openAPI, ar.getValue()); + Map responseSchemas = ModelUtils.getSchemasFromResponse(openAPI, a); + if (responseSchemas != null && responseSchemas.size() > 1 && supportsMultipleResponseTypes) { + for (Map.Entry entry : responseSchemas.entrySet()) { + CodegenModel cm = fromModel(opId + "_" + ar.getKey() + "_" + entry.getKey() + "_Response", entry.getValue()); + objs.put(cm.name, createModelForVariant(cm)); + LOGGER.debug("Created model: " + cm + " from response schema: " + entry.getValue()); + } + } + } + } + if (op.getCallbacks() != null) { + for (Map.Entry callback : op.getCallbacks().entrySet()) { + generateVariantModelsForPathItems(callback.getValue(), objs); + } + } + } + } + // override with any special post-processing for all models @Override @SuppressWarnings("static-method") public Map postProcessAllModels(Map objs) { + generateVariantModelsForPathItems(openAPI.getPaths(), objs); + for (Map.Entry entry : objs.entrySet()) { CodegenModel model = ModelUtils.getModelByName(entry.getKey(), objs); @@ -1008,20 +1080,36 @@ public void preprocessOpenAPI(OpenAPI openAPI) { String opId = getOrGenerateOperationId(op.getValue(), e.getKey(), op.getKey().toString()); // process request body RequestBody b = ModelUtils.getReferencedRequestBody(openAPI, op.getValue().getRequestBody()); - Schema requestSchema = null; + Map requestSchemas = null; if (b != null) { - requestSchema = ModelUtils.getSchemaFromRequestBody(b); + requestSchemas = ModelUtils.getSchemasFromRequestBody(b); } - if (requestSchema != null) { - schemas.put(opId, requestSchema); + if (requestSchemas != null) { + if (requestSchemas.size() > 1 && supportsMultipleRequestTypes) { + for (Map.Entry entry : requestSchemas.entrySet()) { + schemas.put(opId + "_" + entry.getKey() + "_Request", entry.getValue()); + } + } else { + for (Map.Entry entry : requestSchemas.entrySet()) { + schemas.put(opId, entry.getValue()); + break; + } + } } // process all response bodies - if (op.getValue().getResponses() != null) { - for (Map.Entry ar : op.getValue().getResponses().entrySet()) { + ApiResponses responses = op.getValue().getResponses(); + if (responses != null) { + for (Map.Entry ar : responses.entrySet()) { ApiResponse a = ModelUtils.getReferencedApiResponse(openAPI, ar.getValue()); - Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, a)); - if (responseSchema != null) { - schemas.put(opId + ar.getKey(), responseSchema); + Map responseSchemas = ModelUtils.getSchemasFromResponse(openAPI, a); + if (responseSchemas != null && responseSchemas.size() > 0) { + if (responseSchemas.size() > 1 && supportsMultipleResponseTypes) { + for (Map.Entry entry : responseSchemas.entrySet()) { + schemas.put(opId + "_" + ar.getKey() + "_" + entry.getKey() + "_Response", entry.getValue()); + } + } else { + schemas.put(opId + ar.getKey(), responseSchemas.values().iterator().next()); + } } } } @@ -2038,7 +2126,7 @@ public void setParameterExampleValue(CodegenParameter codegenParameter, RequestB Content content = requestBody.getContent(); if (content.size() > 1) { - // @see ModelUtils.getSchemaFromContent() + // @see ModelUtils.getFirstSchemaFromContent() once(LOGGER).debug("Multiple MediaTypes found, using only the first one"); } @@ -2308,6 +2396,17 @@ public Schema unaliasSchema(Schema schema) { return ModelUtils.unaliasSchema(this.openAPI, schema, schemaMapping); } + /** + * Return the name of a variant schema + * + * @param names List of names + * @return name of the oneOf schema + */ + @SuppressWarnings("static-method") + public String toVariantName(List names) { + return "oneOf<" + String.join(",", names) + ">"; + } + /** * Return a string representation of the schema type, resolving aliasing and references if necessary. * @@ -4350,7 +4449,7 @@ protected void handleMethodResponse(Operation operation, CodegenOperation op, ApiResponse methodResponse, Map schemaMappings) { - Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, methodResponse)); + Schema responseSchema = unaliasSchema(ModelUtils.getFirstSchemaFromResponse(openAPI, methodResponse)); if (responseSchema != null) { CodegenProperty cm = fromProperty("response", responseSchema, false); @@ -4471,7 +4570,7 @@ public CodegenOperation fromOperation(String path, String key = operationGetResponsesEntry.getKey(); ApiResponse response = operationGetResponsesEntry.getValue(); addProducesInfo(response, op); - CodegenResponse r = fromResponse(key, response); + CodegenResponse r = fromResponse(op.operationId, key, response); Map headers = response.getHeaders(); if (headers != null) { List responseHeaders = new ArrayList<>(); @@ -4540,7 +4639,7 @@ public CodegenOperation fromOperation(String path, for (String statusCode : operation.getResponses().keySet()) { ApiResponse apiResponse = operation.getResponses().get(statusCode); - Schema schema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, apiResponse)); + Schema schema = unaliasSchema(ModelUtils.getFirstSchemaFromResponse(openAPI, apiResponse)); if (schema == null) { continue; } @@ -4584,37 +4683,54 @@ public CodegenOperation fromOperation(String path, CodegenParameter bodyParam = null; RequestBody requestBody = ModelUtils.getReferencedRequestBody(this.openAPI, operation.getRequestBody()); if (requestBody != null) { - String contentType = getContentType(requestBody); - if (contentType != null) { - contentType = contentType.toLowerCase(Locale.ROOT); - } - if (contentType != null && - ((!(this instanceof RustAxumServerCodegen) && contentType.startsWith("application/x-www-form-urlencoded")) || - contentType.startsWith("multipart"))) { - // process form parameters - formParams = fromRequestBodyToFormParameters(requestBody, imports); - op.isMultipart = contentType.startsWith("multipart"); - for (CodegenParameter cp : formParams) { - setParameterEncodingValues(cp, requestBody.getContent().get(contentType)); - postProcessParameter(cp); - } - // add form parameters to the beginning of all parameter list - if (prependFormOrBodyParameters) { + LOGGER.debug("Op: " + op.operationId + " has request body"); + + requestBody = ModelUtils.getReferencedRequestBody(this.openAPI, requestBody); + + Map bodySchemas = ModelUtils.getSchemasFromRequestBody(requestBody); + + boolean simpleForm = false; + + if (bodySchemas != null && bodySchemas.size() == 1) { + LOGGER.debug("Op: " + op.operationId + " has request body with single schema"); + + Map.Entry entry = bodySchemas.entrySet().iterator().next(); + + if (!(this instanceof RustAxumServerCodegen) && isForm(entry.getKey())) { + simpleForm = true; + + LOGGER.debug("Op: " + op.operationId + " has request body with simple form"); + + // process form parameters + Schema bodySchema = ModelUtils.getReferencedSchema(this.openAPI, entry.getValue()); + formParams = fromSchemaToFormParameters(bodySchema, requestBody.getContent().get(entry.getKey()), imports); + String contentType = entry.getKey().toLowerCase(Locale.ROOT); + op.isMultipart = contentType.startsWith("multipart"); for (CodegenParameter cp : formParams) { - allParams.add(cp.copy()); + setParameterEncodingValues(cp, requestBody.getContent().get(contentType)); + postProcessParameter(cp); + } + // add form parameters to the beginning of all parameter list + if (prependFormOrBodyParameters) { + for (CodegenParameter cp : formParams) { + allParams.add(cp.copy()); + } } } - } else { + } + + if (!simpleForm) { // process body parameter String bodyParameterName = ""; if (op.vendorExtensions != null && op.vendorExtensions.containsKey("x-codegen-request-body-name")) { bodyParameterName = (String) op.vendorExtensions.get("x-codegen-request-body-name"); } + if (requestBody.getExtensions() != null && requestBody.getExtensions().containsKey("x-codegen-request-body-name")) { bodyParameterName = (String) requestBody.getExtensions().get("x-codegen-request-body-name"); } - bodyParam = fromRequestBody(requestBody, imports, bodyParameterName); + bodyParam = fromRequestBody(requestBody, op.operationId, imports, bodyParameterName); if (bodyParam != null) { bodyParam.description = escapeText(requestBody.getDescription()); @@ -4783,7 +4899,7 @@ public boolean isParameterNameUnique(CodegenParameter p, List * @param response OAS Response object * @return Codegen Response object */ - public CodegenResponse fromResponse(String responseCode, ApiResponse response) { + public CodegenResponse fromResponse(String opId, String responseCode, ApiResponse response) { CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE); if ("default".equals(responseCode) || "defaultResponse".equals(responseCode)) { @@ -4813,139 +4929,189 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { } } - Schema responseSchema; - if (this.openAPI != null && this.openAPI.getComponents() != null) { - responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, response)); - } else { // no model/alias defined - responseSchema = ModelUtils.getSchemaFromResponse(openAPI, response); - } - r.schema = responseSchema; r.message = escapeText(response.getDescription()); + r.jsonSchema = Json.pretty(response); // TODO need to revise and test examples in responses // ApiResponse does not support examples at the moment //r.examples = toExamples(response.getExamples()); - r.jsonSchema = Json.pretty(response); if (response.getExtensions() != null && !response.getExtensions().isEmpty()) { r.vendorExtensions.putAll(response.getExtensions()); } addHeaders(response, r.headers); r.hasHeaders = !r.headers.isEmpty(); - if (r.schema == null) { + CodegenResponse baseResponse = r; + + Map schemas = ModelUtils.getSchemasFromResponse(openAPI, response); + + if (schemas == null || schemas.size() == 0) { r.primitiveType = true; r.simpleType = true; - return r; - } - - ModelUtils.syncValidationProperties(responseSchema, r); - if (responseSchema.getPattern() != null) { - r.setPattern(toRegularExpression(responseSchema.getPattern())); - } + } else { + if ((schemas.size() > 1) && supportsMultipleResponseTypes) { + r.schemaVariants = new ArrayList(schemas.size()); - CodegenProperty cp = fromProperty("response", responseSchema, false); - r.dataType = getTypeDeclaration(responseSchema); - r.returnProperty = cp; + List names = new ArrayList<>(); - if (!ModelUtils.isArraySchema(responseSchema)) { - if (cp.complexType != null) { - if (cp.items != null) { - r.baseType = cp.items.complexType; - } else { - r.baseType = cp.complexType; + for (String mimeType : schemas.keySet()) { + // We'll generate this during post processing + names.add(toModelName(opId + "_" + responseCode + "_" + mimeType + "_Response")); } - r.isModel = true; - } else { - r.baseType = cp.baseType; + String dataType = toVariantName(names); + r.dataType = dataType; } - } - r.setTypeProperties(responseSchema); - r.setComposedSchemas(getComposedSchemas(responseSchema)); - if (ModelUtils.isArraySchema(responseSchema)) { - r.simpleType = false; - r.isArray = true; - r.containerType = cp.containerType; - r.containerTypeMapped = typeMapping.get(cp.containerType); - CodegenProperty items = fromProperty("response", ModelUtils.getSchemaItems(responseSchema), false); - r.setItems(items); - CodegenProperty innerCp = items; + for (Map.Entry entry : schemas.entrySet()) { + if (schemas.size() > 1 && supportsMultipleResponseTypes) { + r = new CodegenResponse(); + baseResponse.schemaVariants.add(r); + r.variantType = toModelName(opId + "_" + responseCode + "_" + entry.getKey() + "_Response"); + } - while (innerCp != null) { - r.baseType = innerCp.baseType; - innerCp = innerCp.items; - } - } else if (ModelUtils.isFileSchema(responseSchema) && !ModelUtils.isStringSchema(responseSchema)) { - // swagger v2 only, type file - r.isFile = true; - } else if (ModelUtils.isStringSchema(responseSchema)) { - if (ModelUtils.isEmailSchema(responseSchema)) { - r.isEmail = true; - } else if (ModelUtils.isPasswordSchema(responseSchema)) { - r.isPassword = true; - } else if (ModelUtils.isUUIDSchema(responseSchema)) { - r.isUuid = true; - } else if (ModelUtils.isByteArraySchema(responseSchema)) { - r.setIsString(false); - r.isByteArray = true; - } else if (ModelUtils.isBinarySchema(responseSchema)) { - r.isFile = true; // file = binary in OAS3 - r.isBinary = true; - } else if (ModelUtils.isDateSchema(responseSchema)) { - r.setIsString(false); // for backward compatibility with 2.x - r.isDate = true; - } else if (ModelUtils.isDateTimeSchema(responseSchema)) { - r.setIsString(false); // for backward compatibility with 2.x - r.isDateTime = true; - } else if (ModelUtils.isDecimalSchema(responseSchema)) { // type: string, format: number - r.isDecimal = true; - r.setIsString(false); - r.isNumeric = true; - } - } else if (ModelUtils.isIntegerSchema(responseSchema)) { // integer type - r.isNumeric = Boolean.TRUE; - if (ModelUtils.isLongSchema(responseSchema)) { // int64/long format - r.isLong = Boolean.TRUE; - } else { - r.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int - if (ModelUtils.isShortSchema(responseSchema)) { // int32 - r.setIsShort(Boolean.TRUE); + r.contentType = entry.getKey(); + + Schema responseSchema = entry.getValue(); + + if (isForm(r.contentType)) { + Schema formSchema = ModelUtils.getReferencedSchema(this.openAPI, responseSchema); + r.formParams = fromSchemaToFormParameters(formSchema, + response.getContent().get(r.contentType), new TreeSet()); + LOGGER.info("Created form parameters for " + opId + "-" + responseCode + " :: " + r.formParams); } - } - } else if (ModelUtils.isNumberSchema(responseSchema)) { - r.isNumeric = Boolean.TRUE; - if (ModelUtils.isFloatSchema(responseSchema)) { // float - r.isFloat = Boolean.TRUE; - } else if (ModelUtils.isDoubleSchema(responseSchema)) { // double - r.isDouble = Boolean.TRUE; - } - } else if (ModelUtils.isTypeObjectSchema(responseSchema)) { - if (ModelUtils.isFreeFormObject(responseSchema)) { - r.isFreeFormObject = true; - } else { - r.isModel = true; - } - r.simpleType = false; - r.containerType = cp.containerType; - r.containerTypeMapped = cp.containerTypeMapped; - addVarsRequiredVarsAdditionalProps(responseSchema, r); - } else if (ModelUtils.isAnyType(responseSchema)) { - addVarsRequiredVarsAdditionalProps(responseSchema, r); - } else if (!ModelUtils.isBooleanSchema(responseSchema)) { - // referenced schemas - LOGGER.debug("Property type is not primitive: {}", cp.dataType); - } - r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType)); + if (this.openAPI != null && + this.openAPI.getComponents() != null && + !ModelUtils.isGenerateAliasAsModel()) + { + responseSchema = ModelUtils.unaliasSchema(this.openAPI, responseSchema); + } - if (r.baseType == null) { - r.isMap = false; - r.isArray = false; - r.primitiveType = true; - r.simpleType = true; + r.schema = responseSchema; + + if (r.schema == null) { + r.primitiveType = true; + r.simpleType = true; + } else { + ModelUtils.syncValidationProperties(responseSchema, r); + + if (responseSchema.getPattern() != null) { + r.setPattern(toRegularExpression(responseSchema.getPattern())); + } + + CodegenProperty cp = fromProperty("response", responseSchema); + r.dataType = getTypeDeclaration(responseSchema); + r.returnProperty = cp; + + if (!ModelUtils.isArraySchema(responseSchema)) { + if (cp.complexType != null) { + if (cp.items != null) { + r.baseType = cp.items.complexType; + } else { + r.baseType = cp.complexType; + } + r.isModel = true; + } else { + r.baseType = cp.baseType; + } + } + + r.setTypeProperties(responseSchema); + r.setComposedSchemas(getComposedSchemas(responseSchema)); + if (ModelUtils.isArraySchema(responseSchema)) { + r.simpleType = false; + r.isArray = true; + r.containerType = cp.containerType; + r.containerTypeMapped = typeMapping.get(cp.containerType); + CodegenProperty items = fromProperty("response", ModelUtils.getSchemaItems(responseSchema), false); + r.setItems(items); + CodegenProperty innerCp = items; + + while (innerCp != null) { + r.baseType = innerCp.baseType; + innerCp = innerCp.items; + } + } else if (ModelUtils.isFileSchema(responseSchema) && !ModelUtils.isStringSchema(responseSchema)) { + // swagger v2 only, type file + r.isFile = true; + } else if (ModelUtils.isStringSchema(responseSchema)) { + if (ModelUtils.isEmailSchema(responseSchema)) { + r.isEmail = true; + } else if (ModelUtils.isPasswordSchema(responseSchema)) { + r.isPassword = true; + } else if (ModelUtils.isUUIDSchema(responseSchema)) { + r.isUuid = true; + } else if (ModelUtils.isByteArraySchema(responseSchema)) { + r.setIsString(false); + r.isByteArray = true; + } else if (ModelUtils.isBinarySchema(responseSchema)) { + r.isFile = true; // file = binary in OAS3 + r.isBinary = true; + } else if (ModelUtils.isDateSchema(responseSchema)) { + r.setIsString(false); // for backward compatibility with 2.x + r.isDate = true; + } else if (ModelUtils.isDateTimeSchema(responseSchema)) { + r.setIsString(false); // for backward compatibility with 2.x + r.isDateTime = true; + } else if (ModelUtils.isDecimalSchema(responseSchema)) { // type: string, format: number + r.isDecimal = true; + r.setIsString(false); + r.isNumeric = true; + } + } else if (ModelUtils.isIntegerSchema(responseSchema)) { // integer type + r.isNumeric = Boolean.TRUE; + if (ModelUtils.isLongSchema(responseSchema)) { // int64/long format + r.isLong = Boolean.TRUE; + } else { + r.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int + if (ModelUtils.isShortSchema(responseSchema)) { // int32 + r.setIsShort(Boolean.TRUE); + } + } + } else if (ModelUtils.isNumberSchema(responseSchema)) { + r.isNumeric = Boolean.TRUE; + if (ModelUtils.isFloatSchema(responseSchema)) { // float + r.isFloat = Boolean.TRUE; + } else if (ModelUtils.isDoubleSchema(responseSchema)) { // double + r.isDouble = Boolean.TRUE; + } + } else if (ModelUtils.isTypeObjectSchema(responseSchema)) { + if (ModelUtils.isFreeFormObject(responseSchema)) { + r.isFreeFormObject = true; + } else { + r.isModel = true; + } + r.simpleType = false; + r.containerType = cp.containerType; + r.containerTypeMapped = cp.containerTypeMapped; + addVarsRequiredVarsAdditionalProps(responseSchema, r); + } else if (ModelUtils.isAnyType(responseSchema)) { + addVarsRequiredVarsAdditionalProps(responseSchema, r); + } else if (!ModelUtils.isBooleanSchema(responseSchema)) { + // referenced schemas + LOGGER.debug("Property type is not primitive: {}", cp.dataType); + } + + r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType)); + + if (r.baseType == null) { + r.isMap = false; + r.isArray = false; + r.primitiveType = true; + r.simpleType = true; + } + + postProcessResponseWithProperty(r, cp); + } + + if (!supportsMultipleResponseTypes) { + break; + } + } } - postProcessResponseWithProperty(r, cp); - return r; + LOGGER.debug("Response for " + opId + " - " + responseCode + ": " + baseResponse); + + return baseResponse; } /** @@ -6831,7 +6997,7 @@ public void writePropertyBack(String propertyKey, Object value) { additionalProperties.put(propertyKey, value); } - protected String getContentType(RequestBody requestBody) { + protected String getFirstContentType(RequestBody requestBody) { if (requestBody == null || requestBody.getContent() == null || requestBody.getContent().isEmpty()) { LOGGER.debug("Cannot determine the content type. Returning null."); return null; @@ -6926,13 +7092,17 @@ public boolean hasFormParameter(Operation operation) { return false; } - public boolean hasBodyParameter(Operation operation) { + public boolean hasFirstBodyParameter(Operation operation) { RequestBody requestBody = ModelUtils.getReferencedRequestBody(openAPI, operation.getRequestBody()); if (requestBody == null) { return false; } - Schema schema = ModelUtils.getSchemaFromRequestBody(requestBody); + Schema schema = ModelUtils.getFirstSchemaFromRequestBody(requestBody); + if (schema == null) { + return false; + } + return ModelUtils.getReferencedSchema(openAPI, schema) != null; } @@ -7028,11 +7198,26 @@ public String getHelp() { return null; } - public List fromRequestBodyToFormParameters(RequestBody body, Set imports) { + public static boolean isForm(String contentType) { + if (contentType != null) { + contentType = contentType.toLowerCase(Locale.ROOT); + } + + return (contentType != null && + (contentType.startsWith("application/x-www-form-urlencoded") || + contentType.startsWith("multipart"))); + } + + protected List fromFirstRequestBodyToFormParameters(RequestBody requestBody, + Set imports) { + MediaType mediaType = ModelUtils.getFirstMediaTypeFromRequestBody(requestBody); + Schema schema = mediaType.getSchema(); + return fromSchemaToFormParameters(schema, mediaType, imports); + } + + public List fromSchemaToFormParameters(Schema schema, MediaType mediaType, Set imports) { List parameters = new ArrayList<>(); - LOGGER.debug("debugging fromRequestBodyToFormParameters= {}", body); - Schema schema = ModelUtils.getSchemaFromRequestBody(body); - schema = ModelUtils.getReferencedSchema(this.openAPI, schema); + LOGGER.debug("debugging fromSchemaToFormParameters= " + schema); Schema original = null; // check if it's allOf (only 1 sub schema) with or without default/nullable/etc set in the top level @@ -7085,6 +7270,7 @@ public List fromRequestBodyToFormParameters(RequestBody body, } parameters.add(codegenParameter); + postProcessParameter(codegenParameter); } } @@ -7300,6 +7486,7 @@ protected void addBodyModelSchema(CodegenParameter codegenParameter, String name codegenParameter.paramName = toParamName(codegenParameter.baseName); codegenParameter.baseType = codegenModel.classname; codegenParameter.dataType = getTypeDeclaration(codegenModel.classname); + LOGGER.debug("Setting body model to " + codegenParameter.dataType + " from type declaration with simple ref"); codegenParameter.description = codegenModel.description; codegenParameter.isNullable = codegenModel.isNullable; imports.add(codegenParameter.baseType); @@ -7316,6 +7503,7 @@ protected void addBodyModelSchema(CodegenParameter codegenParameter, String name codegenParameter.paramName = toParamName(codegenParameter.baseName); codegenParameter.baseType = codegenParameter.baseName; codegenParameter.dataType = getTypeDeclaration(codegenModelName); + LOGGER.debug("Setting body model to " + codegenParameter.dataType + " from type declaration with complex type"); codegenParameter.description = codegenProperty.getDescription(); codegenParameter.isNullable = codegenProperty.isNullable; } else { @@ -7347,6 +7535,7 @@ protected void addBodyModelSchema(CodegenParameter codegenParameter, String name codegenParameter.paramName = toParamName(codegenParameter.baseName); codegenParameter.baseType = codegenModelName; codegenParameter.dataType = getTypeDeclaration(codegenModelName); + LOGGER.debug("Setting body model to " + codegenParameter.dataType + " from type declaration with non-map type"); codegenParameter.description = codegenModelDescription; imports.add(codegenParameter.baseType); @@ -7665,7 +7854,7 @@ protected LinkedHashMap getContent(Content content, Se return cmtContent; } - public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { + public CodegenParameter fromRequestBody(RequestBody body, String opId, Set imports, String bodyParameterName) { if (body == null) { LOGGER.error("body in fromRequestBody cannot be null!"); throw new RuntimeException("body in fromRequestBody cannot be null!"); @@ -7675,144 +7864,197 @@ public CodegenParameter fromRequestBody(RequestBody body, Set imports, S codegenParameter.paramName = "UNKNOWN_PARAM_NAME"; codegenParameter.description = escapeText(body.getDescription()); codegenParameter.required = body.getRequired() != null ? body.getRequired() : Boolean.FALSE; - codegenParameter.isBodyParam = Boolean.TRUE; + codegenParameter.isBodyParam = true; + codegenParameter.setContent(getContent(body.getContent(), imports, "RequestBody")); + if (body.getExtensions() != null) { codegenParameter.vendorExtensions.putAll(body.getExtensions()); } String name = null; LOGGER.debug("Request body = {}", body); - Schema schema = ModelUtils.getSchemaFromRequestBody(body); - if (schema == null) { - LOGGER.error("Schema cannot be null in the request body: {}", body); - return null; - } - Schema original = null; - // check if it's allOf (only 1 sub schema) with or without default/nullable/etc set in the top level - if (ModelUtils.isAllOf(schema) && schema.getAllOf().size() == 1 && - ModelUtils.getType(schema) == null) { - if (schema.getAllOf().get(0) instanceof Schema) { - original = schema; - schema = (Schema) schema.getAllOf().get(0); - } else { - LOGGER.error("Unknown type in allOf schema. Please report the issue via openapi-generator's Github issue tracker."); - } - } - codegenParameter.setContent(getContent(body.getContent(), imports, "RequestBody")); - if (StringUtils.isNotBlank(schema.get$ref())) { - name = ModelUtils.getSimpleRef(schema.get$ref()); + Map schemas = ModelUtils.getSchemasFromRequestBody(body); + if (schemas == null || schemas.size() == 0) { + throw new RuntimeException("Request body cannot be null. Possible cause: missing schema in body parameter (OAS v2): " + body); } - Schema unaliasedSchema = unaliasSchema(schema); - schema = ModelUtils.getReferencedSchema(this.openAPI, schema); + CodegenParameter baseCodegenParameter = codegenParameter; - ModelUtils.syncValidationProperties(unaliasedSchema, codegenParameter); - codegenParameter.setTypeProperties(unaliasedSchema); - codegenParameter.setComposedSchemas(getComposedSchemas(unaliasedSchema)); - // TODO in the future switch al the below schema usages to unaliasedSchema - // because it keeps models as refs and will not get their referenced schemas - if (ModelUtils.isArraySchema(schema)) { - updateRequestBodyForArray(codegenParameter, schema, name, imports, bodyParameterName); - } else if (ModelUtils.isTypeObjectSchema(schema)) { - updateRequestBodyForObject(codegenParameter, schema, name, imports, bodyParameterName); - } else if (ModelUtils.isIntegerSchema(schema)) { // integer type - updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); - codegenParameter.isNumeric = Boolean.TRUE; - if (ModelUtils.isLongSchema(schema)) { // int64/long format - codegenParameter.isLong = Boolean.TRUE; - } else { - codegenParameter.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int - if (ModelUtils.isShortSchema(schema)) { // int32 - codegenParameter.setIsShort(Boolean.TRUE); - } - } - } else if (ModelUtils.isBooleanSchema(schema)) { // boolean type - updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); - } else if (ModelUtils.isFileSchema(schema) && !ModelUtils.isStringSchema(schema)) { - // swagger v2 only, type file - codegenParameter.isFile = true; - } else if (ModelUtils.isStringSchema(schema)) { - updateRequestBodyForString(codegenParameter, schema, imports, bodyParameterName); - } else if (ModelUtils.isNumberSchema(schema)) { - updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); - codegenParameter.isNumeric = Boolean.TRUE; - if (ModelUtils.isFloatSchema(schema)) { // float - codegenParameter.isFloat = Boolean.TRUE; - } else if (ModelUtils.isDoubleSchema(schema)) { // double - codegenParameter.isDouble = Boolean.TRUE; + if (schemas.size() > 1 && supportsMultipleRequestTypes) { + // OneOf of multiple types + List names = new ArrayList<>(); + + for (String mimeType : schemas.keySet()) { + // We'll generate this during post processing + names.add(toModelName(opId + "_" + mimeType + "_Request")); } - } else if (ModelUtils.isNullType(schema)) { - updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); - } else if (ModelUtils.isAnyType(schema)) { - if (ModelUtils.isMapSchema(schema)) { - // Schema with additionalproperties: true (including composed schemas with additionalproperties: true) - updateRequestBodyForMap(codegenParameter, schema, name, imports, bodyParameterName); - } else if (ModelUtils.isComposedSchema(schema)) { - this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, false); - } else if (ModelUtils.isObjectSchema(schema)) { - // object type schema OR (AnyType schema with properties defined) - this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, false); + + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = "body"; // default to body } else { - updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); + codegenParameter.baseName = bodyParameterName; } - addVarsRequiredVarsAdditionalProps(schema, codegenParameter); - } else { - // referenced schemas - updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); + codegenParameter.paramName = toParamName(codegenParameter.baseName); + String dataType = toVariantName(names); + LOGGER.debug("Using " + dataType + " for " + opId); + codegenParameter.dataType = dataType; + codegenParameter.schemaVariants = new ArrayList(schemas.size()); } - addJsonSchemaForBodyRequestInCaseItsNotPresent(codegenParameter, body); + for (Map.Entry entry : schemas.entrySet()) { - // set the parameter's example value - // should be overridden by lang codegen - setParameterExampleValue(codegenParameter, body); + if (schemas.size() > 1 && supportsMultipleRequestTypes) { + codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + codegenParameter.required = true; + codegenParameter.isBodyParam = true; + codegenParameter.description = escapeText(body.getDescription()); - // restore original schema with description, extensions etc - if (original != null) { - // evaluate common attributes such as description if defined in the top level - if (original.getNullable() != null) { - codegenParameter.isNullable = original.getNullable(); - } else if (original.getExtensions() != null && original.getExtensions().containsKey("x-nullable")) { - codegenParameter.isNullable = (Boolean) original.getExtensions().get("x-nullable"); + baseCodegenParameter.schemaVariants.add(codegenParameter); + codegenParameter.contentType = entry.getKey(); + codegenParameter.variantType = toModelName(opId + "_" + entry.getKey() + "_Request"); } - if (original.getExtensions() != null) { - codegenParameter.vendorExtensions.putAll(original.getExtensions()); - } - if (original.getDeprecated() != null) { - codegenParameter.isDeprecated = original.getDeprecated(); - } - if (original.getDescription() != null) { - codegenParameter.description = escapeText(original.getDescription()); - codegenParameter.unescapedDescription = original.getDescription(); - } - if (original.getMaxLength() != null) { - codegenParameter.setMaxLength(original.getMaxLength()); - } - if (original.getMinLength() != null) { - codegenParameter.setMinLength(original.getMinLength()); - } - if (original.getMaxItems() != null) { - codegenParameter.setMaxItems(original.getMaxItems()); - } - if (original.getMinItems() != null) { - codegenParameter.setMinItems(original.getMinItems()); + codegenParameter.contentType = entry.getKey(); + Schema schema = entry.getValue(); + + Schema original = null; + // check if it's allOf (only 1 sub schema) with or without default/nullable/etc set in the top level + if (ModelUtils.isAllOf(schema) && schema.getAllOf().size() == 1 && + ModelUtils.getType(schema) == null) { + if (schema.getAllOf().get(0) instanceof Schema) { + original = schema; + schema = (Schema) schema.getAllOf().get(0); + } else { + LOGGER.error("Unknown type in allOf schema. Please report the issue via openapi-generator's Github issue tracker."); + } } - if (original.getMaximum() != null) { - codegenParameter.setMaximum(String.valueOf(original.getMaximum().doubleValue())); + + if (StringUtils.isNotBlank(schema.get$ref())) { + name = ModelUtils.getSimpleRef(schema.get$ref()); } - if (original.getMinimum() != null) { - codegenParameter.setMinimum(String.valueOf(original.getMinimum().doubleValue())); + + Schema unaliasedSchema = unaliasSchema(schema); + schema = ModelUtils.getReferencedSchema(this.openAPI, schema); + + ModelUtils.syncValidationProperties(unaliasedSchema, codegenParameter); + codegenParameter.setTypeProperties(unaliasedSchema); + codegenParameter.setComposedSchemas(getComposedSchemas(unaliasedSchema)); + + if (isForm(entry.getKey())) { + addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true); + codegenParameter.formParams = fromSchemaToFormParameters(schema, body.getContent().get(entry.getKey()), imports); + LOGGER.info("Schema variant has dataType: " + codegenParameter.dataType); + } else { + // TODO in the future switch all the below schema usages to unaliasedSchema + // because it keeps models as refs and will not get their referenced schemas + if (ModelUtils.isArraySchema(schema)) { + updateRequestBodyForArray(codegenParameter, schema, name, imports, bodyParameterName); + } else if (ModelUtils.isTypeObjectSchema(schema)) { + updateRequestBodyForObject(codegenParameter, schema, name, imports, bodyParameterName); + } else if (ModelUtils.isIntegerSchema(schema)) { // integer type + updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); + codegenParameter.isNumeric = Boolean.TRUE; + if (ModelUtils.isLongSchema(schema)) { // int64/long format + codegenParameter.isLong = Boolean.TRUE; + } else { + codegenParameter.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int + if (ModelUtils.isShortSchema(schema)) { // int32 + codegenParameter.setIsShort(Boolean.TRUE); + } + } + } else if (ModelUtils.isBooleanSchema(schema)) { // boolean type + updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); + } else if (ModelUtils.isFileSchema(schema) && !ModelUtils.isStringSchema(schema)) { + // swagger v2 only, type file + codegenParameter.isFile = true; + } else if (ModelUtils.isStringSchema(schema)) { + updateRequestBodyForString(codegenParameter, schema, imports, bodyParameterName); + } else if (ModelUtils.isNumberSchema(schema)) { + updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); + codegenParameter.isNumeric = Boolean.TRUE; + if (ModelUtils.isFloatSchema(schema)) { // float + codegenParameter.isFloat = Boolean.TRUE; + } else if (ModelUtils.isDoubleSchema(schema)) { // double + codegenParameter.isDouble = Boolean.TRUE; + } + } else if (ModelUtils.isNullType(schema)) { + updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); + } else if (ModelUtils.isAnyType(schema)) { + if (ModelUtils.isMapSchema(schema)) { + // Schema with additionalproperties: true (including composed schemas with additionalproperties: true) + updateRequestBodyForMap(codegenParameter, schema, name, imports, bodyParameterName); + } else if (ModelUtils.isComposedSchema(schema)) { + this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, false); + } else if (ModelUtils.isObjectSchema(schema)) { + // object type schema OR (AnyType schema with properties defined) + this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, false); + } else { + updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); + } + addVarsRequiredVarsAdditionalProps(schema, codegenParameter); + } else { + // referenced schemas + updateRequestBodyForPrimitiveType(codegenParameter, schema, bodyParameterName, imports); + } + + // restore original schema with description, extensions etc + if (original != null) { + // evaluate common attributes such as description if defined in the top level + if (original.getNullable() != null) { + codegenParameter.isNullable = original.getNullable(); + } else if (original.getExtensions() != null && original.getExtensions().containsKey("x-nullable")) { + codegenParameter.isNullable = (Boolean) original.getExtensions().get("x-nullable"); + } + + if (original.getExtensions() != null) { + codegenParameter.vendorExtensions.putAll(original.getExtensions()); + } + if (original.getDeprecated() != null) { + codegenParameter.isDeprecated = original.getDeprecated(); + } + if (original.getDescription() != null) { + codegenParameter.description = escapeText(original.getDescription()); + codegenParameter.unescapedDescription = original.getDescription(); + } + if (original.getMaxLength() != null) { + codegenParameter.setMaxLength(original.getMaxLength()); + } + if (original.getMinLength() != null) { + codegenParameter.setMinLength(original.getMinLength()); + } + if (original.getMaxItems() != null) { + codegenParameter.setMaxItems(original.getMaxItems()); + } + if (original.getMinItems() != null) { + codegenParameter.setMinItems(original.getMinItems()); + } + if (original.getMaximum() != null) { + codegenParameter.setMaximum(String.valueOf(original.getMaximum().doubleValue())); + } + if (original.getMinimum() != null) { + codegenParameter.setMinimum(String.valueOf(original.getMinimum().doubleValue())); + } + /* comment out below as we don't store `title` in the codegen parametera the moment + if (original.getTitle() != null) { + codegenParameter.setTitle(original.getTitle()); + } + */ + } } - /* comment out below as we don't store `title` in the codegen parametera the moment - if (original.getTitle() != null) { - codegenParameter.setTitle(original.getTitle()); + + if (!supportsMultipleRequestTypes) { + break; } - */ } - return codegenParameter; + addJsonSchemaForBodyRequestInCaseItsNotPresent(baseCodegenParameter, body); + + // set the parameter's example value + // should be overridden by lang codegen + setParameterExampleValue(baseCodegenParameter, body); + + return baseCodegenParameter; } protected void addRequiredVarsMap(Schema schema, IJsonSchemaValidationProperties property) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index c5d220012155..826a04ccc83a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -561,7 +561,7 @@ void generateModels(List files, List allModels, List unu ModelMap modelTemplate = modelList.get(0); if (modelTemplate != null && modelTemplate.getModel() != null) { CodegenModel m = modelTemplate.getModel(); - if (m.isAlias) { + if (m.isAlias && !m.isVariant) { // alias to number, string, enum, etc, which should not be generated as model // but aliases are still used to dereference models in some languages (such as in html2). aliasModels.add(modelTemplate); // Store aliases in the separate list. diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java index 6a090df03d5a..a36ee11989de 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java @@ -563,7 +563,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation if (op.getHasExamples()) { // prepare examples for Apex test classes ApiResponse apiResponse = findMethodResponse(operation.getResponses()); - final Schema responseSchema = ModelUtils.getSchemaFromResponse(openAPI, apiResponse); + final Schema responseSchema = ModelUtils.getFirstSchemaFromResponse(openAPI, apiResponse); String deserializedExample = toExampleValue(responseSchema); for (Map example : op.examples) { example.put("example", escapeText(example.get("example"))); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java index 52e71fc22b79..69354e1687a4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java @@ -1874,7 +1874,7 @@ public void preprocessOpenAPI(OpenAPI openAPI) { } for (Operation operation : path.readOperations()) { LOGGER.info("Processing operation {}", operation.getOperationId()); - if (hasBodyParameter(operation) || hasFormParameter(operation)) { + if (hasFirstBodyParameter(operation) || hasFormParameter(operation)) { String defaultContentType = hasFormParameter(operation) ? "application/x-www-form-urlencoded" : "application/json"; List consumes = new ArrayList<>(getConsumesInfo(openAPI, operation)); String contentType = consumes.isEmpty() ? defaultContentType : consumes.get(0); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java index fe14ee6a86ca..3a7eb1306fbd 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java @@ -281,7 +281,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation ApiResponse apiResponse = findMethodResponse(operation.getResponses()); if (apiResponse != null) { - Schema response = ModelUtils.getSchemaFromResponse(openAPI, apiResponse); + Schema response = ModelUtils.getFirstSchemaFromResponse(openAPI, apiResponse); if (response != null) { CodegenProperty cm = fromProperty("response", response, false); op.vendorExtensions.put("x-codegen-response", cm); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java index a802ea26f878..2fa6ee0b39ce 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java @@ -302,7 +302,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation ApiResponse methodResponse = findMethodResponse(operation.getResponses()); if (methodResponse != null) { - Schema response = ModelUtils.getSchemaFromResponse(openAPI, methodResponse); + Schema response = ModelUtils.getFirstSchemaFromResponse(openAPI, methodResponse); response = unaliasSchema(response); if (response != null) { CodegenProperty cm = fromProperty("response", response, false); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java index 775afb9bd597..13d244addcd4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java @@ -377,8 +377,8 @@ public CodegenModel fromModel(String name, Schema model) { } @Override - public CodegenResponse fromResponse(String responseCode, ApiResponse resp) { - return new ExtendedCodegenResponse(super.fromResponse(responseCode, resp)); + public CodegenResponse fromResponse(String opId, String responseCode, ApiResponse resp) { + return new ExtendedCodegenResponse(super.fromResponse(opId, responseCode, resp)); } // We should use String.join if we can use Java8 diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonCommonCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonCommonCodegen.java index b2b3d1a6df13..2a4b8158e9c4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonCommonCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonCommonCodegen.java @@ -320,8 +320,8 @@ public CodegenParameter fromParameter(Parameter parameter, Set imports) } @Override - public CodegenResponse fromResponse(String responseCode, ApiResponse response) { - CodegenResponse result = super.fromResponse(responseCode, response); + public CodegenResponse fromResponse(String opId, String responseCode, ApiResponse response) { + CodegenResponse result = super.fromResponse(opId, responseCode, response); result.vendorExtensions.put(X_HAS_RESPONSE_PROPS, result.hasHeaders || result.dataType != null); List allResponseProps = new ArrayList<>(result.headers); List requiredResponseProps = new ArrayList<>(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonServerCodegen.java index 54cfe6574b0c..542f35d41e47 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaHelidonServerCodegen.java @@ -290,8 +290,8 @@ private void addApiTemplateFiles() { } @Override - public CodegenResponse fromResponse(String responseCode, ApiResponse response) { - var result = super.fromResponse(responseCode, response); + public CodegenResponse fromResponse(String opId, String responseCode, ApiResponse response) { + var result = super.fromResponse(opId, responseCode, response); result.vendorExtensions.put(X_RESULT_STATUS_DECL, statusDeclaration(result.code)); return result; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java index 88dbb526d750..30c83a15e699 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/K6ClientCodegen.java @@ -568,7 +568,7 @@ public void preprocessOpenAPI(OpenAPI openAPI) { } } - if (hasBodyParameter(operation) || hasFormParameter(operation)) { + if (hasFirstBodyParameter(operation) || hasFormParameter(operation)) { String defaultContentType = hasFormParameter(operation) ? "application/x-www-form-urlencoded" : "application/json"; List consumes = new ArrayList<>(getConsumesInfo(openAPI, operation)); String contentTypeValue = consumes.isEmpty() ? defaultContentType : consumes.get(0); @@ -586,7 +586,7 @@ public void preprocessOpenAPI(OpenAPI openAPI) { } for (Map.Entry responseEntry : operation.getResponses().entrySet()) { - CodegenResponse r = fromResponse(responseEntry.getKey(), responseEntry.getValue()); + CodegenResponse r = fromResponse(operationId, responseEntry.getKey(), responseEntry.getValue()); if (r.baseType != null && !defaultIncludes.contains(r.baseType) && !languageSpecificPrimitives.contains(r.baseType)) { @@ -596,7 +596,7 @@ public void preprocessOpenAPI(OpenAPI openAPI) { // if we have at least one request body example, we do not need to construct these dummies if (!hasRequestBodyExample) { - List formParameters = fromRequestBodyToFormParameters(requestBody, imports); + List formParameters = fromFirstRequestBodyToFormParameters(requestBody, imports); for (CodegenParameter parameter : formParameters) { String reference = ""; if (parameter.isModel) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinWiremockServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinWiremockServerCodegen.java index f876ef2cbd10..a51b09787b68 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinWiremockServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinWiremockServerCodegen.java @@ -128,8 +128,8 @@ public ModelsMap postProcessModels(ModelsMap objs) { } @Override - public CodegenResponse fromResponse(String responseCode, ApiResponse response) { - var r = super.fromResponse(responseCode, response); + public CodegenResponse fromResponse(String opId, String responseCode, ApiResponse response) { + var r = super.fromResponse(opId, responseCode, response); var isRange = List.of("1xx", "2xx", "3xx", "4xx", "5xx").contains(responseCode.toLowerCase(Locale.ROOT)); r.vendorExtensions.put(VENDOR_EXTENSION_IS_RANGE_RESPONSE_CODE, isRange); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java index d15f92edf7a8..0366729ba6bc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpDataTransferClientCodegen.java @@ -193,7 +193,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera } @Override - protected String getContentType(RequestBody requestBody) { + protected String getFirstContentType(RequestBody requestBody) { //Awfully nasty workaround to skip formParams generation return null; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustAxumServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustAxumServerCodegen.java index 6cef19c836f8..08e1ed1b9137 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustAxumServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustAxumServerCodegen.java @@ -689,9 +689,9 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera // Thus, we grab the inner schema beforehand, and then tinker afterward to // restore things to sensible values. @Override - public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { - Schema original_schema = ModelUtils.getSchemaFromRequestBody(body); - CodegenParameter codegenParameter = super.fromRequestBody(body, imports, bodyParameterName); + public CodegenParameter fromRequestBody(RequestBody body, String opId, Set imports, String bodyParameterName) { + Schema original_schema = ModelUtils.getFirstSchemaFromRequestBody(body); + CodegenParameter codegenParameter = super.fromRequestBody(body, opId, imports, bodyParameterName); if (StringUtils.isNotBlank(original_schema.get$ref())) { // Undo the mess `super.fromRequestBody` made - re-wrap the inner diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java index 21e69bc28f06..7cbb0c9c5054 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java @@ -98,6 +98,10 @@ public class RustServerCodegen extends AbstractRustCodegen implements CodegenCon public RustServerCodegen() { super(); + // Enable multiple request/response media types + supportsMultipleRequestTypes = true; + supportsMultipleResponseTypes = true; + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) @@ -448,7 +452,6 @@ private String tidyUpRuntimeCallbackParam(String param) { @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { - Map definitions = ModelUtils.getSchemas(this.openAPI); CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); String pathFormatString = op.path; @@ -595,39 +598,6 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation processParam(param, op); } - // We keep track of the 'default' model type for this API. If there are - // *any* XML responses, then we set the default to XML, otherwise we - // let the default be JSON. It would be odd for an API to want to use - // both XML and JSON on a single operation, and if we don't know - // anything then JSON is a more modern (ergo reasonable) choice. - boolean defaultsToXml = false; - - // Determine the types that this operation produces. `getProducesInfo` - // simply lists all the types, and then we add the correct imports to - // the generated library. - List produces = new ArrayList(getProducesInfo(openAPI, operation)); - boolean producesXml = false; - boolean producesPlainText = false; - if (produces != null && !produces.isEmpty()) { - List> c = new ArrayList>(); - for (String mimeType : produces) { - Map mediaType = new HashMap(); - - if (isMimetypeXml(mimeType)) { - additionalProperties.put("usesXml", true); - defaultsToXml = true; - producesXml = true; - } else if (isMimetypePlain(mimeType)) { - producesPlainText = true; - } - - mediaType.put("mediaType", mimeType); - c.add(mediaType); - } - op.produces = c; - op.hasProduces = true; - } - for (CodegenParameter param : op.headerParams) { processParam(param, op); @@ -684,99 +654,37 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation rsp.vendorExtensions.put("x-response-id", responseId); rsp.vendorExtensions.put("x-uppercase-response-id", underscoredResponseId.toUpperCase(Locale.ROOT)); rsp.vendorExtensions.put("x-uppercase-operation-id", underscoredOperationId.toUpperCase(Locale.ROOT)); - if (rsp.dataType != null) { - String uppercaseDataType = (rsp.dataType.replace("models::", "")).toUpperCase(Locale.ROOT); - rsp.vendorExtensions.put("x-uppercase-data-type", uppercaseDataType); - - // Get the mimetype which is produced by this response. Note - // that although in general responses produces a set of - // different mimetypes currently we only support 1 per - // response. - String firstProduces = null; - - if (original.getContent() != null) { - firstProduces = original.getContent().keySet().stream().findFirst().orElse(null); - } - // The output mime type. This allows us to do sensible fallback - // to JSON/XML rather than using only the default operation - // mimetype. - String outputMime; - - if (firstProduces == null) { - if (producesXml) { - outputMime = xmlMimeType; - } else if (producesPlainText) { - if (bytesType.equals(rsp.dataType)) { - outputMime = octetMimeType; - } else { - outputMime = plainTextMimeType; - } - } else { - outputMime = jsonMimeType; - } - } else { - // If we know exactly what mimetype this response is - // going to produce, then use that. If we have not found - // anything, then we'll fall back to the 'producesXXX' - // definitions we worked out above for the operation as a - // whole. - if (isMimetypeXml(firstProduces)) { - producesXml = true; - producesPlainText = false; - } else if (isMimetypePlain(firstProduces)) { - producesXml = false; - producesPlainText = true; - } else { - producesXml = false; - producesPlainText = false; - } + if (rsp.schemaVariants != null) { - outputMime = firstProduces; - } + boolean first = true; + int i = 0; + String oneOfName = "swagger::OneOf" + rsp.schemaVariants.size() + "::<"; - rsp.vendorExtensions.put("x-mime-type", outputMime); - - // Write out the type of data we actually expect this response - // to make. - if (producesXml) { - rsp.vendorExtensions.put("x-produces-xml", true); - } else if (producesPlainText) { - // Plain text means that there is not structured data in - // this response. So it'll either be a UTF-8 encoded string - // 'plainText' or some generic 'bytes'. - // - // Note that we don't yet distinguish between string/binary - // and string/bytes - that is we don't auto-detect whether - // base64 encoding should be done. They both look like - // 'producesBytes'. - if (bytesType.equals(rsp.dataType)) { - rsp.vendorExtensions.put("x-produces-bytes", true); + for (CodegenResponse variant : rsp.schemaVariants) { + if (first) { + first = false; } else { - rsp.vendorExtensions.put("x-produces-plain-text", true); - } - } else { - rsp.vendorExtensions.put("x-produces-json", true); - // If the data type is just "object", then ensure that the - // Rust data type is "serde_json::Value". This allows us - // to define APIs that can return arbitrary JSON bodies. - if ("object".equals(rsp.dataType)) { - rsp.dataType = "serde_json::Value"; + oneOfName += ", "; } + oneOfName += "models::" + variant.variantType; } - Schema response = (Schema) rsp.schema; - // Check whether we're returning an object with a defined XML namespace. - if (response != null && (!StringUtils.isEmpty(response.get$ref()))) { - Schema model = definitions.get(ModelUtils.getSimpleRef(response.get$ref())); - if ((model != null)) { - XML xml = model.getXml(); - if ((xml != null) && (xml.getNamespace() != null)) { - rsp.vendorExtensions.put("x-has-namespace", "true"); - } - } + for (CodegenResponse variant : rsp.schemaVariants) { + variant.vendorExtensions.put( + "x-variant-name", + oneOfName + ">::" + ((char) ('A' + i))); + + ++i; + + processInnerResponse(variant); + + LOGGER.info("Schema variant: " + variant); } + } else { + processInnerResponse(rsp); } + for (CodegenProperty header : rsp.headers) { if (uuidType.equals(header.dataType)) { additionalProperties.put("apiUsesUuid", true); @@ -801,6 +709,68 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation return op; } + private void processInnerResponse(CodegenResponse rsp) { + if (rsp.dataType != null) { + Map ve = rsp.vendorExtensions; + + String uppercaseDataType = (rsp.dataType.replace("models::", "")).toUpperCase(Locale.ROOT); + ve.put("x-uppercase-data-type", uppercaseDataType); + + String outputMime = rsp.contentType; + ve.put("x-mime-type", outputMime); + + // Write out the type of data we actually expect this response + // to make. + if (isMimetypeXml(outputMime)) { + ve.put("x-produces-basic", true); + ve.put("x-produces-xml", true); + } else if (isMimetypeMultipartRelated(outputMime)) { + additionalProperties.put("apiUsesMultipartRelated", true); + additionalProperties.put("apiUsesMultipart", true); + ve.put("x-produces-multipart-related", true); + } else if (isMimetypePlain(outputMime)) { + // Plain text means that there is not structured data in + // this response. So it'll either be a UTF-8 encoded string + // 'plainText' or some generic 'bytes'. + // + // Note that we don't yet distinguish between string/binary + // and string/bytes - that is we don't auto-detect whether + // base64 encoding should be done. They both look like + // 'producesBytes'. + ve.put("x-produces-basic", true); + if (rsp.dataType.equals(bytesType)) { + ve.put("x-produces-bytes", true); + } else { + ve.put("x-produces-plain-text", true); + } + } else { + ve.put("x-produces-basic", true); + ve.put("x-produces-json", true); + // If the data type is just "object", then ensure that the + // Rust data type is "serde_json::Value". This allows us + // to define APIs that can return arbitrary JSON bodies. + if (rsp.dataType.equals("object")) { + rsp.dataType = "serde_json::Value"; + } + } + + Schema response = (Schema) rsp.schema; + // Check whether we're returning an object with a defined XML namespace. + if (response != null && (!StringUtils.isEmpty(response.get$ref()))) { + Map definitions = ModelUtils.getSchemas(this.openAPI); + String ref = ModelUtils.getSimpleRef(response.get$ref()); + rsp.dataType = "models::" + toModelName(ref); + Schema model = definitions.get(ref); + if ((model != null)) { + XML xml = model.getXml(); + if ((xml != null) && (xml.getNamespace() != null)) { + ve.put("x-has-namespace", "true"); + } + } + } + } + } + @Override public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { OperationMap operations = objs.getOperations(); @@ -826,52 +796,105 @@ private void postProcessOperationWithModels(CodegenOperation op, List boolean consumesPlainText = false; boolean consumesXml = false; - if (op.consumes != null) { - for (Map consume : op.consumes) { - if (consume.get("mediaType") != null) { - String mediaType = consume.get("mediaType"); - - if (isMimetypeXml(mediaType)) { - additionalProperties.put("usesXml", true); - consumesXml = true; - } else if (isMimetypePlain(mediaType)) { - consumesPlainText = true; - } else if (isMimetypeWwwFormUrlEncoded(mediaType)) { - op.vendorExtensions.put("x-consumes-form", true); - additionalProperties.put("usesUrlEncodedForm", true); - } else if (isMimetypeMultipartFormData(mediaType)) { - op.vendorExtensions.put("x-consumes-multipart", true); - op.vendorExtensions.put("x-consumes-multipart-form", true); - additionalProperties.put("apiUsesMultipartFormData", true); - additionalProperties.put("apiUsesMultipart", true); - } else if (isMimetypeMultipartRelated(mediaType)) { - op.vendorExtensions.put("x-consumes-multipart", true); - op.vendorExtensions.put("x-consumes-multipart-related", true); - additionalProperties.put("apiUsesMultipartRelated", true); - additionalProperties.put("apiUsesMultipart", true); - } - } - } - } + String underscoredOperationId = underscore(op.operationId).toUpperCase(Locale.ROOT); if (op.bodyParams.size() > 0 || op.formParams.size() > 0){ op.vendorExtensions.put("x-has-request-body", true); } - String underscoredOperationId = underscore(op.operationId).toUpperCase(Locale.ROOT); + if (op.bodyParam != null && op.bodyParam.schemaVariants != null) { + op.vendorExtensions.put("x-has-schema-variants", true); - if (op.bodyParam != null) { - // Default to consuming json - op.bodyParam.vendorExtensions.put("x-uppercase-operation-id", underscoredOperationId); - if (consumesXml) { - op.vendorExtensions.put("x-consumes-basic", true); - op.bodyParam.vendorExtensions.put("x-consumes-xml", true); - } else if (consumesPlainText) { - op.vendorExtensions.put("x-consumes-basic", true); - op.bodyParam.vendorExtensions.put("x-consumes-plain-text", true); - } else { - op.vendorExtensions.put("x-consumes-basic", true); - op.bodyParam.vendorExtensions.put("x-consumes-json", true); + String oneOfName = "swagger::OneOf" + op.bodyParam.schemaVariants.size() + "::<"; + boolean first = true; + + for (CodegenParameter param : op.bodyParam.schemaVariants) { + if (first) { + first = false; + } else { + oneOfName += ", "; + } + oneOfName += "models::" + param.variantType; + } + + oneOfName += ">"; + int i = 0; + + for (CodegenParameter param : op.bodyParam.schemaVariants) { + + String mediaType = param.contentType; + Map ve = param.vendorExtensions; + ve.put("x-has-schema-variants", false); + ve.put("x-variant-name", oneOfName + "::" + ((char) ('A' + i))); + ++i; + param.variantType = "models::" + param.variantType; + + if (isMimetypeXml(mediaType)) { + additionalProperties.put("usesXml", true); + ve.put("x-consumes-basic", true); + ve.put("x-consumes-xml", true); + } else if (isMimetypeJson(mediaType)) { + ve.put("x-consumes-basic", true); + ve.put("x-consumes-json", true); + } else if (isMimetypePlain(mediaType)) { + ve.put("x-consumes-basic", true); + ve.put("x-consumes-plain-text", true); + } else if (isMimetypeWwwFormUrlEncoded(mediaType)) { + additionalProperties.put("usesUrlEncodedForm", true); + ve.put("x-consumes-form", true); + } else if (isMimetypeMultipartFormData(mediaType)) { + additionalProperties.put("apiUsesMultipartFormData", true); + additionalProperties.put("apiUsesMultipart", true); + ve.put("x-consumes-multipart-form", true); + } else if (isMimetypeMultipartRelated(mediaType)) { + additionalProperties.put("apiUsesMultipartRelated", true); + additionalProperties.put("apiUsesMultipart", true); + ve.put("x-consumes-multipart-related", true); + } + } + } else { + if (op.consumes != null) { + for (Map consume : op.consumes) { + if (consume.get("mediaType") != null) { + String mediaType = consume.get("mediaType"); + + if (isMimetypeXml(mediaType)) { + additionalProperties.put("usesXml", true); + consumesXml = true; + op.vendorExtensions.put("x-consumes-basic", true); + } else if (isMimetypePlain(mediaType)) { + consumesPlainText = true; + op.vendorExtensions.put("x-consumes-basic", true); + } else if (isMimetypeWwwFormUrlEncoded(mediaType)) { + additionalProperties.put("usesUrlEncodedForm", true); + op.vendorExtensions.put("x-consumes-form", true); + } else if (isMimetypeMultipartFormData(mediaType)) { + op.vendorExtensions.put("x-consumes-multipart", true); + op.vendorExtensions.put("x-consumes-multipart-form", true); + additionalProperties.put("apiUsesMultipartFormData", true); + additionalProperties.put("apiUsesMultipart", true); + } else if (isMimetypeMultipartRelated(mediaType)) { + op.vendorExtensions.put("x-consumes-multipart", true); + op.vendorExtensions.put("x-consumes-multipart-related", true); + additionalProperties.put("apiUsesMultipartRelated", true); + additionalProperties.put("apiUsesMultipart", true); + } else { + op.vendorExtensions.put("x-consumes-basic", true); + } + } + } + } + + if (op.bodyParam != null) { + // Default to consuming json + op.bodyParam.vendorExtensions.put("x-uppercase-operation-id", underscoredOperationId); + if (consumesXml) { + op.bodyParam.vendorExtensions.put("x-consumes-xml", true); + } else if (consumesPlainText) { + op.bodyParam.vendorExtensions.put("x-consumes-plain-text", true); + } else { + op.bodyParam.vendorExtensions.put("x-consumes-json", true); + } } } @@ -882,13 +905,10 @@ private void postProcessOperationWithModels(CodegenOperation op, List // Default to producing json if nothing else is specified if (consumesXml) { - op.vendorExtensions.put("x-consumes-basic", true); param.vendorExtensions.put("x-consumes-xml", true); } else if (consumesPlainText) { - op.vendorExtensions.put("x-consumes-basic", true); param.vendorExtensions.put("x-consumes-plain-text", true); } else { - op.vendorExtensions.put("x-consumes-basic", true); param.vendorExtensions.put("x-consumes-json", true); } } @@ -916,6 +936,12 @@ private void postProcessOperationWithModels(CodegenOperation op, List header.nameInLowerCase = header.baseName.toLowerCase(Locale.ROOT); } + for (CodegenResponse rsp : op.responses) { + for (CodegenParameter param : rsp.formParams) { + processParam(param, op); + } + } + if (op.authMethods != null) { boolean headerAuthMethods = false; @@ -982,31 +1008,43 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera // Thus, we grab the inner schema beforehand, and then tinker afterwards to // restore things to sensible values. @Override - public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { - Schema original_schema = ModelUtils.getSchemaFromRequestBody(body); - CodegenParameter codegenParameter = super.fromRequestBody(body, imports, bodyParameterName); - - if (StringUtils.isNotBlank(original_schema.get$ref())) { - // Undo the mess `super.fromRequestBody` made - re-wrap the inner - // type. - codegenParameter.dataType = getTypeDeclaration(original_schema); - codegenParameter.isPrimitiveType = false; - codegenParameter.isArray = false; - codegenParameter.isString = false; - codegenParameter.isByteArray = ModelUtils.isByteArraySchema(original_schema); - - - // This is a model, so should only have an example if explicitly - // defined. - if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { - codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example")); - } else if (!codegenParameter.required) { - //mandatory parameter use the example in the yaml. if no example, it is also null. - codegenParameter.example = null; + public CodegenParameter fromRequestBody(RequestBody body, String opId, Set imports, String bodyParameterName) { + Map originalSchemas = ModelUtils.getSchemasFromRequestBody(body); + CodegenParameter baseCodegenParameter = super.fromRequestBody(body, opId, imports, bodyParameterName); + + int i = 0; + + for (Schema originalSchema : originalSchemas.values()) { + CodegenParameter codegenParameter; + + if (originalSchemas.size() == 1) { + codegenParameter = baseCodegenParameter; + } else { + codegenParameter = baseCodegenParameter.schemaVariants.get(i); + ++i; + } + + if (StringUtils.isNotBlank(originalSchema.get$ref())) { + // Undo the mess `super.fromRequestBody` made - re-wrap the inner + // type. + codegenParameter.dataType = getTypeDeclaration(originalSchema); + codegenParameter.isPrimitiveType = false; + codegenParameter.isArray = false; + codegenParameter.isString = false; + codegenParameter.isByteArray = ModelUtils.isByteArraySchema(originalSchema); + + // This is a model, so should only have an example if explicitly + // defined. + if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { + codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example")); + } else if (!codegenParameter.required) { + //mandatory parameter use the example in the yaml. if no example, it is also null. + codegenParameter.example = null; + } } } - return codegenParameter; + return baseCodegenParameter; } @Override @@ -1341,6 +1379,11 @@ else if (ModelUtils.isBooleanSchema(p)) { return defaultValue; } + @Override + public String toVariantName(List names) { + return "swagger::OneOf" + names.size() + ""; + } + @Override public String toOneOfName(List names, Schema composedSchema) { Map exts = null; @@ -1457,6 +1500,19 @@ public ModelsMap postProcessModels(ModelsMap objs) { } private void processParam(CodegenParameter param, CodegenOperation op) { + // recurse into schemaVariants + if (param.schemaVariants != null && param.schemaVariants.size() != 0) { + for (CodegenParameter p : param.schemaVariants) { + processParam(p, op); + } + } + + if (param.formParams != null) { + for (CodegenParameter p : param.formParams) { + processParam(p, op); + } + } + String example = null; // If a parameter uses UUIDs, we need to import the UUID package. diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java index cb3c52a99c75..666f9eb5e112 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java @@ -1034,7 +1034,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation $ref: */ Map> schemaTypes = operation.getResponses().entrySet().stream() - .map(e -> Pair.of(e.getValue(), fromResponse(e.getKey(), e.getValue()))) + .map(e -> Pair.of(e.getValue(), fromResponse(operation.getOperationId(), e.getKey(), e.getValue()))) .filter(p -> p.getRight().is2xx) // consider only success .map(p -> p.getLeft().getContent().get(MEDIA_EVENT_STREAM)) .map(MediaType::getSchema) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index ae6cbce2f0c7..a77014d3bcc7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -20,6 +20,7 @@ import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.Mustache; import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.media.MediaType; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.parameters.RequestBody; @@ -519,8 +520,8 @@ private void addNpmPackageGeneration() { } @Override - public List fromRequestBodyToFormParameters(RequestBody body, Set imports) { - List superParams = super.fromRequestBodyToFormParameters(body, imports); + public List fromSchemaToFormParameters(Schema schema, MediaType mediaType, Set imports) { + List superParams = super.fromSchemaToFormParameters(schema, mediaType, imports); List extendedParams = new ArrayList(); for (CodegenParameter cp : superParams) { extendedParams.add(new ExtendedCodegenParameter(cp)); @@ -541,8 +542,8 @@ public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set } @Override - public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { - CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName); + public CodegenParameter fromRequestBody(RequestBody body, String opId, Set imports, String bodyParameterName) { + CodegenParameter cp = super.fromRequestBody(body, opId, imports, bodyParameterName); return new ExtendedCodegenParameter(cp); } @@ -614,7 +615,7 @@ public ExtendedCodegenOperation fromOperation(String path, String httpMethod, Op } if (!op.hasReturnPassthroughVoid) { - Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, methodResponse)); + Schema responseSchema = unaliasSchema(ModelUtils.getFirstSchemaFromResponse(openAPI, methodResponse)); ExtendedCodegenProperty cp = null; if (op.returnPassthrough instanceof String && cm != null) { cp = (ExtendedCodegenProperty) this.processCodeGenModel(cm).vars.get(1); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZapierClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZapierClientCodegen.java index 4740460f676e..9209c7ca7dc5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZapierClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ZapierClientCodegen.java @@ -192,8 +192,8 @@ public String escapeQuotationMark(String input) { } @Override - public CodegenResponse fromResponse(String responseCode, ApiResponse response) { - CodegenResponse r = super.fromResponse(responseCode, response); + public CodegenResponse fromResponse(String operationId, String responseCode, ApiResponse response) { + CodegenResponse r = super.fromResponse(operationId, responseCode, response); try { Map>> map = Json.mapper().readerFor(Map.class).readValue(Json.pretty(response.getContent())); Map.Entry>> entry = map.entrySet().stream().findFirst().orElseThrow(() -> new IllegalStateException("no response object available")); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java index b8bf2bcd669a..0562ba28235e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java @@ -1175,8 +1175,28 @@ public static Callback getCallback(OpenAPI openAPI, String name) { * @param requestBody request body of the operation * @return first schema */ - public static Schema getSchemaFromRequestBody(RequestBody requestBody) { - return getSchemaFromContent(requestBody.getContent()); + public static Schema getFirstSchemaFromRequestBody(RequestBody requestBody) { + return getFirstSchemaFromContent(requestBody.getContent()); + } + + /** + * Return the schemas for a RequestBody + * + * @param requestBody request body of the operation + * @return schemas + */ + public static Map getSchemasFromRequestBody(RequestBody requestBody) { + return getSchemasFromContent(requestBody.getContent()); + } + + /** + * Return the Media Type for a RequestBody + * + * @param requestBody request body of the operation + * @return schemas + */ + public static MediaType getFirstMediaTypeFromRequestBody(RequestBody requestBody) { + return getFirstMediaTypeFromContent(requestBody.getContent()); } /** @@ -1186,12 +1206,27 @@ public static Schema getSchemaFromRequestBody(RequestBody requestBody) { * @param response API response of the operation * @return firstSchema */ - public static Schema getSchemaFromResponse(OpenAPI openAPI, ApiResponse response) { + public static Schema getFirstSchemaFromResponse(OpenAPI openAPI, ApiResponse response) { + ApiResponse result = getReferencedApiResponse(openAPI, response); + if (result == null) { + return null; + } else { + return getFirstSchemaFromContent(result.getContent()); + } + } + + /** + * Return the Schemas for a ApiResponse + * + * @param response api response of the operation + * @return schemas + */ + public static Map getSchemasFromResponse(OpenAPI openAPI, ApiResponse response) { ApiResponse result = getReferencedApiResponse(openAPI, response); if (result == null) { return null; } else { - return getSchemaFromContent(result.getContent()); + return getSchemasFromContent(result.getContent()); } } @@ -1213,18 +1248,63 @@ public static Schema getSchemaFromResponse(OpenAPI openAPI, ApiResponse response * @param content a 'content' section in the OAS specification. * @return the Schema. */ - private static Schema getSchemaFromContent(Content content) { + private static Schema getFirstSchemaFromContent(Content content) { + MediaType mediaType = getFirstMediaTypeFromContent(content); + + if (mediaType == null) { + return null; + } else { + return mediaType.getSchema(); + } + } + + /** + * Return the first MediaType from a specified OAS 'content' section. + *

+ * For example, given the following OAS, this method returns the 'application/json' + * media type because it is listed first in the OAS. + *

+ * responses: + * '200': + * content: + * application/json: + * schema: + * $ref: '#/components/schemas/XYZ' + * application/xml: + * ... + * + * @param content a 'content' section in the OAS specification. + * @return the Schema. + */ + private static MediaType getFirstMediaTypeFromContent(Content content) { if (content == null || content.isEmpty()) { return null; } + Map.Entry entry = content.entrySet().iterator().next(); + if (content.size() > 1) { // Other content types are currently ignored by codegen. If you see this warning, // reorder the OAS spec to put the desired content type first. once(LOGGER).debug("Multiple schemas found in the OAS 'content' section, returning only the first one ({})", entry.getKey()); } - return entry.getValue().getSchema(); + + return entry.getValue(); + } + + private static Map getSchemasFromContent(Content content) { + if (content == null || content.isEmpty()) { + return null; + } + + Map schemas = new HashMap(content.values().size()); + + for (Map.Entry entry : content.entrySet()) { + schemas.put(entry.getKey(), entry.getValue().getSchema()); + } + + return schemas; } /** diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-imports.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-imports.mustache index d2a4b3fcc252..baf5004af8c5 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-imports.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-imports.mustache @@ -26,7 +26,8 @@ use multipart::client::lazy::Multipart; {{/apiUsesMultipartFormData}} {{#apiUsesMultipartRelated}} use hyper_0_10::header::{Headers, ContentType}; -use mime_multipart::{Node, Part, write_multipart}; +use log::warn; +use mime_multipart::{read_multipart_body, Node, Part, write_multipart}; {{/apiUsesMultipartRelated}} use crate::models; diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache index fec80b345b8e..86e57ed28e50 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache @@ -85,7 +85,8 @@ Ok(req) => req, Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; -{{>client-request-body-instance}} + +{{>client-request-body}} let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -180,8 +181,9 @@ match response.status().as_u16() { {{#responses}} {{{code}}} => { + let (header, body) = response.into_parts(); {{#headers}} - let response_{{{name}}} = match response.headers().get(HeaderName::from_static("{{{nameInLowerCase}}}")) { + let response_{{{name}}} = match header.headers.get(HeaderName::from_static("{{{nameInLowerCase}}}")) { Some(response_{{{name}}}) => { let response_{{{name}}} = response_{{{name}}}.clone(); let response_{{{name}}} = match TryInto::>::try_into(response_{{{name}}}) { @@ -207,12 +209,11 @@ {{/headers}} {{#dataType}} - let body = response.into_body(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; -{{>client-response-body-instance}} +{{>client-response-body}} Ok({{{operationId}}}Response::{{#vendorExtensions}}{{x-response-id}}{{/vendorExtensions}} {{^headers}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-request-body-instance.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-request-body-instance.mustache index d9f734cdf8a6..55132d900f71 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-request-body-instance.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-request-body-instance.mustache @@ -50,9 +50,6 @@ // Consumes basic body {{#bodyParam}} // Body parameter - {{^required}} - if let Some(param_{{{paramName}}}) = param_{{{paramName}}} { - {{/required}} {{#vendorExtensions}} {{#x-consumes-plain-text}} {{#isByteArray}} @@ -70,9 +67,6 @@ {{/x-consumes-json}} {{/vendorExtensions}} *request.body_mut() = Body::from(body); - {{^required}} - } - {{/required}} let header = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}{{^consumes}}application/json{{/consumes}}"; request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-request-body.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-request-body.mustache new file mode 100644 index 000000000000..02e83e9b3bbf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-server/client-request-body.mustache @@ -0,0 +1,40 @@ +{{#vendorExtensions.x-has-schema-variants}} + {{^bodyParam.required}} + if let Some(param_{{{bodyParam.paramName}}}) = param_{{{bodyParam.paramName}}} { + {{/bodyParam.required}} + match param_{{bodyParam.paramName}} { + {{#bodyParam.schemaVariants}} + {{{vendorExtensions.x-variant-name}}}(body) => { + let body : {{{dataType}}} = body.into(); + {{#vendorExtensions.x-consumes-basic}} + let param_{{{bodyParam.paramName}}} = body; + {{/vendorExtensions.x-consumes-basic}} + {{^vendorExtensions.x-consumes-basic}} + {{#formParams}} + let param_{{{paramName}}} = body.{{{paramName}}}; + {{/formParams}} + {{/vendorExtensions.x-consumes-basic}} +{{>client-request-body-instance}} + }, + {{/bodyParam.schemaVariants}} + } + {{^bodyParam.required}} + } + {{/bodyParam.required}} +{{/vendorExtensions.x-has-schema-variants}} +{{^vendorExtensions.x-has-schema-variants}} + // No schema variants + {{#vendorExtensions.x-consumes-basic}} + // Basic schema + {{^bodyParam.required}} + // Optional Basic Schema + if let Some(param_{{{bodyParam.paramName}}}) = param_{{{bodyParam.paramName}}} { + {{/bodyParam.required}} + {{/vendorExtensions.x-consumes-basic}} +{{>client-request-body-instance}} + {{#vendorExtensions.x-consumes-basic}} + {{^bodyParam.required}} + } + {{/bodyParam.required}} + {{/vendorExtensions.x-consumes-basic}} +{{/vendorExtensions.x-has-schema-variants}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-response-body-instance.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-response-body-instance.mustache index 3ff6dfb0c7a9..c3b13b2ebe90 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-response-body-instance.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-response-body-instance.mustache @@ -1,3 +1,4 @@ + // {{contentType}} {{#vendorExtensions}} {{#x-produces-bytes}} let body = swagger::ByteArray(body.to_vec()); diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-response-body.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-response-body.mustache new file mode 100644 index 000000000000..44cef05b1bb4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-server/client-response-body.mustache @@ -0,0 +1,30 @@ +{{#schemaVariants}} + {{#-first}} + // Body has multiple variant schemas + let content_type = if let Some(content_type) = header.headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Err(ApiError(String::from("Missing content type header"))); + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + let body = match content_type { + {{/-first}} + Ok("{{contentType}}") => { +{{>client-response-body-instance}} + let body : models::{{{variantType}}} = models::{{{variantType}}}::from(body); + + {{{vendorExtensions.x-variant-name}}}(body) + }, + {{#-last}} + e => { + return Err(ApiError(format!("Unexpected content type: {:?}", e))); + } + }; + {{/-last}} +{{/schemaVariants}} +{{^schemaVariants}} +{{>client-response-body-instance}} +{{/schemaVariants}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/models.mustache b/modules/openapi-generator/src/main/resources/rust-server/models.mustache index ab1814b7c6b6..8845e3ff4a3e 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -59,7 +59,7 @@ impl std::str::FromStr for {{{classname}}} { {{/isEnum}} {{^isEnum}} {{#dataType}} -#[derive(Debug, Clone, PartialEq, {{#vendorExtensions.x-partial-ord}}PartialOrd, {{/vendorExtensions.x-partial-ord}}serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, {{#vendorExtensions.x-partial-ord}}{{#^isVariant}}PartialOrd, {{/^isVariant}}{{/vendorExtensions.x-partial-ord}}serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] {{#xmlName}} #[serde(rename = "{{{.}}}")] diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-imports.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-imports.mustache index 1b39e6808be0..56d0741970e5 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-imports.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-imports.mustache @@ -14,8 +14,7 @@ use swagger::auth::Scopes; use url::form_urlencoded; {{#apiUsesMultipartRelated}} use hyper_0_10::header::{Headers, ContentType}; -use mime_0_2::{TopLevel, SubLevel, Mime as Mime2}; -use mime_multipart::{read_multipart_body, Node, Part}; +use mime_multipart::{read_multipart_body, Node, Part, write_multipart}; {{/apiUsesMultipartRelated}} {{#apiUsesMultipartFormData}} use multipart::server::Multipart; diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache index 4957b65c4dc5..efcdfcbbfa2c 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache @@ -201,12 +201,12 @@ Ok(body) => { {{^vendorExtensions.x-consumes-multipart-form}} {{^vendorExtensions.x-consumes-form}} - {{^bodyParam.vendorExtensions.x-consumes-plain-text}} + {{^vendorExtensions.x-consumes-plain-text}} let mut unused_elements : Vec = vec![]; - {{/bodyParam.vendorExtensions.x-consumes-plain-text}} + {{/vendorExtensions.x-consumes-plain-text}} {{/vendorExtensions.x-consumes-form}} {{/vendorExtensions.x-consumes-multipart-form}} -{{>server-request-body-instance}} +{{>server-request-body}} {{/vendorExtensions.x-has-request-body}} let result = api_impl.{{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}( {{#vendorExtensions}} @@ -228,14 +228,14 @@ {{#vendorExtensions.x-has-request-body}} {{^vendorExtensions.x-consumes-multipart-form}} {{^vendorExtensions.x-consumes-form}} - {{^bodyParam.vendorExtensions.x-consumes-plain-text}} + {{^vendorExtensions.x-consumes-plain-text}} if !unused_elements.is_empty() { response.headers_mut().insert( HeaderName::from_static("warning"), HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) .expect("Unable to create Warning header value")); } - {{/bodyParam.vendorExtensions.x-consumes-plain-text}} + {{/vendorExtensions.x-consumes-plain-text}} {{/vendorExtensions.x-consumes-form}} {{/vendorExtensions.x-consumes-multipart-form}} {{/vendorExtensions.x-has-request-body}} @@ -294,7 +294,7 @@ } {{/required}} {{/headers}} -{{>server-response-body-instance}} +{{>server-response-body}} }, {{/responses}} }, diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-request-body.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-request-body.mustache new file mode 100644 index 000000000000..ec765477fcab --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-server/server-request-body.mustache @@ -0,0 +1,103 @@ +{{#vendorExtensions.x-has-schema-variants}} + // Body has multiple variant schemas + let param_{{{bodyParam.paramName}}} : + {{^bodyParam.required}} + Option< + {{/bodyParam.required}} + {{{bodyParam.dataType}}} + {{^bodyParam.required}} + > + {{/bodyParam.required}} + = if body.is_empty() { + + {{#bodyParam.required}} + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Missing body"))) + .expect("Unable to create Bad Request for missing body")) + {{/bodyParam.required}} + {{^bodyParam.required}} + None + {{/bodyParam.required}} + + } else { + let content_type = headers.get(CONTENT_TYPE); + + let content_type = if let Some(content_type) = headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Missing Content-Type header"))) + .expect("Unable to create Bad Request for missing content type")) + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + +{{^bodyParam.required}} + Some( +{{/bodyParam.required}} + match content_type { + {{#bodyParam.schemaVariants}} + Ok("{{contentType}}") => { + {{#vendorExtensions.x-consumes-basic}} + {{>server-request-body-basic}} + {{/vendorExtensions.x-consumes-basic}} + {{#vendorExtensions.x-consumes-multipart-form}} + {{>server-request-body-multipart-form}} + {{/vendorExtensions.x-consumes-multipart-form}} + {{#vendorExtensions.x-consumes-form}} + {{>server-request-body-form}} + {{/vendorExtensions.x-consumes-form}} + {{#vendorExtensions.x-consumes-multipart-related}} + {{>server-request-body-multipart-related}} + {{/vendorExtensions.x-consumes-multipart-related}} + + {{^vendorExtensions.x-consumes-basic}} + let param_{{{paramName}}} : {{{dataType}}} = {{{dataType}}} { + {{#formParams}} + {{{paramName}}}: param_{{{paramName}}}, + {{/formParams}} + }; + {{/vendorExtensions.x-consumes-basic}} + + let param_{{{paramName}}} : {{{variantType}}} = {{{variantType}}}::from(param_{{{paramName}}}); + + {{{vendorExtensions.x-variant-name}}}(param_{{{paramName}}}) + }, + {{/bodyParam.schemaVariants}} + _ => { + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Incorrect content type"))) + .expect("Unable to create Bad Request for incorrect content type")) + } + } +{{^bodyParam.required}} + ) +{{/bodyParam.required}} + }; +{{/vendorExtensions.x-has-schema-variants}} +{{^vendorExtensions.x-has-schema-variants}} +{{#vendorExtensions}} + {{#x-consumes-multipart}} + {{#x-consumes-multipart-related}} +{{>server-request-body-multipart-related}} + {{/x-consumes-multipart-related}} + {{^x-consumes-multipart-related}} + {{^bodyParams}} +{{>server-request-body-multipart-form}} + {{/bodyParams}} + {{/x-consumes-multipart-related}} + {{/x-consumes-multipart}} + {{^x-consumes-multipart}} + {{#bodyParams}} +{{>server-request-body-basic}} + {{/bodyParams}} + {{^bodyParams}} +{{>server-request-body-form}} + {{/bodyParams}} + {{/x-consumes-multipart}} +{{/vendorExtensions}} +{{/vendorExtensions.x-has-schema-variants}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-response-body-instance.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-response-body-instance.mustache index 9bb648c525f7..142f2aca1ad8 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-response-body-instance.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-response-body-instance.mustache @@ -1,10 +1,11 @@ {{#dataType}} + // {{contentType}} {{#vendorExtensions}} {{^x-produces-multipart-related}} response.headers_mut().insert( CONTENT_TYPE, - HeaderValue::from_str("{{{x-mime-type}}}") - .expect("Unable to create Content-Type header for {{{x-mime-type}}}")); + HeaderValue::from_str("{{{contentType}}}") + .expect("Unable to create Content-Type header for {{{contentType}}}")); {{/x-produces-multipart-related}} {{#x-produces-xml}} // XML Body diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-response-body.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-response-body.mustache new file mode 100644 index 000000000000..84d247d72110 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-server/server-response-body.mustache @@ -0,0 +1,16 @@ +{{#schemaVariants}} + {{#-first}} + let body = match body { + {{/-first}} + {{{vendorExtensions.x-variant-name}}}(body) => { + let body : {{{dataType}}} = body.into(); + +{{>server-response-body-instance}} + }, + {{#-last}} + }; + {{/-last}} +{{/schemaVariants}} +{{^schemaVariants}} +{{>server-response-body-instance}} +{{/schemaVariants}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index 1c0631f98cca..bd824b51516d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -116,15 +116,15 @@ public void testHasBodyParameter() { final DefaultCodegen codegen = new DefaultCodegen(); codegen.setOpenAPI(openAPI); - Assertions.assertFalse(codegen.hasBodyParameter(pingOperation)); - Assertions.assertTrue(codegen.hasBodyParameter(createOperation)); + Assertions.assertFalse(codegen.hasFirstBodyParameter(pingOperation)); + Assertions.assertTrue(codegen.hasFirstBodyParameter(createOperation)); } @Test(expectedExceptions = RuntimeException.class) public void testParameterEmptyDescription() { DefaultCodegen codegen = new DefaultCodegen(); - codegen.fromRequestBody(null, new HashSet<>(), null); + codegen.fromRequestBody(null, "opId", new HashSet<>(), null); } @Test @@ -259,7 +259,7 @@ public void testFormParameterHasDefaultValue() { codegen.setOpenAPI(openAPI); Schema requestBodySchema = ModelUtils.getReferencedSchema(openAPI, - ModelUtils.getSchemaFromRequestBody(openAPI.getPaths().get("/fake").getGet().getRequestBody())); + ModelUtils.getFirstSchemaFromRequestBody(openAPI.getPaths().get("/fake").getGet().getRequestBody())); CodegenParameter codegenParameter = codegen.fromFormProperty("enum_form_string", (Schema) requestBodySchema.getProperties().get("enum_form_string"), new HashSet()); Assertions.assertEquals(codegenParameter.defaultValue, "-efg"); @@ -272,7 +272,7 @@ public void testDateTimeFormParameterHasDefaultValue() { final DefaultCodegen codegen = new DefaultCodegen(); codegen.setOpenAPI(openAPI); - Schema requestBodySchema = ModelUtils.getSchemaFromRequestBody(openAPI.getPaths().get("/thingy/{date}").getPost().getRequestBody()); + Schema requestBodySchema = ModelUtils.getFirstSchemaFromRequestBody(openAPI.getPaths().get("/thingy/{date}").getPost().getRequestBody()); // dereference requestBodySchema = ModelUtils.getReferencedSchema(openAPI, requestBodySchema); CodegenParameter codegenParameter = codegen.fromFormProperty("visitDate", (Schema) requestBodySchema.getProperties().get("visitDate"), @@ -648,7 +648,7 @@ public void testGetSchemaTypeWithComposedSchemaWithOneOf() { Operation operation = openAPI.getPaths().get("/state").getPost(); Schema schema = ModelUtils.getReferencedSchema(openAPI, - ModelUtils.getSchemaFromRequestBody(operation.getRequestBody())); + ModelUtils.getFirstSchemaFromRequestBody(operation.getRequestBody())); String type = codegen.getSchemaType(schema); Assertions.assertNotNull(type); @@ -1871,7 +1871,7 @@ public void testResponseWithNoSchemaInHeaders() { final DefaultCodegen codegen = new DefaultCodegen(); codegen.setOpenAPI(openAPI); - CodegenResponse cr = codegen.fromResponse("2XX", response2XX); + CodegenResponse cr = codegen.fromResponse("op1", "2XX", response2XX); Assertions.assertNotNull(cr); Assertions.assertTrue(cr.hasHeaders); } @@ -2231,7 +2231,7 @@ public void mapParamImportInnerObject() { RequestBody requestBody = openAPI.getPaths().get("/api/instruments").getPost().getRequestBody(); HashSet imports = new HashSet<>(); - codegen.fromRequestBody(requestBody, imports, ""); + codegen.fromRequestBody(requestBody, "opId", imports, ""); HashSet expected = Sets.newHashSet("InstrumentDefinition", "map"); @@ -2319,7 +2319,7 @@ public void arrayInnerReferencedSchemaMarkedAsModel_20() { RequestBody body = openAPI.getPaths().get("/examples").getPost().getRequestBody(); - CodegenParameter codegenParameter = codegen.fromRequestBody(body, imports, ""); + CodegenParameter codegenParameter = codegen.fromRequestBody(body, "opId", imports, ""); Assertions.assertTrue(codegenParameter.isContainer); Assertions.assertTrue(codegenParameter.items.isModel); @@ -2337,7 +2337,7 @@ public void arrayInnerReferencedSchemaMarkedAsModel_30() { RequestBody body = openAPI.getPaths().get("/examples").getPost().getRequestBody(); - CodegenParameter codegenParameter = codegen.fromRequestBody(body, imports, ""); + CodegenParameter codegenParameter = codegen.fromRequestBody(body, "opId", imports, ""); Assertions.assertTrue(codegenParameter.isContainer); Assertions.assertTrue(codegenParameter.items.isModel); @@ -4324,7 +4324,7 @@ public void testUnalias() { final DefaultCodegen codegen = new DefaultCodegen(); codegen.setOpenAPI(openAPI); - Schema requestBodySchema = ModelUtils.getSchemaFromRequestBody( + Schema requestBodySchema = ModelUtils.getFirstSchemaFromRequestBody( openAPI.getPaths().get("/thingy/{date}").getPost().getRequestBody()); Assertions.assertEquals(requestBodySchema.get$ref(), "#/components/schemas/updatePetWithForm_request"); Assertions.assertEquals(ModelUtils.getSimpleRef(requestBodySchema.get$ref()), "updatePetWithForm_request"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java index 750a78cacfb3..d5784661fb67 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java @@ -429,15 +429,15 @@ public void testRefModelValidationProperties() { // Validate when converting to parameter Operation operation = openAPI.getPaths().get("/fake/StringRegex").getPost(); RequestBody body = operation.getRequestBody(); - CodegenParameter codegenParameter = config.fromRequestBody(body, new HashSet<>(), "body"); + CodegenParameter codegenParameter = config.fromRequestBody(body, "opId", new HashSet<>(), "body"); Assert.assertEquals(codegenParameter.pattern, escapedPattern); // Validate when converting to response ApiResponse response = operation.getResponses().get("200"); - CodegenResponse codegenResponse = config.fromResponse("200", response); + CodegenResponse codegenResponse = config.fromResponse("opId", "200", response); - Assert.assertEquals(((Schema) codegenResponse.schema).getPattern(), expectedPattern); + Assert.assertEquals(((Schema)codegenResponse.schema).getPattern(), expectedPattern); Assert.assertEquals(codegenResponse.pattern, escapedPattern); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index a16014271aa5..49777abba3f5 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -144,7 +144,7 @@ public String toString() { "application/json", new MediaType().schema(new ArraySchema().items(new StringSchema())) )); - CodegenParameter codegenParameter1 = codegen.fromRequestBody(body1, new HashSet<>(), null); + CodegenParameter codegenParameter1 = codegen.fromRequestBody(body1, "opId", new HashSet<>(), null); Assertions.assertEquals(codegenParameter1.description, "A list of ids"); Assertions.assertEquals(codegenParameter1.dataType, "List"); Assertions.assertEquals(codegenParameter1.baseType, "String"); @@ -155,7 +155,7 @@ public String toString() { "application/json", new MediaType().schema(new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))) )); - CodegenParameter codegenParameter2 = codegen.fromRequestBody(body2, new HashSet<>(), null); + CodegenParameter codegenParameter2 = codegen.fromRequestBody(body2, "opId", new HashSet<>(), null); Assertions.assertEquals(codegenParameter2.description, "A list of list of values"); Assertions.assertEquals(codegenParameter2.dataType, "List>"); Assertions.assertEquals(codegenParameter2.baseType, "List"); @@ -174,7 +174,7 @@ public String toString() { point.addProperty("message", new StringSchema()); point.addProperty("x", new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)); point.addProperty("y", new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)); - CodegenParameter codegenParameter3 = codegen.fromRequestBody(body3, new HashSet<>(), null); + CodegenParameter codegenParameter3 = codegen.fromRequestBody(body3, "opId", new HashSet<>(), null); Assertions.assertEquals(codegenParameter3.description, "A list of points"); Assertions.assertEquals(codegenParameter3.dataType, "List"); Assertions.assertEquals(codegenParameter3.baseType, "Point"); @@ -595,7 +595,7 @@ public void testReferencedHeader() { codegen.setOpenAPI(openAPI); ApiResponse ok_200 = openAPI.getComponents().getResponses().get("OK_200"); - CodegenResponse response = codegen.fromResponse("200", ok_200); + CodegenResponse response = codegen.fromResponse("opId", "200", ok_200); Assertions.assertEquals(response.headers.size(), 1); CodegenProperty header = response.headers.get(0); From 09ed2d05e08534c325f213074fc936e8e9e8253a Mon Sep 17 00:00:00 2001 From: Richard Whitehouse Date: Wed, 21 Aug 2024 13:08:28 +0100 Subject: [PATCH 2/6] Update samples --- .../output/multipart-v3/src/client/mod.rs | 15 +- .../output/multipart-v3/src/server/mod.rs | 6 +- .../output/no-example-v3/src/client/mod.rs | 5 + .../output/no-example-v3/src/server/mod.rs | 1 + .../output/openapi-v3/docs/default_api.md | 2 +- .../output/openapi-v3/src/client/callbacks.rs | 2 + .../output/openapi-v3/src/client/mod.rs | 232 +- .../rust-server/output/openapi-v3/src/lib.rs | 4 +- .../output/openapi-v3/src/models.rs | 22 +- .../output/openapi-v3/src/server/callbacks.rs | 8 + .../output/openapi-v3/src/server/mod.rs | 69 + .../output/ops-v3/src/client/mod.rs | 148 + .../output/ops-v3/src/server/mod.rs | 37 + .../.openapi-generator/FILES | 18 + .../README.md | 18 + .../docs/AddPetApplicationSlashJsonRequest.md | 9 + .../docs/AddPetApplicationSlashXmlRequest.md | 9 + ...ByStatus200ApplicationSlashJsonResponse.md | 9 + ...sByStatus200ApplicationSlashXmlResponse.md | 9 + ...tsByTags200ApplicationSlashJsonResponse.md | 9 + ...etsByTags200ApplicationSlashXmlResponse.md | 9 + ...rderById200ApplicationSlashJsonResponse.md | 9 + ...OrderById200ApplicationSlashXmlResponse.md | 9 + ...tPetById200ApplicationSlashJsonResponse.md | 9 + ...etPetById200ApplicationSlashXmlResponse.md | 9 + ...erByName200ApplicationSlashJsonResponse.md | 9 + ...serByName200ApplicationSlashXmlResponse.md | 9 + ...oginUser200ApplicationSlashJsonResponse.md | 9 + ...LoginUser200ApplicationSlashXmlResponse.md | 9 + ...aceOrder200ApplicationSlashJsonResponse.md | 9 + ...laceOrder200ApplicationSlashXmlResponse.md | 9 + .../UpdatePetApplicationSlashJsonRequest.md | 9 + .../UpdatePetApplicationSlashXmlRequest.md | 9 + .../docs/pet_api.md | 10 +- .../docs/store_api.md | 4 +- .../docs/user_api.md | 4 +- .../examples/server/server.rs | 4 +- .../src/client/mod.rs | 556 ++- .../src/lib.rs | 32 +- .../src/models.rs | 3364 +++++++++++++++-- .../src/server/mod.rs | 347 +- .../output/ping-bearer-auth/src/client/mod.rs | 4 + .../output/ping-bearer-auth/src/server/mod.rs | 1 + .../output/rust-server-test/src/client/mod.rs | 61 +- .../output/rust-server-test/src/server/mod.rs | 28 + 45 files changed, 4642 insertions(+), 522 deletions(-) create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AddPetApplicationSlashJsonRequest.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AddPetApplicationSlashXmlRequest.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByStatus200ApplicationSlashJsonResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByStatus200ApplicationSlashXmlResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByTags200ApplicationSlashJsonResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByTags200ApplicationSlashXmlResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetOrderById200ApplicationSlashJsonResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetOrderById200ApplicationSlashXmlResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetPetById200ApplicationSlashJsonResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetPetById200ApplicationSlashXmlResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetUserByName200ApplicationSlashJsonResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetUserByName200ApplicationSlashXmlResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/LoginUser200ApplicationSlashJsonResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/LoginUser200ApplicationSlashXmlResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/PlaceOrder200ApplicationSlashJsonResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/PlaceOrder200ApplicationSlashXmlResponse.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/UpdatePetApplicationSlashJsonRequest.md create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/UpdatePetApplicationSlashXmlRequest.md diff --git a/samples/server/petstore/rust-server/output/multipart-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/multipart-v3/src/client/mod.rs index 42a5fbc96b86..86c1a7a5e194 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/src/client/mod.rs @@ -23,7 +23,8 @@ use mime::Mime; use std::io::Cursor; use multipart::client::lazy::Multipart; use hyper_0_10::header::{Headers, ContentType}; -use mime_multipart::{Node, Part, write_multipart}; +use log::warn; +use mime_multipart::{read_multipart_body, Node, Part, write_multipart}; use crate::models; use crate::header; @@ -423,6 +424,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Consumes multipart/related body let boundary = swagger::multipart::related::generate_boundary(); let mut body_parts = vec![]; @@ -489,6 +492,7 @@ impl Api for Client where // Add the message body to the request object. *request.body_mut() = Body::from(body); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -500,6 +504,7 @@ impl Api for Client where match response.status().as_u16() { 201 => { + let (header, body) = response.into_parts(); Ok( MultipartRelatedRequestPostResponse::OK ) @@ -561,6 +566,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Consumes multipart/form body let (body_string, multipart_header) = { let mut multipart = Multipart::new(); @@ -643,6 +650,7 @@ impl Api for Client where }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -654,6 +662,7 @@ impl Api for Client where match response.status().as_u16() { 201 => { + let (header, body) = response.into_parts(); Ok( MultipartRequestPostResponse::OK ) @@ -713,6 +722,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Consumes multipart/related body let boundary = swagger::multipart::related::generate_boundary(); let mut body_parts = vec![]; @@ -764,6 +775,7 @@ impl Api for Client where // Add the message body to the request object. *request.body_mut() = Body::from(body); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -775,6 +787,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( MultipleIdenticalMimeTypesPostResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/multipart-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/multipart-v3/src/server/mod.rs index e9296a9524a5..f2564b4a6183 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/src/server/mod.rs @@ -13,8 +13,7 @@ pub use swagger::auth::Authorization; use swagger::auth::Scopes; use url::form_urlencoded; use hyper_0_10::header::{Headers, ContentType}; -use mime_0_2::{TopLevel, SubLevel, Mime as Mime2}; -use mime_multipart::{read_multipart_body, Node, Part}; +use mime_multipart::{read_multipart_body, Node, Part, write_multipart}; use multipart::server::Multipart; use multipart::server::save::{PartialReason, SaveResult}; @@ -295,6 +294,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + }, }, Err(_) => { @@ -483,6 +483,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + }, }, Err(_) => { @@ -589,6 +590,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { diff --git a/samples/server/petstore/rust-server/output/no-example-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/no-example-v3/src/client/mod.rs index 218967ec7a60..4a48787b82ea 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/no-example-v3/src/client/mod.rs @@ -414,6 +414,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = serde_json::to_string(¶m_op_get_request).expect("impossible to fail to serialize"); @@ -425,6 +428,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -436,6 +440,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( OpGetResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/no-example-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/no-example-v3/src/server/mod.rs index c9632d351d20..f46936c5c3a2 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/no-example-v3/src/server/mod.rs @@ -200,6 +200,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/default_api.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/default_api.md index e0897cd495b7..5955322619fd 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/docs/default_api.md +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/default_api.md @@ -216,7 +216,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/octet-stream, application/xml, text/plain + - **Accept**: application/json, application/xml, application/octet-stream, text/plain [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/client/callbacks.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/client/callbacks.rs index 97198a90b7eb..b19b62a9481a 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/client/callbacks.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/client/callbacks.rs @@ -208,6 +208,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + }, }, Err(_) => { @@ -249,6 +250,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + }, }, Err(_) => { diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs index f6c7c7035989..f9874ea6e047 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs @@ -445,6 +445,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -456,49 +459,55 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(AnyOfGetResponse::Success (body) ) } 201 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(AnyOfGetResponse::AlternateSuccess (body) ) } 202 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(AnyOfGetResponse::AnyOfSuccess (body) ) @@ -559,6 +568,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -570,6 +582,7 @@ impl Api for Client where match response.status().as_u16() { 204 => { + let (header, body) = response.into_parts(); Ok( CallbackWithHeaderPostResponse::OK ) @@ -632,6 +645,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -643,6 +659,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( ComplexQueryParamGetResponse::Success ) @@ -708,6 +725,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -719,6 +739,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( JsonComplexQueryParamGetResponse::Success ) @@ -777,6 +798,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -800,6 +824,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( MandatoryRequestHeaderGetResponse::Success ) @@ -857,6 +882,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -868,17 +896,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/merge-patch+json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(MergePatchJsonGetResponse::Merge (body) ) @@ -936,6 +966,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -947,27 +980,30 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(MultigetGetResponse::JSONRsp (body) ) } 201 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -976,82 +1012,93 @@ impl Api for Client where .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(MultigetGetResponse::XMLRsp (body) ) } 202 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/octet-stream let body = swagger::ByteArray(body.to_vec()); + Ok(MultigetGetResponse::OctetRsp (body) ) } 203 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // text/plain let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = body.to_string(); + Ok(MultigetGetResponse::StringRsp (body) ) } 204 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(MultigetGetResponse::DuplicateResponseLongText (body) ) } 205 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(MultigetGetResponse::DuplicateResponseLongText_2 (body) ) } 206 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(MultigetGetResponse::DuplicateResponseLongText_3 (body) ) @@ -1109,6 +1156,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1139,6 +1189,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( MultipleAuthSchemeGetResponse::CheckThatLimitingToMultipleRequiredAuthSchemesWorks ) @@ -1196,6 +1247,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1207,17 +1261,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(OneOfGetResponse::Success (body) ) @@ -1275,6 +1331,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1286,6 +1345,7 @@ impl Api for Client where match response.status().as_u16() { 204 => { + let (header, body) = response.into_parts(); Ok( OverrideServerGetResponse::Success ) @@ -1358,6 +1418,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1369,17 +1432,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(ParamgetGetResponse::JSONRsp (body) ) @@ -1437,6 +1502,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1467,6 +1535,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( ReadonlyAuthSchemeGetResponse::CheckThatLimitingToASingleRequiredAuthSchemeWorks ) @@ -1527,6 +1596,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1538,6 +1610,7 @@ impl Api for Client where match response.status().as_u16() { 204 => { + let (header, body) = response.into_parts(); Ok( RegisterCallbackPostResponse::OK ) @@ -1596,6 +1669,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = param_body.0; @@ -1607,6 +1683,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1618,6 +1695,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( RequiredOctetStreamPutResponse::OK ) @@ -1675,6 +1753,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1686,7 +1767,8 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let response_success_info = match response.headers().get(HeaderName::from_static("success-info")) { + let (header, body) = response.into_parts(); + let response_success_info = match header.headers.get(HeaderName::from_static("success-info")) { Some(response_success_info) => { let response_success_info = response_success_info.clone(); let response_success_info = match TryInto::>::try_into(response_success_info) { @@ -1700,7 +1782,7 @@ impl Api for Client where None => return Err(ApiError(String::from("Required response header Success-Info for response 200 was not found."))), }; - let response_bool_header = match response.headers().get(HeaderName::from_static("bool-header")) { + let response_bool_header = match header.headers.get(HeaderName::from_static("bool-header")) { Some(response_bool_header) => { let response_bool_header = response_bool_header.clone(); let response_bool_header = match TryInto::>::try_into(response_bool_header) { @@ -1714,7 +1796,7 @@ impl Api for Client where None => None, }; - let response_object_header = match response.headers().get(HeaderName::from_static("object-header")) { + let response_object_header = match header.headers.get(HeaderName::from_static("object-header")) { Some(response_object_header) => { let response_object_header = response_object_header.clone(); let response_object_header = match TryInto::>::try_into(response_object_header) { @@ -1728,17 +1810,18 @@ impl Api for Client where None => None, }; - let body = response.into_body(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(ResponsesWithHeadersGetResponse::Success { body, @@ -1749,7 +1832,8 @@ impl Api for Client where ) } 412 => { - let response_further_info = match response.headers().get(HeaderName::from_static("further-info")) { + let (header, body) = response.into_parts(); + let response_further_info = match header.headers.get(HeaderName::from_static("further-info")) { Some(response_further_info) => { let response_further_info = response_further_info.clone(); let response_further_info = match TryInto::>::try_into(response_further_info) { @@ -1763,7 +1847,7 @@ impl Api for Client where None => None, }; - let response_failure_info = match response.headers().get(HeaderName::from_static("failure-info")) { + let response_failure_info = match header.headers.get(HeaderName::from_static("failure-info")) { Some(response_failure_info) => { let response_failure_info = response_failure_info.clone(); let response_failure_info = match TryInto::>::try_into(response_failure_info) { @@ -1838,6 +1922,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1849,43 +1936,48 @@ impl Api for Client where match response.status().as_u16() { 204 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(Rfc7807GetResponse::OK (body) ) } 404 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/problem+json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(Rfc7807GetResponse::NotFound (body) ) } 406 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/problem+xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -1894,6 +1986,7 @@ impl Api for Client where .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(Rfc7807GetResponse::NotAcceptable (body) ) @@ -1952,12 +2045,15 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Optional Basic Schema + if let Some(param_object_untyped_props) = param_object_untyped_props { + // Consumes basic body // Body parameter - if let Some(param_object_untyped_props) = param_object_untyped_props { let body = serde_json::to_string(¶m_object_untyped_props).expect("impossible to fail to serialize"); *request.body_mut() = Body::from(body); - } let header = "application/json"; request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { @@ -1965,6 +2061,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + } + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1976,6 +2074,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( UntypedPropertyGetResponse::CheckThatUntypedPropertiesWorks ) @@ -2033,6 +2132,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2044,17 +2146,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body) + let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(UuidGetResponse::DuplicateResponseLongText (body) ) @@ -2113,12 +2217,15 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Optional Basic Schema + if let Some(param_duplicate_xml_object) = param_duplicate_xml_object { + // Consumes basic body // Body parameter - if let Some(param_duplicate_xml_object) = param_duplicate_xml_object { let body = param_duplicate_xml_object.as_xml(); *request.body_mut() = Body::from(body); - } let header = "application/xml"; request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { @@ -2126,6 +2233,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + } + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2137,11 +2246,13 @@ impl Api for Client where match response.status().as_u16() { 201 => { + let (header, body) = response.into_parts(); Ok( XmlExtraPostResponse::OK ) } 400 => { + let (header, body) = response.into_parts(); Ok( XmlExtraPostResponse::BadRequest ) @@ -2200,12 +2311,15 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Optional Basic Schema + if let Some(param_another_xml_object) = param_another_xml_object { + // Consumes basic body // Body parameter - if let Some(param_another_xml_object) = param_another_xml_object { let body = param_another_xml_object.as_xml(); *request.body_mut() = Body::from(body); - } let header = "text/xml"; request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { @@ -2213,6 +2327,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + } + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2224,11 +2340,12 @@ impl Api for Client where match response.status().as_u16() { 201 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // text/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -2237,11 +2354,13 @@ impl Api for Client where .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(XmlOtherPostResponse::OK (body) ) } 400 => { + let (header, body) = response.into_parts(); Ok( XmlOtherPostResponse::BadRequest ) @@ -2300,12 +2419,15 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Optional Basic Schema + if let Some(param_another_xml_array) = param_another_xml_array { + // Consumes basic body // Body parameter - if let Some(param_another_xml_array) = param_another_xml_array { let body = param_another_xml_array.as_xml(); *request.body_mut() = Body::from(body); - } let header = "application/xml"; request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { @@ -2313,6 +2435,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + } + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2324,11 +2448,13 @@ impl Api for Client where match response.status().as_u16() { 201 => { + let (header, body) = response.into_parts(); Ok( XmlOtherPutResponse::OK ) } 400 => { + let (header, body) = response.into_parts(); Ok( XmlOtherPutResponse::BadRequest ) @@ -2387,12 +2513,15 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Optional Basic Schema + if let Some(param_xml_array) = param_xml_array { + // Consumes basic body // Body parameter - if let Some(param_xml_array) = param_xml_array { let body = param_xml_array.as_xml(); *request.body_mut() = Body::from(body); - } let header = "application/xml"; request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { @@ -2400,6 +2529,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + } + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2411,11 +2542,13 @@ impl Api for Client where match response.status().as_u16() { 201 => { + let (header, body) = response.into_parts(); Ok( XmlPostResponse::OK ) } 400 => { + let (header, body) = response.into_parts(); Ok( XmlPostResponse::BadRequest ) @@ -2474,12 +2607,15 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Optional Basic Schema + if let Some(param_xml_object) = param_xml_object { + // Consumes basic body // Body parameter - if let Some(param_xml_object) = param_xml_object { let body = param_xml_object.as_xml(); *request.body_mut() = Body::from(body); - } let header = "application/xml"; request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { @@ -2487,6 +2623,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + } + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2498,11 +2636,13 @@ impl Api for Client where match response.status().as_u16() { 201 => { + let (header, body) = response.into_parts(); Ok( XmlPutResponse::OK ) } 400 => { + let (header, body) = response.into_parts(); Ok( XmlPutResponse::BadRequest ) @@ -2562,6 +2702,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2573,6 +2716,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( EnumInPathPathParamGetResponse::Success ) @@ -2631,6 +2775,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = serde_json::to_string(¶m_object_param).expect("impossible to fail to serialize"); @@ -2642,6 +2789,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2653,6 +2801,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( CreateRepoResponse::Success ) @@ -2712,6 +2861,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2723,17 +2875,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body) + let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(GetRepoInfoResponse::OK (body) ) diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs index ed43bd647d31..bd216e90a948 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs @@ -205,7 +205,7 @@ pub enum UntypedPropertyGetResponse { pub enum UuidGetResponse { /// Duplicate Response long text. One. DuplicateResponseLongText - (uuid::Uuid) + (models::UuidObject) } #[derive(Debug, PartialEq, Serialize, Deserialize)] @@ -275,7 +275,7 @@ pub enum CreateRepoResponse { pub enum GetRepoInfoResponse { /// OK OK - (String) + (models::StringObject) } /// API diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs index 043e71c56a1c..f2999ba5cb35 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -342,7 +342,7 @@ impl AnotherXmlArray { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] #[serde(rename = "snake_another_xml_inner")] pub struct AnotherXmlInner(String); @@ -1742,7 +1742,7 @@ impl EnumWithStarObject { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct Err(String); @@ -1877,7 +1877,7 @@ impl Err { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct Error(String); @@ -2466,7 +2466,7 @@ impl MultigetGet201Response { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct MyId(i32); @@ -3854,7 +3854,7 @@ impl ObjectWithArrayOfObjects { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct Ok(String); @@ -4132,7 +4132,7 @@ impl OneOfGet200Response { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct OptionalObjectHeader(i32); @@ -4277,7 +4277,7 @@ impl OptionalObjectHeader { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct RequiredObjectHeader(bool); @@ -4422,7 +4422,7 @@ impl RequiredObjectHeader { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct Result(String); @@ -4685,7 +4685,7 @@ impl StringEnum { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct StringObject(String); @@ -4821,7 +4821,7 @@ impl StringObject { } /// Test a model containing a UUID -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct UuidObject(uuid::Uuid); @@ -5159,7 +5159,7 @@ impl XmlArray { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] #[serde(rename = "camelXmlInner")] pub struct XmlInner(String); diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/server/callbacks.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/server/callbacks.rs index 5bda72e889d5..4fca4050a15d 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/server/callbacks.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/callbacks.rs @@ -264,6 +264,9 @@ impl CallbackApi for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -293,6 +296,7 @@ impl CallbackApi for Client where match response.status().as_u16() { 204 => { + let (header, body) = response.into_parts(); Ok( CallbackCallbackWithHeaderPostResponse::OK ) @@ -351,6 +355,9 @@ impl CallbackApi for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -362,6 +369,7 @@ impl CallbackApi for Client where match response.status().as_u16() { 204 => { + let (header, body) = response.into_parts(); Ok( CallbackCallbackPostResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs index 025004ed700e..68d462c086ee 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs @@ -259,6 +259,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -267,11 +268,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, AnyOfGetResponse::AlternateSuccess (body) => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -280,11 +283,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, AnyOfGetResponse::AnyOfSuccess (body) => { *response.status_mut() = StatusCode::from_u16(202).expect("Unable to turn 202 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -293,6 +298,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -351,6 +357,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + }, }, Err(_) => { @@ -393,6 +400,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -444,6 +452,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -498,6 +507,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -528,6 +538,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/merge-patch+json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/merge-patch+json") @@ -536,6 +547,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -566,6 +578,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -574,11 +587,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, MultigetGetResponse::XMLRsp (body) => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + // application/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/xml") @@ -587,11 +602,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, MultigetGetResponse::OctetRsp (body) => { *response.status_mut() = StatusCode::from_u16(202).expect("Unable to turn 202 into a StatusCode"); + // application/octet-stream response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/octet-stream") @@ -600,11 +617,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = body.0; *response.body_mut() = Body::from(body); + }, MultigetGetResponse::StringRsp (body) => { *response.status_mut() = StatusCode::from_u16(203).expect("Unable to turn 203 into a StatusCode"); + // text/plain response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("text/plain") @@ -613,11 +632,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = body; *response.body_mut() = Body::from(body); + }, MultigetGetResponse::DuplicateResponseLongText (body) => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -626,11 +647,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, MultigetGetResponse::DuplicateResponseLongText_2 (body) => { *response.status_mut() = StatusCode::from_u16(205).expect("Unable to turn 205 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -639,11 +662,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, MultigetGetResponse::DuplicateResponseLongText_3 (body) => { *response.status_mut() = StatusCode::from_u16(206).expect("Unable to turn 206 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -652,6 +677,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -712,6 +738,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -742,6 +769,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -750,6 +778,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -780,6 +809,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + }, }, Err(_) => { @@ -867,6 +897,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -875,6 +906,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -934,6 +966,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -992,6 +1025,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + }, }, Err(_) => { @@ -1013,6 +1047,7 @@ impl hyper::service::Service<(Request, C)> for Service where let result = body.into_raw().await; match result { Ok(body) => { + let mut unused_elements : Vec = vec![]; let param_body: Option = if !body.is_empty() { Some(swagger::ByteArray(body.to_vec())) } else { @@ -1037,12 +1072,19 @@ impl hyper::service::Service<(Request, C)> for Service where HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); + if !unused_elements.is_empty() { + response.headers_mut().insert( + HeaderName::from_static("warning"), + HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) + .expect("Unable to create Warning header value")); + } match result { Ok(rsp) => match rsp { RequiredOctetStreamPutResponse::OK => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1133,6 +1175,7 @@ impl hyper::service::Service<(Request, C)> for Service where object_header ); } + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -1141,6 +1184,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, ResponsesWithHeadersGetResponse::PreconditionFailed { @@ -1184,6 +1228,7 @@ impl hyper::service::Service<(Request, C)> for Service where ); } + }, }, Err(_) => { @@ -1214,6 +1259,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -1222,11 +1268,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, Rfc7807GetResponse::NotFound (body) => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + // application/problem+json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/problem+json") @@ -1235,11 +1283,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, Rfc7807GetResponse::NotAcceptable (body) => { *response.status_mut() = StatusCode::from_u16(406).expect("Unable to turn 406 into a StatusCode"); + // application/problem+xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/problem+xml") @@ -1248,6 +1298,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -1306,6 +1357,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1342,6 +1394,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -1350,6 +1403,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -1408,11 +1462,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + }, XmlExtraPostResponse::BadRequest => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -1477,6 +1533,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + // text/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("text/xml") @@ -1489,11 +1546,13 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, XmlOtherPostResponse::BadRequest => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -1558,11 +1617,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + }, XmlOtherPutResponse::BadRequest => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -1627,11 +1688,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + }, XmlPostResponse::BadRequest => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -1696,11 +1759,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + }, XmlPutResponse::BadRequest => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -1761,6 +1826,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1829,6 +1895,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1889,6 +1956,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -1897,6 +1965,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { diff --git a/samples/server/petstore/rust-server/output/ops-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/ops-v3/src/client/mod.rs index f3dbc73c9892..a1f657db58ea 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/ops-v3/src/client/mod.rs @@ -449,6 +449,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -460,6 +463,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op10GetResponse::OK ) @@ -517,6 +521,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -528,6 +535,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op11GetResponse::OK ) @@ -585,6 +593,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -596,6 +607,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op12GetResponse::OK ) @@ -653,6 +665,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -664,6 +679,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op13GetResponse::OK ) @@ -721,6 +737,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -732,6 +751,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op14GetResponse::OK ) @@ -789,6 +809,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -800,6 +823,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op15GetResponse::OK ) @@ -857,6 +881,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -868,6 +895,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op16GetResponse::OK ) @@ -925,6 +953,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -936,6 +967,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op17GetResponse::OK ) @@ -993,6 +1025,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1004,6 +1039,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op18GetResponse::OK ) @@ -1061,6 +1097,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1072,6 +1111,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op19GetResponse::OK ) @@ -1129,6 +1169,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1140,6 +1183,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op1GetResponse::OK ) @@ -1197,6 +1241,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1208,6 +1255,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op20GetResponse::OK ) @@ -1265,6 +1313,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1276,6 +1327,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op21GetResponse::OK ) @@ -1333,6 +1385,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1344,6 +1399,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op22GetResponse::OK ) @@ -1401,6 +1457,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1412,6 +1471,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op23GetResponse::OK ) @@ -1469,6 +1529,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1480,6 +1543,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op24GetResponse::OK ) @@ -1537,6 +1601,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1548,6 +1615,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op25GetResponse::OK ) @@ -1605,6 +1673,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1616,6 +1687,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op26GetResponse::OK ) @@ -1673,6 +1745,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1684,6 +1759,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op27GetResponse::OK ) @@ -1741,6 +1817,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1752,6 +1831,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op28GetResponse::OK ) @@ -1809,6 +1889,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1820,6 +1903,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op29GetResponse::OK ) @@ -1877,6 +1961,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1888,6 +1975,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op2GetResponse::OK ) @@ -1945,6 +2033,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1956,6 +2047,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op30GetResponse::OK ) @@ -2013,6 +2105,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2024,6 +2119,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op31GetResponse::OK ) @@ -2081,6 +2177,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2092,6 +2191,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op32GetResponse::OK ) @@ -2149,6 +2249,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2160,6 +2263,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op33GetResponse::OK ) @@ -2217,6 +2321,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2228,6 +2335,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op34GetResponse::OK ) @@ -2285,6 +2393,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2296,6 +2407,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op35GetResponse::OK ) @@ -2353,6 +2465,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2364,6 +2479,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op36GetResponse::OK ) @@ -2421,6 +2537,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2432,6 +2551,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op37GetResponse::OK ) @@ -2489,6 +2609,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2500,6 +2623,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op3GetResponse::OK ) @@ -2557,6 +2681,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2568,6 +2695,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op4GetResponse::OK ) @@ -2625,6 +2753,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2636,6 +2767,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op5GetResponse::OK ) @@ -2693,6 +2825,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2704,6 +2839,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op6GetResponse::OK ) @@ -2761,6 +2897,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2772,6 +2911,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op7GetResponse::OK ) @@ -2829,6 +2969,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2840,6 +2983,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op8GetResponse::OK ) @@ -2897,6 +3041,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2908,6 +3055,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Op9GetResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/ops-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/ops-v3/src/server/mod.rs index 47846655bfb7..ac9a0b2ffe29 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/ops-v3/src/server/mod.rs @@ -270,6 +270,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -300,6 +301,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -330,6 +332,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -360,6 +363,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -390,6 +394,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -420,6 +425,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -450,6 +456,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -480,6 +487,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -510,6 +518,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -540,6 +549,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -570,6 +580,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -600,6 +611,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -630,6 +642,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -660,6 +673,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -690,6 +704,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -720,6 +735,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -750,6 +766,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -780,6 +797,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -810,6 +828,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -840,6 +859,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -870,6 +890,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -900,6 +921,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -930,6 +952,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -960,6 +983,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -990,6 +1014,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1020,6 +1045,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1050,6 +1076,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1080,6 +1107,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1110,6 +1138,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1140,6 +1169,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1170,6 +1200,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1200,6 +1231,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1230,6 +1262,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1260,6 +1293,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1290,6 +1324,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1320,6 +1355,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1350,6 +1386,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES index a0e98549a01d..dd0ece514673 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES @@ -3,6 +3,8 @@ Cargo.toml README.md api/openapi.yaml +docs/AddPetApplicationSlashJsonRequest.md +docs/AddPetApplicationSlashXmlRequest.md docs/AdditionalPropertiesClass.md docs/Animal.md docs/AnimalFarm.md @@ -25,10 +27,22 @@ docs/EnumClass.md docs/EnumTest.md docs/EnumTestEnumInteger.md docs/EnumTestEnumString.md +docs/FindPetsByStatus200ApplicationSlashJsonResponse.md +docs/FindPetsByStatus200ApplicationSlashXmlResponse.md docs/FindPetsByStatusStatusParameterInner.md +docs/FindPetsByTags200ApplicationSlashJsonResponse.md +docs/FindPetsByTags200ApplicationSlashXmlResponse.md docs/FormatTest.md +docs/GetOrderById200ApplicationSlashJsonResponse.md +docs/GetOrderById200ApplicationSlashXmlResponse.md +docs/GetPetById200ApplicationSlashJsonResponse.md +docs/GetPetById200ApplicationSlashXmlResponse.md +docs/GetUserByName200ApplicationSlashJsonResponse.md +docs/GetUserByName200ApplicationSlashXmlResponse.md docs/HasOnlyReadOnly.md docs/List.md +docs/LoginUser200ApplicationSlashJsonResponse.md +docs/LoginUser200ApplicationSlashXmlResponse.md docs/MapTest.md docs/MapTestMapMapOfEnumValueValue.md docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -46,6 +60,8 @@ docs/OuterNumber.md docs/OuterString.md docs/Pet.md docs/PetStatus.md +docs/PlaceOrder200ApplicationSlashJsonResponse.md +docs/PlaceOrder200ApplicationSlashXmlResponse.md docs/ReadOnlyFirst.md docs/Return.md docs/Tag.md @@ -54,6 +70,8 @@ docs/TestEnumParametersEnumHeaderStringParameter.md docs/TestEnumParametersEnumQueryDoubleParameter.md docs/TestEnumParametersEnumQueryIntegerParameter.md docs/TestEnumParametersRequestEnumFormString.md +docs/UpdatePetApplicationSlashJsonRequest.md +docs/UpdatePetApplicationSlashXmlRequest.md docs/User.md docs/another_fake_api.md docs/fake_api.md diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md index 15d416ccaafb..1d67b06e1b07 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md @@ -158,6 +158,8 @@ Method | HTTP request | Description ## Documentation For Models + - [AddPetApplicationSlashJsonRequest](docs/AddPetApplicationSlashJsonRequest.md) + - [AddPetApplicationSlashXmlRequest](docs/AddPetApplicationSlashXmlRequest.md) - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Animal](docs/Animal.md) - [AnimalFarm](docs/AnimalFarm.md) @@ -180,10 +182,22 @@ Method | HTTP request | Description - [EnumTest](docs/EnumTest.md) - [EnumTestEnumInteger](docs/EnumTestEnumInteger.md) - [EnumTestEnumString](docs/EnumTestEnumString.md) + - [FindPetsByStatus200ApplicationSlashJsonResponse](docs/FindPetsByStatus200ApplicationSlashJsonResponse.md) + - [FindPetsByStatus200ApplicationSlashXmlResponse](docs/FindPetsByStatus200ApplicationSlashXmlResponse.md) - [FindPetsByStatusStatusParameterInner](docs/FindPetsByStatusStatusParameterInner.md) + - [FindPetsByTags200ApplicationSlashJsonResponse](docs/FindPetsByTags200ApplicationSlashJsonResponse.md) + - [FindPetsByTags200ApplicationSlashXmlResponse](docs/FindPetsByTags200ApplicationSlashXmlResponse.md) - [FormatTest](docs/FormatTest.md) + - [GetOrderById200ApplicationSlashJsonResponse](docs/GetOrderById200ApplicationSlashJsonResponse.md) + - [GetOrderById200ApplicationSlashXmlResponse](docs/GetOrderById200ApplicationSlashXmlResponse.md) + - [GetPetById200ApplicationSlashJsonResponse](docs/GetPetById200ApplicationSlashJsonResponse.md) + - [GetPetById200ApplicationSlashXmlResponse](docs/GetPetById200ApplicationSlashXmlResponse.md) + - [GetUserByName200ApplicationSlashJsonResponse](docs/GetUserByName200ApplicationSlashJsonResponse.md) + - [GetUserByName200ApplicationSlashXmlResponse](docs/GetUserByName200ApplicationSlashXmlResponse.md) - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - [List](docs/List.md) + - [LoginUser200ApplicationSlashJsonResponse](docs/LoginUser200ApplicationSlashJsonResponse.md) + - [LoginUser200ApplicationSlashXmlResponse](docs/LoginUser200ApplicationSlashXmlResponse.md) - [MapTest](docs/MapTest.md) - [MapTestMapMapOfEnumValueValue](docs/MapTestMapMapOfEnumValueValue.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) @@ -201,6 +215,8 @@ Method | HTTP request | Description - [OuterString](docs/OuterString.md) - [Pet](docs/Pet.md) - [PetStatus](docs/PetStatus.md) + - [PlaceOrder200ApplicationSlashJsonResponse](docs/PlaceOrder200ApplicationSlashJsonResponse.md) + - [PlaceOrder200ApplicationSlashXmlResponse](docs/PlaceOrder200ApplicationSlashXmlResponse.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [Return](docs/Return.md) - [Tag](docs/Tag.md) @@ -209,6 +225,8 @@ Method | HTTP request | Description - [TestEnumParametersEnumQueryDoubleParameter](docs/TestEnumParametersEnumQueryDoubleParameter.md) - [TestEnumParametersEnumQueryIntegerParameter](docs/TestEnumParametersEnumQueryIntegerParameter.md) - [TestEnumParametersRequestEnumFormString](docs/TestEnumParametersRequestEnumFormString.md) + - [UpdatePetApplicationSlashJsonRequest](docs/UpdatePetApplicationSlashJsonRequest.md) + - [UpdatePetApplicationSlashXmlRequest](docs/UpdatePetApplicationSlashXmlRequest.md) - [User](docs/User.md) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AddPetApplicationSlashJsonRequest.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AddPetApplicationSlashJsonRequest.md new file mode 100644 index 000000000000..3fcd4b52435e --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AddPetApplicationSlashJsonRequest.md @@ -0,0 +1,9 @@ +# AddPetApplicationSlashJsonRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AddPetApplicationSlashXmlRequest.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AddPetApplicationSlashXmlRequest.md new file mode 100644 index 000000000000..4b2a2e9c2c70 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AddPetApplicationSlashXmlRequest.md @@ -0,0 +1,9 @@ +# AddPetApplicationSlashXmlRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByStatus200ApplicationSlashJsonResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByStatus200ApplicationSlashJsonResponse.md new file mode 100644 index 000000000000..b3f02d365751 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByStatus200ApplicationSlashJsonResponse.md @@ -0,0 +1,9 @@ +# FindPetsByStatus200ApplicationSlashJsonResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByStatus200ApplicationSlashXmlResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByStatus200ApplicationSlashXmlResponse.md new file mode 100644 index 000000000000..a8e7c87aa723 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByStatus200ApplicationSlashXmlResponse.md @@ -0,0 +1,9 @@ +# FindPetsByStatus200ApplicationSlashXmlResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByTags200ApplicationSlashJsonResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByTags200ApplicationSlashJsonResponse.md new file mode 100644 index 000000000000..360caedc7f7d --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByTags200ApplicationSlashJsonResponse.md @@ -0,0 +1,9 @@ +# FindPetsByTags200ApplicationSlashJsonResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByTags200ApplicationSlashXmlResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByTags200ApplicationSlashXmlResponse.md new file mode 100644 index 000000000000..ed63eed87a69 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FindPetsByTags200ApplicationSlashXmlResponse.md @@ -0,0 +1,9 @@ +# FindPetsByTags200ApplicationSlashXmlResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetOrderById200ApplicationSlashJsonResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetOrderById200ApplicationSlashJsonResponse.md new file mode 100644 index 000000000000..c0b15915b577 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetOrderById200ApplicationSlashJsonResponse.md @@ -0,0 +1,9 @@ +# GetOrderById200ApplicationSlashJsonResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetOrderById200ApplicationSlashXmlResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetOrderById200ApplicationSlashXmlResponse.md new file mode 100644 index 000000000000..30c57940b3b8 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetOrderById200ApplicationSlashXmlResponse.md @@ -0,0 +1,9 @@ +# GetOrderById200ApplicationSlashXmlResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetPetById200ApplicationSlashJsonResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetPetById200ApplicationSlashJsonResponse.md new file mode 100644 index 000000000000..029f2b739da6 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetPetById200ApplicationSlashJsonResponse.md @@ -0,0 +1,9 @@ +# GetPetById200ApplicationSlashJsonResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetPetById200ApplicationSlashXmlResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetPetById200ApplicationSlashXmlResponse.md new file mode 100644 index 000000000000..a3b3c9cf6a80 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetPetById200ApplicationSlashXmlResponse.md @@ -0,0 +1,9 @@ +# GetPetById200ApplicationSlashXmlResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetUserByName200ApplicationSlashJsonResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetUserByName200ApplicationSlashJsonResponse.md new file mode 100644 index 000000000000..19bf19a5ffe1 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetUserByName200ApplicationSlashJsonResponse.md @@ -0,0 +1,9 @@ +# GetUserByName200ApplicationSlashJsonResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetUserByName200ApplicationSlashXmlResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetUserByName200ApplicationSlashXmlResponse.md new file mode 100644 index 000000000000..d5794deab00f --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/GetUserByName200ApplicationSlashXmlResponse.md @@ -0,0 +1,9 @@ +# GetUserByName200ApplicationSlashXmlResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/LoginUser200ApplicationSlashJsonResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/LoginUser200ApplicationSlashJsonResponse.md new file mode 100644 index 000000000000..72b44fbdf0fc --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/LoginUser200ApplicationSlashJsonResponse.md @@ -0,0 +1,9 @@ +# LoginUser200ApplicationSlashJsonResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/LoginUser200ApplicationSlashXmlResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/LoginUser200ApplicationSlashXmlResponse.md new file mode 100644 index 000000000000..0046ab6b89c9 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/LoginUser200ApplicationSlashXmlResponse.md @@ -0,0 +1,9 @@ +# LoginUser200ApplicationSlashXmlResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/PlaceOrder200ApplicationSlashJsonResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/PlaceOrder200ApplicationSlashJsonResponse.md new file mode 100644 index 000000000000..55f044dd1032 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/PlaceOrder200ApplicationSlashJsonResponse.md @@ -0,0 +1,9 @@ +# PlaceOrder200ApplicationSlashJsonResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/PlaceOrder200ApplicationSlashXmlResponse.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/PlaceOrder200ApplicationSlashXmlResponse.md new file mode 100644 index 000000000000..dd190f7da39d --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/PlaceOrder200ApplicationSlashXmlResponse.md @@ -0,0 +1,9 @@ +# PlaceOrder200ApplicationSlashXmlResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/UpdatePetApplicationSlashJsonRequest.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/UpdatePetApplicationSlashJsonRequest.md new file mode 100644 index 000000000000..f6e999e8a3da --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/UpdatePetApplicationSlashJsonRequest.md @@ -0,0 +1,9 @@ +# UpdatePetApplicationSlashJsonRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/UpdatePetApplicationSlashXmlRequest.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/UpdatePetApplicationSlashXmlRequest.md new file mode 100644 index 000000000000..e1439d24d542 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/UpdatePetApplicationSlashXmlRequest.md @@ -0,0 +1,9 @@ +# UpdatePetApplicationSlashXmlRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/pet_api.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/pet_api.md index 26e6a98d32f4..12d0ea4b6bca 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/pet_api.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/pet_api.md @@ -23,7 +23,7 @@ Add a new pet to the store Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **body** | [****](.md)| Pet object that needs to be added to the store | ### Return type @@ -64,7 +64,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -92,7 +92,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -105,7 +105,7 @@ Update an existing pet Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **body** | [****](.md)| Pet object that needs to be added to the store | ### Return type @@ -181,7 +181,7 @@ Name | Type | Description | Notes ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/store_api.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/store_api.md index f8e633abd83e..3050823e7823 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/store_api.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/store_api.md @@ -55,7 +55,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -109,7 +109,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/user_api.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/user_api.md index 9518a5d031c5..e4e5b8a136d3 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/user_api.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/user_api.md @@ -113,7 +113,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -187,7 +187,7 @@ No authorization required ### HTTP request headers - **Content-Type**: Not defined - - **Accept**: application/json, application/xml + - **Accept**: application/xml, application/json [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs index 2920da486195..bf2dcb5d283a 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs @@ -309,7 +309,7 @@ impl Api for Server where C: Has + Send + Sync /// Add a new pet to the store async fn add_pet( &self, - body: models::Pet, + body: swagger::OneOf2, context: &C) -> Result { info!("add_pet({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); @@ -339,7 +339,7 @@ impl Api for Server where C: Has + Send + Sync /// Update an existing pet async fn update_pet( &self, - body: models::Pet, + body: swagger::OneOf2, context: &C) -> Result { info!("update_pet({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs index 96e66db706f5..43dfdc7a0b09 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs @@ -451,6 +451,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); @@ -462,6 +465,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -473,17 +477,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(TestSpecialTagsResponse::SuccessfulOperation (body) ) @@ -541,6 +547,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -552,6 +561,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( Call123exampleResponse::Success ) @@ -610,18 +620,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - if let Some(param_body) = param_body { - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - } + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -634,17 +634,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // */* let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body) + let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(FakeOuterBooleanSerializeResponse::OutputBoolean (body) ) @@ -703,18 +705,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - if let Some(param_body) = param_body { - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - } + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -727,17 +719,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // */* let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(FakeOuterCompositeSerializeResponse::OutputComposite (body) ) @@ -796,18 +790,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - if let Some(param_body) = param_body { - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - } + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -820,17 +804,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // */* let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body) + let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(FakeOuterNumberSerializeResponse::OutputNumber (body) ) @@ -889,18 +875,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - if let Some(param_body) = param_body { - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); - } + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -913,17 +889,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // */* let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; - let body = serde_json::from_str::(body) + let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(FakeOuterStringSerializeResponse::OutputString (body) ) @@ -981,6 +959,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -992,6 +973,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( FakeResponseWithNumericalDescriptionResponse::Status200 ) @@ -1053,6 +1035,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); @@ -1064,6 +1049,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1075,6 +1061,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( TestBodyWithQueryParamsResponse::Success ) @@ -1133,6 +1120,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); @@ -1144,6 +1134,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1155,17 +1146,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(TestClientModelResponse::SuccessfulOperation (body) ) @@ -1237,6 +1230,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Consumes form body let params = &[ ("integer", param_integer.map(|param| format!("{:?}", param))), @@ -1264,6 +1259,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1294,11 +1290,13 @@ impl Api for Client where match response.status().as_u16() { 400 => { + let (header, body) = response.into_parts(); Ok( TestEndpointParametersResponse::InvalidUsernameSupplied ) } 404 => { + let (header, body) = response.into_parts(); Ok( TestEndpointParametersResponse::UserNotFound ) @@ -1379,6 +1377,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Consumes form body let params = &[ ("enum_form_string", param_enum_form_string.map(|param| format!("{:?}", param))), @@ -1393,6 +1393,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1439,11 +1440,13 @@ impl Api for Client where match response.status().as_u16() { 400 => { + let (header, body) = response.into_parts(); Ok( TestEnumParametersResponse::InvalidRequest ) } 404 => { + let (header, body) = response.into_parts(); Ok( TestEnumParametersResponse::NotFound ) @@ -1502,6 +1505,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = serde_json::to_string(¶m_param).expect("impossible to fail to serialize"); @@ -1513,6 +1519,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1524,6 +1531,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( TestInlineAdditionalPropertiesResponse::SuccessfulOperation ) @@ -1583,6 +1591,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Consumes form body let params = &[ ("param", Some(param_param)), @@ -1598,6 +1608,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1609,6 +1620,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( TestJsonFormDataResponse::SuccessfulOperation ) @@ -1668,6 +1680,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1679,6 +1694,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( HyphenParamResponse::Success ) @@ -1740,6 +1756,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); @@ -1751,6 +1770,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1771,17 +1791,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(TestClassnameResponse::SuccessfulOperation (body) ) @@ -1808,7 +1830,7 @@ impl Api for Client where async fn add_pet( &self, - param_body: models::Pet, + param_body: swagger::OneOf2, context: &C) -> Result { let mut client_service = self.client_service.clone(); @@ -1840,9 +1862,31 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + match param_body { + swagger::OneOf2::::A(body) => { + let body : models::Pet = body.into(); + let param_body = body; + + // Consumes basic body + // Body parameter + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + *request.body_mut() = Body::from(body); + + let header = "application/json"; + request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { + Ok(h) => h, + Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) + }); + + }, + swagger::OneOf2::::B(body) => { + let body : models::Pet = body.into(); + let param_body = body; + // Consumes basic body // Body parameter let body = param_body.as_xml(); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); *request.body_mut() = Body::from(body); let header = "application/json"; @@ -1851,6 +1895,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + }, + } + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1881,6 +1928,7 @@ impl Api for Client where match response.status().as_u16() { 405 => { + let (header, body) = response.into_parts(); Ok( AddPetResponse::InvalidInput ) @@ -1941,6 +1989,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1971,11 +2022,24 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // Body has multiple variant schemas + let content_type = if let Some(content_type) = header.headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Err(ApiError(String::from("Missing content type header"))); + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + let body = match content_type { + Ok("application/xml") => { + // application/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -1983,12 +2047,33 @@ impl Api for Client where let body = serde_xml_rs::from_str::>(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + let body : models::FindPetsByStatus200ApplicationSlashXmlResponse = models::FindPetsByStatus200ApplicationSlashXmlResponse::from(body); + + swagger::OneOf2::::A(body) + }, + Ok("application/json") => { + // application/json + let body = str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::>(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + let body : models::FindPetsByStatus200ApplicationSlashJsonResponse = models::FindPetsByStatus200ApplicationSlashJsonResponse::from(body); + + swagger::OneOf2::::B(body) + }, + e => { + return Err(ApiError(format!("Unexpected content type: {:?}", e))); + } + }; + Ok(FindPetsByStatusResponse::SuccessfulOperation (body) ) } 400 => { + let (header, body) = response.into_parts(); Ok( FindPetsByStatusResponse::InvalidStatusValue ) @@ -2049,6 +2134,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2079,11 +2167,24 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // Body has multiple variant schemas + let content_type = if let Some(content_type) = header.headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Err(ApiError(String::from("Missing content type header"))); + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + let body = match content_type { + Ok("application/xml") => { + // application/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -2091,12 +2192,33 @@ impl Api for Client where let body = serde_xml_rs::from_str::>(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + let body : models::FindPetsByTags200ApplicationSlashXmlResponse = models::FindPetsByTags200ApplicationSlashXmlResponse::from(body); + + swagger::OneOf2::::A(body) + }, + Ok("application/json") => { + // application/json + let body = str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::>(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + let body : models::FindPetsByTags200ApplicationSlashJsonResponse = models::FindPetsByTags200ApplicationSlashJsonResponse::from(body); + + swagger::OneOf2::::B(body) + }, + e => { + return Err(ApiError(format!("Unexpected content type: {:?}", e))); + } + }; + Ok(FindPetsByTagsResponse::SuccessfulOperation (body) ) } 400 => { + let (header, body) = response.into_parts(); Ok( FindPetsByTagsResponse::InvalidTagValue ) @@ -2123,7 +2245,7 @@ impl Api for Client where async fn update_pet( &self, - param_body: models::Pet, + param_body: swagger::OneOf2, context: &C) -> Result { let mut client_service = self.client_service.clone(); @@ -2155,9 +2277,31 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + match param_body { + swagger::OneOf2::::A(body) => { + let body : models::Pet = body.into(); + let param_body = body; + + // Consumes basic body + // Body parameter + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + *request.body_mut() = Body::from(body); + + let header = "application/json"; + request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { + Ok(h) => h, + Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) + }); + + }, + swagger::OneOf2::::B(body) => { + let body : models::Pet = body.into(); + let param_body = body; + // Consumes basic body // Body parameter let body = param_body.as_xml(); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); *request.body_mut() = Body::from(body); let header = "application/json"; @@ -2166,6 +2310,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + }, + } + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2196,16 +2343,19 @@ impl Api for Client where match response.status().as_u16() { 400 => { + let (header, body) = response.into_parts(); Ok( UpdatePetResponse::InvalidIDSupplied ) } 404 => { + let (header, body) = response.into_parts(); Ok( UpdatePetResponse::PetNotFound ) } 405 => { + let (header, body) = response.into_parts(); Ok( UpdatePetResponse::ValidationException ) @@ -2266,6 +2416,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2314,6 +2467,7 @@ impl Api for Client where match response.status().as_u16() { 400 => { + let (header, body) = response.into_parts(); Ok( DeletePetResponse::InvalidPetValue ) @@ -2373,6 +2527,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2393,11 +2550,24 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // Body has multiple variant schemas + let content_type = if let Some(content_type) = header.headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Err(ApiError(String::from("Missing content type header"))); + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + let body = match content_type { + Ok("application/xml") => { + // application/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -2405,17 +2575,39 @@ impl Api for Client where let body = serde_xml_rs::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + let body : models::GetPetById200ApplicationSlashXmlResponse = models::GetPetById200ApplicationSlashXmlResponse::from(body); + + swagger::OneOf2::::A(body) + }, + Ok("application/json") => { + // application/json + let body = str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + let body : models::GetPetById200ApplicationSlashJsonResponse = models::GetPetById200ApplicationSlashJsonResponse::from(body); + + swagger::OneOf2::::B(body) + }, + e => { + return Err(ApiError(format!("Unexpected content type: {:?}", e))); + } + }; + Ok(GetPetByIdResponse::SuccessfulOperation (body) ) } 400 => { + let (header, body) = response.into_parts(); Ok( GetPetByIdResponse::InvalidIDSupplied ) } 404 => { + let (header, body) = response.into_parts(); Ok( GetPetByIdResponse::PetNotFound ) @@ -2477,6 +2669,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Consumes form body let params = &[ ("name", param_name), @@ -2492,6 +2686,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2522,6 +2717,7 @@ impl Api for Client where match response.status().as_u16() { 405 => { + let (header, body) = response.into_parts(); Ok( UpdatePetWithFormResponse::InvalidInput ) @@ -2583,6 +2779,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Consumes multipart/form body let (body_string, multipart_header) = { let mut multipart = Multipart::new(); @@ -2640,6 +2838,7 @@ impl Api for Client where }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2670,17 +2869,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(UploadFileResponse::SuccessfulOperation (body) ) @@ -2738,6 +2939,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2758,17 +2962,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::>(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(GetInventoryResponse::SuccessfulOperation (body) ) @@ -2827,16 +3033,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -2849,11 +3047,24 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // Body has multiple variant schemas + let content_type = if let Some(content_type) = header.headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Err(ApiError(String::from("Missing content type header"))); + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + let body = match content_type { + Ok("application/xml") => { + // application/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -2861,12 +3072,33 @@ impl Api for Client where let body = serde_xml_rs::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + let body : models::PlaceOrder200ApplicationSlashXmlResponse = models::PlaceOrder200ApplicationSlashXmlResponse::from(body); + + swagger::OneOf2::::A(body) + }, + Ok("application/json") => { + // application/json + let body = str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + let body : models::PlaceOrder200ApplicationSlashJsonResponse = models::PlaceOrder200ApplicationSlashJsonResponse::from(body); + + swagger::OneOf2::::B(body) + }, + e => { + return Err(ApiError(format!("Unexpected content type: {:?}", e))); + } + }; + Ok(PlaceOrderResponse::SuccessfulOperation (body) ) } 400 => { + let (header, body) = response.into_parts(); Ok( PlaceOrderResponse::InvalidOrder ) @@ -2926,6 +3158,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -2937,11 +3172,13 @@ impl Api for Client where match response.status().as_u16() { 400 => { + let (header, body) = response.into_parts(); Ok( DeleteOrderResponse::InvalidIDSupplied ) } 404 => { + let (header, body) = response.into_parts(); Ok( DeleteOrderResponse::OrderNotFound ) @@ -3001,6 +3238,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -3012,11 +3252,24 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // Body has multiple variant schemas + let content_type = if let Some(content_type) = header.headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Err(ApiError(String::from("Missing content type header"))); + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + let body = match content_type { + Ok("application/xml") => { + // application/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -3024,17 +3277,39 @@ impl Api for Client where let body = serde_xml_rs::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + let body : models::GetOrderById200ApplicationSlashXmlResponse = models::GetOrderById200ApplicationSlashXmlResponse::from(body); + + swagger::OneOf2::::A(body) + }, + Ok("application/json") => { + // application/json + let body = str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + let body : models::GetOrderById200ApplicationSlashJsonResponse = models::GetOrderById200ApplicationSlashJsonResponse::from(body); + + swagger::OneOf2::::B(body) + }, + e => { + return Err(ApiError(format!("Unexpected content type: {:?}", e))); + } + }; + Ok(GetOrderByIdResponse::SuccessfulOperation (body) ) } 400 => { + let (header, body) = response.into_parts(); Ok( GetOrderByIdResponse::InvalidIDSupplied ) } 404 => { + let (header, body) = response.into_parts(); Ok( GetOrderByIdResponse::OrderNotFound ) @@ -3093,16 +3368,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -3115,6 +3382,7 @@ impl Api for Client where match response.status().as_u16() { 0 => { + let (header, body) = response.into_parts(); Ok( CreateUserResponse::SuccessfulOperation ) @@ -3173,16 +3441,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -3195,6 +3455,7 @@ impl Api for Client where match response.status().as_u16() { 0 => { + let (header, body) = response.into_parts(); Ok( CreateUsersWithArrayInputResponse::SuccessfulOperation ) @@ -3253,16 +3514,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -3275,6 +3528,7 @@ impl Api for Client where match response.status().as_u16() { 0 => { + let (header, body) = response.into_parts(); Ok( CreateUsersWithListInputResponse::SuccessfulOperation ) @@ -3338,6 +3592,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -3349,7 +3606,8 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let response_x_rate_limit = match response.headers().get(HeaderName::from_static("x-rate-limit")) { + let (header, body) = response.into_parts(); + let response_x_rate_limit = match header.headers.get(HeaderName::from_static("x-rate-limit")) { Some(response_x_rate_limit) => { let response_x_rate_limit = response_x_rate_limit.clone(); let response_x_rate_limit = match TryInto::>::try_into(response_x_rate_limit) { @@ -3363,7 +3621,7 @@ impl Api for Client where None => None, }; - let response_x_expires_after = match response.headers().get(HeaderName::from_static("x-expires-after")) { + let response_x_expires_after = match header.headers.get(HeaderName::from_static("x-expires-after")) { Some(response_x_expires_after) => { let response_x_expires_after = response_x_expires_after.clone(); let response_x_expires_after = match TryInto::>>::try_into(response_x_expires_after) { @@ -3377,11 +3635,23 @@ impl Api for Client where None => None, }; - let body = response.into_body(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // Body has multiple variant schemas + let content_type = if let Some(content_type) = header.headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Err(ApiError(String::from("Missing content type header"))); + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + let body = match content_type { + Ok("application/xml") => { + // application/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -3389,6 +3659,26 @@ impl Api for Client where let body = serde_xml_rs::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + let body : models::LoginUser200ApplicationSlashXmlResponse = models::LoginUser200ApplicationSlashXmlResponse::from(body); + + swagger::OneOf2::::A(body) + }, + Ok("application/json") => { + // application/json + let body = str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + let body : models::LoginUser200ApplicationSlashJsonResponse = models::LoginUser200ApplicationSlashJsonResponse::from(body); + + swagger::OneOf2::::B(body) + }, + e => { + return Err(ApiError(format!("Unexpected content type: {:?}", e))); + } + }; + Ok(LoginUserResponse::SuccessfulOperation { @@ -3399,6 +3689,7 @@ impl Api for Client where ) } 400 => { + let (header, body) = response.into_parts(); Ok( LoginUserResponse::InvalidUsername ) @@ -3456,6 +3747,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -3467,6 +3761,7 @@ impl Api for Client where match response.status().as_u16() { 0 => { + let (header, body) = response.into_parts(); Ok( LogoutUserResponse::SuccessfulOperation ) @@ -3526,6 +3821,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -3537,11 +3835,13 @@ impl Api for Client where match response.status().as_u16() { 400 => { + let (header, body) = response.into_parts(); Ok( DeleteUserResponse::InvalidUsernameSupplied ) } 404 => { + let (header, body) = response.into_parts(); Ok( DeleteUserResponse::UserNotFound ) @@ -3601,6 +3901,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -3612,11 +3915,24 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // Body has multiple variant schemas + let content_type = if let Some(content_type) = header.headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Err(ApiError(String::from("Missing content type header"))); + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + let body = match content_type { + Ok("application/xml") => { + // application/xml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; // ToDo: this will move to swagger-rs and become a standard From conversion trait @@ -3624,17 +3940,39 @@ impl Api for Client where let body = serde_xml_rs::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + let body : models::GetUserByName200ApplicationSlashXmlResponse = models::GetUserByName200ApplicationSlashXmlResponse::from(body); + + swagger::OneOf2::::A(body) + }, + Ok("application/json") => { + // application/json + let body = str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; + let body = serde_json::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + + let body : models::GetUserByName200ApplicationSlashJsonResponse = models::GetUserByName200ApplicationSlashJsonResponse::from(body); + + swagger::OneOf2::::B(body) + }, + e => { + return Err(ApiError(format!("Unexpected content type: {:?}", e))); + } + }; + Ok(GetUserByNameResponse::SuccessfulOperation (body) ) } 400 => { + let (header, body) = response.into_parts(); Ok( GetUserByNameResponse::InvalidUsernameSupplied ) } 404 => { + let (header, body) = response.into_parts(); Ok( GetUserByNameResponse::UserNotFound ) @@ -3695,16 +4033,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -3717,11 +4047,13 @@ impl Api for Client where match response.status().as_u16() { 400 => { + let (header, body) = response.into_parts(); Ok( UpdateUserResponse::InvalidUserSupplied ) } 404 => { + let (header, body) = response.into_parts(); Ok( UpdateUserResponse::UserNotFound ) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs index b910c9ae6b23..a4935993a7b1 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs @@ -37,7 +37,7 @@ pub enum Call123exampleResponse { pub enum FakeOuterBooleanSerializeResponse { /// Output boolean OutputBoolean - (bool) + (models::OuterBoolean) } #[derive(Debug, PartialEq, Serialize, Deserialize)] @@ -51,14 +51,14 @@ pub enum FakeOuterCompositeSerializeResponse { pub enum FakeOuterNumberSerializeResponse { /// Output number OutputNumber - (f64) + (models::OuterNumber) } #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum FakeOuterStringSerializeResponse { /// Output string OutputString - (String) + (models::OuterString) } #[derive(Debug, PartialEq, Serialize, Deserialize)] @@ -136,7 +136,7 @@ pub enum AddPetResponse { pub enum FindPetsByStatusResponse { /// successful operation SuccessfulOperation - (Vec) + (swagger::OneOf2) , /// Invalid status value InvalidStatusValue @@ -147,7 +147,7 @@ pub enum FindPetsByStatusResponse { pub enum FindPetsByTagsResponse { /// successful operation SuccessfulOperation - (Vec) + (swagger::OneOf2) , /// Invalid tag value InvalidTagValue @@ -177,7 +177,7 @@ pub enum DeletePetResponse { pub enum GetPetByIdResponse { /// successful operation SuccessfulOperation - (models::Pet) + (swagger::OneOf2) , /// Invalid ID supplied InvalidIDSupplied @@ -211,7 +211,7 @@ pub enum GetInventoryResponse { pub enum PlaceOrderResponse { /// successful operation SuccessfulOperation - (models::Order) + (swagger::OneOf2) , /// Invalid Order InvalidOrder @@ -232,7 +232,7 @@ pub enum DeleteOrderResponse { pub enum GetOrderByIdResponse { /// successful operation SuccessfulOperation - (models::Order) + (swagger::OneOf2) , /// Invalid ID supplied InvalidIDSupplied @@ -265,7 +265,7 @@ pub enum LoginUserResponse { /// successful operation SuccessfulOperation { - body: String, + body: swagger::OneOf2, x_rate_limit: Option< i32 @@ -302,7 +302,7 @@ pub enum DeleteUserResponse { pub enum GetUserByNameResponse { /// successful operation SuccessfulOperation - (models::User) + (swagger::OneOf2) , /// Invalid username supplied InvalidUsernameSupplied @@ -433,7 +433,7 @@ pub trait Api { /// Add a new pet to the store async fn add_pet( &self, - body: models::Pet, + body: swagger::OneOf2, context: &C) -> Result; /// Finds Pets by status @@ -451,7 +451,7 @@ pub trait Api { /// Update an existing pet async fn update_pet( &self, - body: models::Pet, + body: swagger::OneOf2, context: &C) -> Result; /// Deletes a pet @@ -670,7 +670,7 @@ pub trait ApiNoContext { /// Add a new pet to the store async fn add_pet( &self, - body: models::Pet, + body: swagger::OneOf2, ) -> Result; /// Finds Pets by status @@ -688,7 +688,7 @@ pub trait ApiNoContext { /// Update an existing pet async fn update_pet( &self, - body: models::Pet, + body: swagger::OneOf2, ) -> Result; /// Deletes a pet @@ -981,7 +981,7 @@ impl + Send + Sync, C: Clone + Send + Sync> ApiNoContext for Contex /// Add a new pet to the store async fn add_pet( &self, - body: models::Pet, + body: swagger::OneOf2, ) -> Result { let context = self.context().clone(); @@ -1011,7 +1011,7 @@ impl + Send + Sync, C: Clone + Send + Sync> ApiNoContext for Contex /// Update an existing pet async fn update_pet( &self, - body: models::Pet, + body: swagger::OneOf2, ) -> Result { let context = self.context().clone(); diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs index ff6ade7e2b29..da3f1444aa10 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs @@ -6,6 +6,296 @@ use crate::models; #[cfg(any(feature = "client", feature = "server"))] use crate::header; +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AddPetApplicationSlashJsonRequest(Pet); + +impl std::convert::From for AddPetApplicationSlashJsonRequest { + fn from(x: Pet) -> Self { + AddPetApplicationSlashJsonRequest(x) + } +} + +impl std::convert::From for Pet { + fn from(x: AddPetApplicationSlashJsonRequest) -> Self { + x.0 + } +} + +impl std::ops::Deref for AddPetApplicationSlashJsonRequest { + type Target = Pet; + fn deref(&self) -> &Pet { + &self.0 + } +} + +impl std::ops::DerefMut for AddPetApplicationSlashJsonRequest { + fn deref_mut(&mut self) -> &mut Pet { + &mut self.0 + } +} + +/// Converts the AddPetApplicationSlashJsonRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for AddPetApplicationSlashJsonRequest { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AddPetApplicationSlashJsonRequest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for AddPetApplicationSlashJsonRequest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(AddPetApplicationSlashJsonRequest(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to AddPetApplicationSlashJsonRequest: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for AddPetApplicationSlashJsonRequest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AddPetApplicationSlashJsonRequest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AddPetApplicationSlashJsonRequest - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl AddPetApplicationSlashJsonRequest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AddPetApplicationSlashXmlRequest(Pet); + +impl std::convert::From for AddPetApplicationSlashXmlRequest { + fn from(x: Pet) -> Self { + AddPetApplicationSlashXmlRequest(x) + } +} + +impl std::convert::From for Pet { + fn from(x: AddPetApplicationSlashXmlRequest) -> Self { + x.0 + } +} + +impl std::ops::Deref for AddPetApplicationSlashXmlRequest { + type Target = Pet; + fn deref(&self) -> &Pet { + &self.0 + } +} + +impl std::ops::DerefMut for AddPetApplicationSlashXmlRequest { + fn deref_mut(&mut self) -> &mut Pet { + &mut self.0 + } +} + +/// Converts the AddPetApplicationSlashXmlRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for AddPetApplicationSlashXmlRequest { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AddPetApplicationSlashXmlRequest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for AddPetApplicationSlashXmlRequest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(AddPetApplicationSlashXmlRequest(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to AddPetApplicationSlashXmlRequest: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for AddPetApplicationSlashXmlRequest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AddPetApplicationSlashXmlRequest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AddPetApplicationSlashXmlRequest - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl AddPetApplicationSlashXmlRequest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct AdditionalPropertiesClass { @@ -3921,73 +4211,124 @@ impl EnumTestEnumString { } } -/// Enumeration of values. -/// Since this enum's variants do not hold data, we can easily define them as `#[repr(C)]` -/// which helps with FFI. -#[allow(non_camel_case_types)] -#[repr(C)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] -pub enum FindPetsByStatusStatusParameterInner { - #[serde(rename = "available")] - Available, - #[serde(rename = "pending")] - Pending, - #[serde(rename = "sold")] - Sold, +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct FindPetsByStatus200ApplicationSlashJsonResponse( + Vec +); + +impl std::convert::From> for FindPetsByStatus200ApplicationSlashJsonResponse { + fn from(x: Vec) -> Self { + FindPetsByStatus200ApplicationSlashJsonResponse(x) + } } -impl std::fmt::Display for FindPetsByStatusStatusParameterInner { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match *self { - FindPetsByStatusStatusParameterInner::Available => write!(f, "available"), - FindPetsByStatusStatusParameterInner::Pending => write!(f, "pending"), - FindPetsByStatusStatusParameterInner::Sold => write!(f, "sold"), - } +impl std::convert::From for Vec { + fn from(x: FindPetsByStatus200ApplicationSlashJsonResponse) -> Self { + x.0 } } -impl std::str::FromStr for FindPetsByStatusStatusParameterInner { - type Err = String; +impl std::iter::FromIterator for FindPetsByStatus200ApplicationSlashJsonResponse { + fn from_iter>(u: U) -> Self { + FindPetsByStatus200ApplicationSlashJsonResponse(Vec::::from_iter(u)) + } +} + +impl std::iter::IntoIterator for FindPetsByStatus200ApplicationSlashJsonResponse { + type Item = Pet; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a FindPetsByStatus200ApplicationSlashJsonResponse { + type Item = &'a Pet; + type IntoIter = std::slice::Iter<'a, Pet>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a mut FindPetsByStatus200ApplicationSlashJsonResponse { + type Item = &'a mut Pet; + type IntoIter = std::slice::IterMut<'a, Pet>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } +} + +impl std::ops::Deref for FindPetsByStatus200ApplicationSlashJsonResponse { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for FindPetsByStatus200ApplicationSlashJsonResponse { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Converts the FindPetsByStatus200ApplicationSlashJsonResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for FindPetsByStatus200ApplicationSlashJsonResponse { + fn to_string(&self) -> String { + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a FindPetsByStatus200ApplicationSlashJsonResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for FindPetsByStatus200ApplicationSlashJsonResponse { + type Err = ::Err; fn from_str(s: &str) -> std::result::Result { - match s { - "available" => std::result::Result::Ok(FindPetsByStatusStatusParameterInner::Available), - "pending" => std::result::Result::Ok(FindPetsByStatusStatusParameterInner::Pending), - "sold" => std::result::Result::Ok(FindPetsByStatusStatusParameterInner::Sold), - _ => std::result::Result::Err(format!("Value not valid: {}", s)), + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); } + std::result::Result::Ok(FindPetsByStatus200ApplicationSlashJsonResponse(items)) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for FindPetsByStatusStatusParameterInner - value: {} is invalid {}", + format!("Invalid header value for FindPetsByStatus200ApplicationSlashJsonResponse - value: {} is invalid {}", hdr_value, e)) } } } #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into FindPetsByStatusStatusParameterInner - {}", + format!("Unable to convert header value '{}' into FindPetsByStatus200ApplicationSlashJsonResponse - {}", value, err)) } }, @@ -3999,10 +4340,10 @@ impl std::convert::TryFrom for header::IntoHeaderVal } #[cfg(feature = "server")] -impl std::convert::TryFrom>> for hyper::header::HeaderValue { +impl std::convert::TryFrom>> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { hdr_value.to_string() }).collect(); @@ -4016,21 +4357,21 @@ impl std::convert::TryFrom for header::IntoHeaderValue> { +impl std::convert::TryFrom for header::IntoHeaderValue> { type Error = String; fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { match hdr_values.to_str() { std::result::Result::Ok(hdr_values) => { - let hdr_values : std::vec::Vec = hdr_values + let hdr_values : std::vec::Vec = hdr_values .split(',') .filter_map(|hdr_value| match hdr_value.trim() { "" => std::option::Option::None, hdr_value => std::option::Option::Some({ - match ::from_str(hdr_value) { + match ::from_str(hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into FindPetsByStatusStatusParameterInner - {}", + format!("Unable to convert header value '{}' into FindPetsByStatus200ApplicationSlashJsonResponse - {}", hdr_value, err)) } }) @@ -4044,7 +4385,7 @@ impl std::convert::TryFrom for header::IntoHeaderVal } } -impl FindPetsByStatusStatusParameterInner { +impl FindPetsByStatus200ApplicationSlashJsonResponse { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] @@ -4053,163 +4394,844 @@ impl FindPetsByStatusStatusParameterInner { } } -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct FormatTest { - #[serde(rename = "integer")] - #[validate( - range(min = 10, max = 100), - )] - #[serde(skip_serializing_if="Option::is_none")] - pub integer: Option, - - #[serde(rename = "int32")] - #[validate( - range(min = 20, max = 200), - )] - #[serde(skip_serializing_if="Option::is_none")] - pub int32: Option, - - #[serde(rename = "int64")] - #[serde(skip_serializing_if="Option::is_none")] - pub int64: Option, - - #[serde(rename = "number")] - #[validate( - range(min = 32.1, max = 543.2), - )] - pub number: f64, - - #[serde(rename = "float")] - #[validate( - range(min = 54.3, max = 987.6), - )] - #[serde(skip_serializing_if="Option::is_none")] - pub float: Option, +pub struct FindPetsByStatus200ApplicationSlashXmlResponse( + Vec +); - #[serde(rename = "double")] - #[validate( - range(min = 67.8, max = 123.4), - )] - #[serde(skip_serializing_if="Option::is_none")] - pub double: Option, +impl std::convert::From> for FindPetsByStatus200ApplicationSlashXmlResponse { + fn from(x: Vec) -> Self { + FindPetsByStatus200ApplicationSlashXmlResponse(x) + } +} - #[serde(rename = "string")] - #[validate( - regex = "RE_FORMATTEST_STRING", - )] - #[serde(skip_serializing_if="Option::is_none")] - pub string: Option, +impl std::convert::From for Vec { + fn from(x: FindPetsByStatus200ApplicationSlashXmlResponse) -> Self { + x.0 + } +} - #[serde(rename = "byte")] - #[validate( - custom ="validate_byte_formattest_byte" - )] - pub byte: swagger::ByteArray, +impl std::iter::FromIterator for FindPetsByStatus200ApplicationSlashXmlResponse { + fn from_iter>(u: U) -> Self { + FindPetsByStatus200ApplicationSlashXmlResponse(Vec::::from_iter(u)) + } +} - #[serde(rename = "binary")] - #[serde(skip_serializing_if="Option::is_none")] - pub binary: Option, +impl std::iter::IntoIterator for FindPetsByStatus200ApplicationSlashXmlResponse { + type Item = Pet; + type IntoIter = std::vec::IntoIter; - #[serde(rename = "date")] - pub date: chrono::naive::NaiveDate, + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} - #[serde(rename = "dateTime")] - #[serde(skip_serializing_if="Option::is_none")] - pub date_time: Option>, +impl<'a> std::iter::IntoIterator for &'a FindPetsByStatus200ApplicationSlashXmlResponse { + type Item = &'a Pet; + type IntoIter = std::slice::Iter<'a, Pet>; - #[serde(rename = "uuid")] - #[serde(skip_serializing_if="Option::is_none")] - pub uuid: Option, + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} - #[serde(rename = "password")] - #[validate( - length(min = 10, max = 64), - )] - pub password: String, +impl<'a> std::iter::IntoIterator for &'a mut FindPetsByStatus200ApplicationSlashXmlResponse { + type Item = &'a mut Pet; + type IntoIter = std::slice::IterMut<'a, Pet>; + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } } -lazy_static::lazy_static! { - static ref RE_FORMATTEST_STRING: regex::Regex = regex::Regex::new(r"/[a-z]/i").unwrap(); -} -lazy_static::lazy_static! { - static ref RE_FORMATTEST_BYTE: regex::bytes::Regex = regex::bytes::Regex::new(r"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$").unwrap(); -} -fn validate_byte_formattest_byte( - b: &swagger::ByteArray -) -> Result<(), validator::ValidationError> { - if !RE_FORMATTEST_BYTE.is_match(b) { - return Err(validator::ValidationError::new("Character not allowed")); +impl std::ops::Deref for FindPetsByStatus200ApplicationSlashXmlResponse { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 } - Ok(()) } -impl FormatTest { - #[allow(clippy::new_without_default)] - pub fn new(number: f64, byte: swagger::ByteArray, date: chrono::naive::NaiveDate, password: String, ) -> FormatTest { - FormatTest { - integer: None, - int32: None, - int64: None, - number, - float: None, - double: None, - string: None, - byte, - binary: None, - date, - date_time: None, - uuid: None, - password, - } +impl std::ops::DerefMut for FindPetsByStatus200ApplicationSlashXmlResponse { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 } } -/// Converts the FormatTest value to the Query Parameters representation (style=form, explode=false) +/// Converts the FindPetsByStatus200ApplicationSlashXmlResponse value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for FormatTest { +impl std::string::ToString for FindPetsByStatus200ApplicationSlashXmlResponse { fn to_string(&self) -> String { - let params: Vec> = vec![ - - self.integer.as_ref().map(|integer| { - [ - "integer".to_string(), - integer.to_string(), - ].join(",") - }), + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} +/// Converts Query Parameters representation (style=form, explode=false) to a FindPetsByStatus200ApplicationSlashXmlResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for FindPetsByStatus200ApplicationSlashXmlResponse { + type Err = ::Err; - self.int32.as_ref().map(|int32| { - [ - "int32".to_string(), - int32.to_string(), - ].join(",") - }), + fn from_str(s: &str) -> std::result::Result { + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); + } + std::result::Result::Ok(FindPetsByStatus200ApplicationSlashXmlResponse(items)) + } +} - self.int64.as_ref().map(|int64| { - [ - "int64".to_string(), - int64.to_string(), - ].join(",") - }), +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; - Some("number".to_string()), - Some(self.number.to_string()), + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for FindPetsByStatus200ApplicationSlashXmlResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; - self.float.as_ref().map(|float| { - [ - "float".to_string(), - float.to_string(), - ].join(",") - }), + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FindPetsByStatus200ApplicationSlashXmlResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; - self.double.as_ref().map(|double| { + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FindPetsByStatus200ApplicationSlashXmlResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl FindPetsByStatus200ApplicationSlashXmlResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] +pub enum FindPetsByStatusStatusParameterInner { + #[serde(rename = "available")] + Available, + #[serde(rename = "pending")] + Pending, + #[serde(rename = "sold")] + Sold, +} + +impl std::fmt::Display for FindPetsByStatusStatusParameterInner { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + FindPetsByStatusStatusParameterInner::Available => write!(f, "available"), + FindPetsByStatusStatusParameterInner::Pending => write!(f, "pending"), + FindPetsByStatusStatusParameterInner::Sold => write!(f, "sold"), + } + } +} + +impl std::str::FromStr for FindPetsByStatusStatusParameterInner { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { + "available" => std::result::Result::Ok(FindPetsByStatusStatusParameterInner::Available), + "pending" => std::result::Result::Ok(FindPetsByStatusStatusParameterInner::Pending), + "sold" => std::result::Result::Ok(FindPetsByStatusStatusParameterInner::Sold), + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for FindPetsByStatusStatusParameterInner - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FindPetsByStatusStatusParameterInner - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FindPetsByStatusStatusParameterInner - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl FindPetsByStatusStatusParameterInner { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct FindPetsByTags200ApplicationSlashJsonResponse( + Vec +); + +impl std::convert::From> for FindPetsByTags200ApplicationSlashJsonResponse { + fn from(x: Vec) -> Self { + FindPetsByTags200ApplicationSlashJsonResponse(x) + } +} + +impl std::convert::From for Vec { + fn from(x: FindPetsByTags200ApplicationSlashJsonResponse) -> Self { + x.0 + } +} + +impl std::iter::FromIterator for FindPetsByTags200ApplicationSlashJsonResponse { + fn from_iter>(u: U) -> Self { + FindPetsByTags200ApplicationSlashJsonResponse(Vec::::from_iter(u)) + } +} + +impl std::iter::IntoIterator for FindPetsByTags200ApplicationSlashJsonResponse { + type Item = Pet; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a FindPetsByTags200ApplicationSlashJsonResponse { + type Item = &'a Pet; + type IntoIter = std::slice::Iter<'a, Pet>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a mut FindPetsByTags200ApplicationSlashJsonResponse { + type Item = &'a mut Pet; + type IntoIter = std::slice::IterMut<'a, Pet>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } +} + +impl std::ops::Deref for FindPetsByTags200ApplicationSlashJsonResponse { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for FindPetsByTags200ApplicationSlashJsonResponse { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Converts the FindPetsByTags200ApplicationSlashJsonResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for FindPetsByTags200ApplicationSlashJsonResponse { + fn to_string(&self) -> String { + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a FindPetsByTags200ApplicationSlashJsonResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for FindPetsByTags200ApplicationSlashJsonResponse { + type Err = ::Err; + + fn from_str(s: &str) -> std::result::Result { + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); + } + std::result::Result::Ok(FindPetsByTags200ApplicationSlashJsonResponse(items)) + } +} + + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for FindPetsByTags200ApplicationSlashJsonResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FindPetsByTags200ApplicationSlashJsonResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FindPetsByTags200ApplicationSlashJsonResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl FindPetsByTags200ApplicationSlashJsonResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct FindPetsByTags200ApplicationSlashXmlResponse( + Vec +); + +impl std::convert::From> for FindPetsByTags200ApplicationSlashXmlResponse { + fn from(x: Vec) -> Self { + FindPetsByTags200ApplicationSlashXmlResponse(x) + } +} + +impl std::convert::From for Vec { + fn from(x: FindPetsByTags200ApplicationSlashXmlResponse) -> Self { + x.0 + } +} + +impl std::iter::FromIterator for FindPetsByTags200ApplicationSlashXmlResponse { + fn from_iter>(u: U) -> Self { + FindPetsByTags200ApplicationSlashXmlResponse(Vec::::from_iter(u)) + } +} + +impl std::iter::IntoIterator for FindPetsByTags200ApplicationSlashXmlResponse { + type Item = Pet; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a FindPetsByTags200ApplicationSlashXmlResponse { + type Item = &'a Pet; + type IntoIter = std::slice::Iter<'a, Pet>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a mut FindPetsByTags200ApplicationSlashXmlResponse { + type Item = &'a mut Pet; + type IntoIter = std::slice::IterMut<'a, Pet>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } +} + +impl std::ops::Deref for FindPetsByTags200ApplicationSlashXmlResponse { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for FindPetsByTags200ApplicationSlashXmlResponse { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Converts the FindPetsByTags200ApplicationSlashXmlResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for FindPetsByTags200ApplicationSlashXmlResponse { + fn to_string(&self) -> String { + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a FindPetsByTags200ApplicationSlashXmlResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for FindPetsByTags200ApplicationSlashXmlResponse { + type Err = ::Err; + + fn from_str(s: &str) -> std::result::Result { + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); + } + std::result::Result::Ok(FindPetsByTags200ApplicationSlashXmlResponse(items)) + } +} + + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for FindPetsByTags200ApplicationSlashXmlResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FindPetsByTags200ApplicationSlashXmlResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FindPetsByTags200ApplicationSlashXmlResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl FindPetsByTags200ApplicationSlashXmlResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct FormatTest { + #[serde(rename = "integer")] + #[validate( + range(min = 10, max = 100), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub integer: Option, + + #[serde(rename = "int32")] + #[validate( + range(min = 20, max = 200), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub int32: Option, + + #[serde(rename = "int64")] + #[serde(skip_serializing_if="Option::is_none")] + pub int64: Option, + + #[serde(rename = "number")] + #[validate( + range(min = 32.1, max = 543.2), + )] + pub number: f64, + + #[serde(rename = "float")] + #[validate( + range(min = 54.3, max = 987.6), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub float: Option, + + #[serde(rename = "double")] + #[validate( + range(min = 67.8, max = 123.4), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub double: Option, + + #[serde(rename = "string")] + #[validate( + regex = "RE_FORMATTEST_STRING", + )] + #[serde(skip_serializing_if="Option::is_none")] + pub string: Option, + + #[serde(rename = "byte")] + #[validate( + custom ="validate_byte_formattest_byte" + )] + pub byte: swagger::ByteArray, + + #[serde(rename = "binary")] + #[serde(skip_serializing_if="Option::is_none")] + pub binary: Option, + + #[serde(rename = "date")] + pub date: chrono::naive::NaiveDate, + + #[serde(rename = "dateTime")] + #[serde(skip_serializing_if="Option::is_none")] + pub date_time: Option>, + + #[serde(rename = "uuid")] + #[serde(skip_serializing_if="Option::is_none")] + pub uuid: Option, + + #[serde(rename = "password")] + #[validate( + length(min = 10, max = 64), + )] + pub password: String, + +} + +lazy_static::lazy_static! { + static ref RE_FORMATTEST_STRING: regex::Regex = regex::Regex::new(r"/[a-z]/i").unwrap(); +} +lazy_static::lazy_static! { + static ref RE_FORMATTEST_BYTE: regex::bytes::Regex = regex::bytes::Regex::new(r"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$").unwrap(); +} +fn validate_byte_formattest_byte( + b: &swagger::ByteArray +) -> Result<(), validator::ValidationError> { + if !RE_FORMATTEST_BYTE.is_match(b) { + return Err(validator::ValidationError::new("Character not allowed")); + } + Ok(()) +} + +impl FormatTest { + #[allow(clippy::new_without_default)] + pub fn new(number: f64, byte: swagger::ByteArray, date: chrono::naive::NaiveDate, password: String, ) -> FormatTest { + FormatTest { + integer: None, + int32: None, + int64: None, + number, + float: None, + double: None, + string: None, + byte, + binary: None, + date, + date_time: None, + uuid: None, + password, + } + } +} + +/// Converts the FormatTest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for FormatTest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.integer.as_ref().map(|integer| { + [ + "integer".to_string(), + integer.to_string(), + ].join(",") + }), + + + self.int32.as_ref().map(|int32| { + [ + "int32".to_string(), + int32.to_string(), + ].join(",") + }), + + + self.int64.as_ref().map(|int64| { + [ + "int64".to_string(), + int64.to_string(), + ].join(",") + }), + + + Some("number".to_string()), + Some(self.number.to_string()), + + + self.float.as_ref().map(|float| { + [ + "float".to_string(), + float.to_string(), + ].join(",") + }), + + + self.double.as_ref().map(|double| { [ "double".to_string(), double.to_string(), @@ -4217,155 +5239,1025 @@ impl std::string::ToString for FormatTest { }), - self.string.as_ref().map(|string| { - [ - "string".to_string(), - string.to_string(), - ].join(",") - }), + self.string.as_ref().map(|string| { + [ + "string".to_string(), + string.to_string(), + ].join(",") + }), + + // Skipping byte in query parameter serialization + // Skipping byte in query parameter serialization + + // Skipping binary in query parameter serialization + // Skipping binary in query parameter serialization + + // Skipping date in query parameter serialization + + // Skipping dateTime in query parameter serialization + + // Skipping uuid in query parameter serialization + + + Some("password".to_string()), + Some(self.password.to_string()), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a FormatTest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for FormatTest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub integer: Vec, + pub int32: Vec, + pub int64: Vec, + pub number: Vec, + pub float: Vec, + pub double: Vec, + pub string: Vec, + pub byte: Vec, + pub binary: Vec, + pub date: Vec, + pub date_time: Vec>, + pub uuid: Vec, + pub password: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing FormatTest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "integer" => intermediate_rep.integer.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "int32" => intermediate_rep.int32.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "int64" => intermediate_rep.int64.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "number" => intermediate_rep.number.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "float" => intermediate_rep.float.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "double" => intermediate_rep.double.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "string" => intermediate_rep.string.push(::from_str(val).map_err(|x| x.to_string())?), + "byte" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), + "binary" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), + #[allow(clippy::redundant_clone)] + "date" => intermediate_rep.date.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "uuid" => intermediate_rep.uuid.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing FormatTest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(FormatTest { + integer: intermediate_rep.integer.into_iter().next(), + int32: intermediate_rep.int32.into_iter().next(), + int64: intermediate_rep.int64.into_iter().next(), + number: intermediate_rep.number.into_iter().next().ok_or_else(|| "number missing in FormatTest".to_string())?, + float: intermediate_rep.float.into_iter().next(), + double: intermediate_rep.double.into_iter().next(), + string: intermediate_rep.string.into_iter().next(), + byte: intermediate_rep.byte.into_iter().next().ok_or_else(|| "byte missing in FormatTest".to_string())?, + binary: intermediate_rep.binary.into_iter().next(), + date: intermediate_rep.date.into_iter().next().ok_or_else(|| "date missing in FormatTest".to_string())?, + date_time: intermediate_rep.date_time.into_iter().next(), + uuid: intermediate_rep.uuid.into_iter().next(), + password: intermediate_rep.password.into_iter().next().ok_or_else(|| "password missing in FormatTest".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for FormatTest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FormatTest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FormatTest - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl FormatTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct GetOrderById200ApplicationSlashJsonResponse(Order); + +impl std::convert::From for GetOrderById200ApplicationSlashJsonResponse { + fn from(x: Order) -> Self { + GetOrderById200ApplicationSlashJsonResponse(x) + } +} + +impl std::convert::From for Order { + fn from(x: GetOrderById200ApplicationSlashJsonResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for GetOrderById200ApplicationSlashJsonResponse { + type Target = Order; + fn deref(&self) -> &Order { + &self.0 + } +} + +impl std::ops::DerefMut for GetOrderById200ApplicationSlashJsonResponse { + fn deref_mut(&mut self) -> &mut Order { + &mut self.0 + } +} + +/// Converts the GetOrderById200ApplicationSlashJsonResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for GetOrderById200ApplicationSlashJsonResponse { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a GetOrderById200ApplicationSlashJsonResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for GetOrderById200ApplicationSlashJsonResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(GetOrderById200ApplicationSlashJsonResponse(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to GetOrderById200ApplicationSlashJsonResponse: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for GetOrderById200ApplicationSlashJsonResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetOrderById200ApplicationSlashJsonResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetOrderById200ApplicationSlashJsonResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl GetOrderById200ApplicationSlashJsonResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct GetOrderById200ApplicationSlashXmlResponse(Order); + +impl std::convert::From for GetOrderById200ApplicationSlashXmlResponse { + fn from(x: Order) -> Self { + GetOrderById200ApplicationSlashXmlResponse(x) + } +} + +impl std::convert::From for Order { + fn from(x: GetOrderById200ApplicationSlashXmlResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for GetOrderById200ApplicationSlashXmlResponse { + type Target = Order; + fn deref(&self) -> &Order { + &self.0 + } +} + +impl std::ops::DerefMut for GetOrderById200ApplicationSlashXmlResponse { + fn deref_mut(&mut self) -> &mut Order { + &mut self.0 + } +} + +/// Converts the GetOrderById200ApplicationSlashXmlResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for GetOrderById200ApplicationSlashXmlResponse { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a GetOrderById200ApplicationSlashXmlResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for GetOrderById200ApplicationSlashXmlResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(GetOrderById200ApplicationSlashXmlResponse(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to GetOrderById200ApplicationSlashXmlResponse: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for GetOrderById200ApplicationSlashXmlResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetOrderById200ApplicationSlashXmlResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetOrderById200ApplicationSlashXmlResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl GetOrderById200ApplicationSlashXmlResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct GetPetById200ApplicationSlashJsonResponse(Pet); + +impl std::convert::From for GetPetById200ApplicationSlashJsonResponse { + fn from(x: Pet) -> Self { + GetPetById200ApplicationSlashJsonResponse(x) + } +} + +impl std::convert::From for Pet { + fn from(x: GetPetById200ApplicationSlashJsonResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for GetPetById200ApplicationSlashJsonResponse { + type Target = Pet; + fn deref(&self) -> &Pet { + &self.0 + } +} + +impl std::ops::DerefMut for GetPetById200ApplicationSlashJsonResponse { + fn deref_mut(&mut self) -> &mut Pet { + &mut self.0 + } +} + +/// Converts the GetPetById200ApplicationSlashJsonResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for GetPetById200ApplicationSlashJsonResponse { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a GetPetById200ApplicationSlashJsonResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for GetPetById200ApplicationSlashJsonResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(GetPetById200ApplicationSlashJsonResponse(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to GetPetById200ApplicationSlashJsonResponse: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for GetPetById200ApplicationSlashJsonResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetPetById200ApplicationSlashJsonResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetPetById200ApplicationSlashJsonResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl GetPetById200ApplicationSlashJsonResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct GetPetById200ApplicationSlashXmlResponse(Pet); + +impl std::convert::From for GetPetById200ApplicationSlashXmlResponse { + fn from(x: Pet) -> Self { + GetPetById200ApplicationSlashXmlResponse(x) + } +} + +impl std::convert::From for Pet { + fn from(x: GetPetById200ApplicationSlashXmlResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for GetPetById200ApplicationSlashXmlResponse { + type Target = Pet; + fn deref(&self) -> &Pet { + &self.0 + } +} + +impl std::ops::DerefMut for GetPetById200ApplicationSlashXmlResponse { + fn deref_mut(&mut self) -> &mut Pet { + &mut self.0 + } +} + +/// Converts the GetPetById200ApplicationSlashXmlResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for GetPetById200ApplicationSlashXmlResponse { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a GetPetById200ApplicationSlashXmlResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for GetPetById200ApplicationSlashXmlResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(GetPetById200ApplicationSlashXmlResponse(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to GetPetById200ApplicationSlashXmlResponse: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for GetPetById200ApplicationSlashXmlResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetPetById200ApplicationSlashXmlResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); - // Skipping byte in query parameter serialization - // Skipping byte in query parameter serialization + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} - // Skipping binary in query parameter serialization - // Skipping binary in query parameter serialization +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; - // Skipping date in query parameter serialization + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetPetById200ApplicationSlashXmlResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; - // Skipping dateTime in query parameter serialization + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} - // Skipping uuid in query parameter serialization +impl GetPetById200ApplicationSlashXmlResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct GetUserByName200ApplicationSlashJsonResponse(User); - Some("password".to_string()), - Some(self.password.to_string()), +impl std::convert::From for GetUserByName200ApplicationSlashJsonResponse { + fn from(x: User) -> Self { + GetUserByName200ApplicationSlashJsonResponse(x) + } +} - ]; +impl std::convert::From for User { + fn from(x: GetUserByName200ApplicationSlashJsonResponse) -> Self { + x.0 + } +} - params.into_iter().flatten().collect::>().join(",") +impl std::ops::Deref for GetUserByName200ApplicationSlashJsonResponse { + type Target = User; + fn deref(&self) -> &User { + &self.0 } } -/// Converts Query Parameters representation (style=form, explode=false) to a FormatTest value +impl std::ops::DerefMut for GetUserByName200ApplicationSlashJsonResponse { + fn deref_mut(&mut self) -> &mut User { + &mut self.0 + } +} + +/// Converts the GetUserByName200ApplicationSlashJsonResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for GetUserByName200ApplicationSlashJsonResponse { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a GetUserByName200ApplicationSlashJsonResponse value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for FormatTest { +impl ::std::str::FromStr for GetUserByName200ApplicationSlashJsonResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { - /// An intermediate representation of the struct to use for parsing. - #[derive(Default)] - #[allow(dead_code)] - struct IntermediateRep { - pub integer: Vec, - pub int32: Vec, - pub int64: Vec, - pub number: Vec, - pub float: Vec, - pub double: Vec, - pub string: Vec, - pub byte: Vec, - pub binary: Vec, - pub date: Vec, - pub date_time: Vec>, - pub uuid: Vec, - pub password: Vec, + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(GetUserByName200ApplicationSlashJsonResponse(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to GetUserByName200ApplicationSlashJsonResponse: {:?}", s, e)), } + } +} - let mut intermediate_rep = IntermediateRep::default(); +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - // Parse into intermediate representation - let mut string_iter = s.split(','); - let mut key_result = string_iter.next(); +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing FormatTest".to_string()) - }; + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for GetUserByName200ApplicationSlashJsonResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} - if let Some(key) = key_result { - #[allow(clippy::match_single_binding)] - match key { - #[allow(clippy::redundant_clone)] - "integer" => intermediate_rep.integer.push(::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "int32" => intermediate_rep.int32.push(::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "int64" => intermediate_rep.int64.push(::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "number" => intermediate_rep.number.push(::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "float" => intermediate_rep.float.push(::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "double" => intermediate_rep.double.push(::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "string" => intermediate_rep.string.push(::from_str(val).map_err(|x| x.to_string())?), - "byte" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), - "binary" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), - #[allow(clippy::redundant_clone)] - "date" => intermediate_rep.date.push(::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "uuid" => intermediate_rep.uuid.push(::from_str(val).map_err(|x| x.to_string())?), - #[allow(clippy::redundant_clone)] - "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), - _ => return std::result::Result::Err("Unexpected key while parsing FormatTest".to_string()) - } - } +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; - // Get the next key - key_result = string_iter.next(); + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetUserByName200ApplicationSlashJsonResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) } + } +} - // Use the intermediate representation to return the struct - std::result::Result::Ok(FormatTest { - integer: intermediate_rep.integer.into_iter().next(), - int32: intermediate_rep.int32.into_iter().next(), - int64: intermediate_rep.int64.into_iter().next(), - number: intermediate_rep.number.into_iter().next().ok_or_else(|| "number missing in FormatTest".to_string())?, - float: intermediate_rep.float.into_iter().next(), - double: intermediate_rep.double.into_iter().next(), - string: intermediate_rep.string.into_iter().next(), - byte: intermediate_rep.byte.into_iter().next().ok_or_else(|| "byte missing in FormatTest".to_string())?, - binary: intermediate_rep.binary.into_iter().next(), - date: intermediate_rep.date.into_iter().next().ok_or_else(|| "date missing in FormatTest".to_string())?, - date_time: intermediate_rep.date_time.into_iter().next(), - uuid: intermediate_rep.uuid.into_iter().next(), - password: intermediate_rep.password.into_iter().next().ok_or_else(|| "password missing in FormatTest".to_string())?, - }) +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetUserByName200ApplicationSlashJsonResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl GetUserByName200ApplicationSlashJsonResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct GetUserByName200ApplicationSlashXmlResponse(User); + +impl std::convert::From for GetUserByName200ApplicationSlashXmlResponse { + fn from(x: User) -> Self { + GetUserByName200ApplicationSlashXmlResponse(x) + } +} + +impl std::convert::From for User { + fn from(x: GetUserByName200ApplicationSlashXmlResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for GetUserByName200ApplicationSlashXmlResponse { + type Target = User; + fn deref(&self) -> &User { + &self.0 + } +} + +impl std::ops::DerefMut for GetUserByName200ApplicationSlashXmlResponse { + fn deref_mut(&mut self) -> &mut User { + &mut self.0 + } +} + +/// Converts the GetUserByName200ApplicationSlashXmlResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for GetUserByName200ApplicationSlashXmlResponse { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a GetUserByName200ApplicationSlashXmlResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for GetUserByName200ApplicationSlashXmlResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(GetUserByName200ApplicationSlashXmlResponse(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to GetUserByName200ApplicationSlashXmlResponse: {:?}", s, e)), + } } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for FormatTest - value: {} is invalid {}", + format!("Invalid header value for GetUserByName200ApplicationSlashXmlResponse - value: {} is invalid {}", hdr_value, e)) } } } #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into FormatTest - {}", + format!("Unable to convert header value '{}' into GetUserByName200ApplicationSlashXmlResponse - {}", value, err)) } }, @@ -4377,10 +6269,10 @@ impl std::convert::TryFrom for header::IntoHeaderVal } #[cfg(feature = "server")] -impl std::convert::TryFrom>> for hyper::header::HeaderValue { +impl std::convert::TryFrom>> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { hdr_value.to_string() }).collect(); @@ -4394,21 +6286,21 @@ impl std::convert::TryFrom>> for hyper:: } #[cfg(feature = "server")] -impl std::convert::TryFrom for header::IntoHeaderValue> { +impl std::convert::TryFrom for header::IntoHeaderValue> { type Error = String; fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { match hdr_values.to_str() { std::result::Result::Ok(hdr_values) => { - let hdr_values : std::vec::Vec = hdr_values + let hdr_values : std::vec::Vec = hdr_values .split(',') .filter_map(|hdr_value| match hdr_value.trim() { "" => std::option::Option::None, hdr_value => std::option::Option::Some({ - match ::from_str(hdr_value) { + match ::from_str(hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into FormatTest - {}", + format!("Unable to convert header value '{}' into GetUserByName200ApplicationSlashXmlResponse - {}", hdr_value, err)) } }) @@ -4422,7 +6314,7 @@ impl std::convert::TryFrom for header::IntoHeaderVal } } -impl FormatTest { +impl GetUserByName200ApplicationSlashXmlResponse { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] @@ -4714,31 +6606,301 @@ impl std::str::FromStr for List { // Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for List - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into List - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into List - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl List { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct LoginUser200ApplicationSlashJsonResponse(String); + +impl std::convert::From for LoginUser200ApplicationSlashJsonResponse { + fn from(x: String) -> Self { + LoginUser200ApplicationSlashJsonResponse(x) + } +} + +impl std::convert::From for String { + fn from(x: LoginUser200ApplicationSlashJsonResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for LoginUser200ApplicationSlashJsonResponse { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for LoginUser200ApplicationSlashJsonResponse { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + +impl std::string::ToString for LoginUser200ApplicationSlashJsonResponse { + fn to_string(&self) -> String { + self.0.clone() + } +} + +impl std::str::FromStr for LoginUser200ApplicationSlashJsonResponse { + type Err = ::std::convert::Infallible; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(LoginUser200ApplicationSlashJsonResponse(x.to_owned())) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for LoginUser200ApplicationSlashJsonResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into LoginUser200ApplicationSlashJsonResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into LoginUser200ApplicationSlashJsonResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl LoginUser200ApplicationSlashJsonResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct LoginUser200ApplicationSlashXmlResponse(String); + +impl std::convert::From for LoginUser200ApplicationSlashXmlResponse { + fn from(x: String) -> Self { + LoginUser200ApplicationSlashXmlResponse(x) + } +} + +impl std::convert::From for String { + fn from(x: LoginUser200ApplicationSlashXmlResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for LoginUser200ApplicationSlashXmlResponse { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for LoginUser200ApplicationSlashXmlResponse { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + +impl std::string::ToString for LoginUser200ApplicationSlashXmlResponse { + fn to_string(&self) -> String { + self.0.clone() + } +} + +impl std::str::FromStr for LoginUser200ApplicationSlashXmlResponse { + type Err = ::std::convert::Infallible; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(LoginUser200ApplicationSlashXmlResponse(x.to_owned())) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for List - value: {} is invalid {}", + format!("Invalid header value for LoginUser200ApplicationSlashXmlResponse - value: {} is invalid {}", hdr_value, e)) } } } #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into List - {}", + format!("Unable to convert header value '{}' into LoginUser200ApplicationSlashXmlResponse - {}", value, err)) } }, @@ -4750,10 +6912,10 @@ impl std::convert::TryFrom for header::IntoHeaderVal } #[cfg(feature = "server")] -impl std::convert::TryFrom>> for hyper::header::HeaderValue { +impl std::convert::TryFrom>> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { hdr_value.to_string() }).collect(); @@ -4767,21 +6929,21 @@ impl std::convert::TryFrom>> for hyper::header } #[cfg(feature = "server")] -impl std::convert::TryFrom for header::IntoHeaderValue> { +impl std::convert::TryFrom for header::IntoHeaderValue> { type Error = String; fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { match hdr_values.to_str() { std::result::Result::Ok(hdr_values) => { - let hdr_values : std::vec::Vec = hdr_values + let hdr_values : std::vec::Vec = hdr_values .split(',') .filter_map(|hdr_value| match hdr_value.trim() { "" => std::option::Option::None, hdr_value => std::option::Option::Some({ - match ::from_str(hdr_value) { + match ::from_str(hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into List - {}", + format!("Unable to convert header value '{}' into LoginUser200ApplicationSlashXmlResponse - {}", hdr_value, err)) } }) @@ -4795,7 +6957,7 @@ impl std::convert::TryFrom for header::IntoHeaderVal } } -impl List { +impl LoginUser200ApplicationSlashXmlResponse { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] @@ -6621,7 +8783,7 @@ impl OrderStatus { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct OuterBoolean(bool); @@ -7110,7 +9272,7 @@ impl OuterEnum { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct OuterNumber(f64); @@ -7255,7 +9417,7 @@ impl OuterNumber { } } -#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct OuterString(String); @@ -7651,47 +9813,337 @@ impl std::fmt::Display for PetStatus { } } -impl std::str::FromStr for PetStatus { +impl std::str::FromStr for PetStatus { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { + "available" => std::result::Result::Ok(PetStatus::Available), + "pending" => std::result::Result::Ok(PetStatus::Pending), + "sold" => std::result::Result::Ok(PetStatus::Sold), + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for PetStatus - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into PetStatus - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into PetStatus - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl PetStatus { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct PlaceOrder200ApplicationSlashJsonResponse(Order); + +impl std::convert::From for PlaceOrder200ApplicationSlashJsonResponse { + fn from(x: Order) -> Self { + PlaceOrder200ApplicationSlashJsonResponse(x) + } +} + +impl std::convert::From for Order { + fn from(x: PlaceOrder200ApplicationSlashJsonResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for PlaceOrder200ApplicationSlashJsonResponse { + type Target = Order; + fn deref(&self) -> &Order { + &self.0 + } +} + +impl std::ops::DerefMut for PlaceOrder200ApplicationSlashJsonResponse { + fn deref_mut(&mut self) -> &mut Order { + &mut self.0 + } +} + +/// Converts the PlaceOrder200ApplicationSlashJsonResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for PlaceOrder200ApplicationSlashJsonResponse { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a PlaceOrder200ApplicationSlashJsonResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for PlaceOrder200ApplicationSlashJsonResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(PlaceOrder200ApplicationSlashJsonResponse(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to PlaceOrder200ApplicationSlashJsonResponse: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for PlaceOrder200ApplicationSlashJsonResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into PlaceOrder200ApplicationSlashJsonResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into PlaceOrder200ApplicationSlashJsonResponse - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl PlaceOrder200ApplicationSlashJsonResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct PlaceOrder200ApplicationSlashXmlResponse(Order); + +impl std::convert::From for PlaceOrder200ApplicationSlashXmlResponse { + fn from(x: Order) -> Self { + PlaceOrder200ApplicationSlashXmlResponse(x) + } +} + +impl std::convert::From for Order { + fn from(x: PlaceOrder200ApplicationSlashXmlResponse) -> Self { + x.0 + } +} + +impl std::ops::Deref for PlaceOrder200ApplicationSlashXmlResponse { + type Target = Order; + fn deref(&self) -> &Order { + &self.0 + } +} + +impl std::ops::DerefMut for PlaceOrder200ApplicationSlashXmlResponse { + fn deref_mut(&mut self) -> &mut Order { + &mut self.0 + } +} + +/// Converts the PlaceOrder200ApplicationSlashXmlResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for PlaceOrder200ApplicationSlashXmlResponse { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a PlaceOrder200ApplicationSlashXmlResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for PlaceOrder200ApplicationSlashXmlResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { - match s { - "available" => std::result::Result::Ok(PetStatus::Available), - "pending" => std::result::Result::Ok(PetStatus::Pending), - "sold" => std::result::Result::Ok(PetStatus::Sold), - _ => std::result::Result::Err(format!("Value not valid: {}", s)), + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(PlaceOrder200ApplicationSlashXmlResponse(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to PlaceOrder200ApplicationSlashXmlResponse: {:?}", s, e)), } } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for PetStatus - value: {} is invalid {}", + format!("Invalid header value for PlaceOrder200ApplicationSlashXmlResponse - value: {} is invalid {}", hdr_value, e)) } } } #[cfg(any(feature = "client", feature = "server"))] -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into PetStatus - {}", + format!("Unable to convert header value '{}' into PlaceOrder200ApplicationSlashXmlResponse - {}", value, err)) } }, @@ -7703,10 +10155,10 @@ impl std::convert::TryFrom for header::IntoHeaderVal } #[cfg(feature = "server")] -impl std::convert::TryFrom>> for hyper::header::HeaderValue { +impl std::convert::TryFrom>> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { hdr_value.to_string() }).collect(); @@ -7720,21 +10172,21 @@ impl std::convert::TryFrom>> for hyper::h } #[cfg(feature = "server")] -impl std::convert::TryFrom for header::IntoHeaderValue> { +impl std::convert::TryFrom for header::IntoHeaderValue> { type Error = String; fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { match hdr_values.to_str() { std::result::Result::Ok(hdr_values) => { - let hdr_values : std::vec::Vec = hdr_values + let hdr_values : std::vec::Vec = hdr_values .split(',') .filter_map(|hdr_value| match hdr_value.trim() { "" => std::option::Option::None, hdr_value => std::option::Option::Some({ - match ::from_str(hdr_value) { + match ::from_str(hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into PetStatus - {}", + format!("Unable to convert header value '{}' into PlaceOrder200ApplicationSlashXmlResponse - {}", hdr_value, err)) } }) @@ -7748,7 +10200,7 @@ impl std::convert::TryFrom for header::IntoHeaderVal } } -impl PetStatus { +impl PlaceOrder200ApplicationSlashXmlResponse { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. #[allow(dead_code)] @@ -8977,6 +11429,296 @@ impl TestEnumParametersRequestEnumFormString { } } +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct UpdatePetApplicationSlashJsonRequest(Pet); + +impl std::convert::From for UpdatePetApplicationSlashJsonRequest { + fn from(x: Pet) -> Self { + UpdatePetApplicationSlashJsonRequest(x) + } +} + +impl std::convert::From for Pet { + fn from(x: UpdatePetApplicationSlashJsonRequest) -> Self { + x.0 + } +} + +impl std::ops::Deref for UpdatePetApplicationSlashJsonRequest { + type Target = Pet; + fn deref(&self) -> &Pet { + &self.0 + } +} + +impl std::ops::DerefMut for UpdatePetApplicationSlashJsonRequest { + fn deref_mut(&mut self) -> &mut Pet { + &mut self.0 + } +} + +/// Converts the UpdatePetApplicationSlashJsonRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for UpdatePetApplicationSlashJsonRequest { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a UpdatePetApplicationSlashJsonRequest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for UpdatePetApplicationSlashJsonRequest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(UpdatePetApplicationSlashJsonRequest(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to UpdatePetApplicationSlashJsonRequest: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for UpdatePetApplicationSlashJsonRequest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into UpdatePetApplicationSlashJsonRequest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into UpdatePetApplicationSlashJsonRequest - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl UpdatePetApplicationSlashJsonRequest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct UpdatePetApplicationSlashXmlRequest(Pet); + +impl std::convert::From for UpdatePetApplicationSlashXmlRequest { + fn from(x: Pet) -> Self { + UpdatePetApplicationSlashXmlRequest(x) + } +} + +impl std::convert::From for Pet { + fn from(x: UpdatePetApplicationSlashXmlRequest) -> Self { + x.0 + } +} + +impl std::ops::Deref for UpdatePetApplicationSlashXmlRequest { + type Target = Pet; + fn deref(&self) -> &Pet { + &self.0 + } +} + +impl std::ops::DerefMut for UpdatePetApplicationSlashXmlRequest { + fn deref_mut(&mut self) -> &mut Pet { + &mut self.0 + } +} + +/// Converts the UpdatePetApplicationSlashXmlRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for UpdatePetApplicationSlashXmlRequest { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a UpdatePetApplicationSlashXmlRequest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for UpdatePetApplicationSlashXmlRequest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match std::str::FromStr::from_str(s) { + std::result::Result::Ok(r) => std::result::Result::Ok(UpdatePetApplicationSlashXmlRequest(r)), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {} to UpdatePetApplicationSlashXmlRequest: {:?}", s, e)), + } + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for UpdatePetApplicationSlashXmlRequest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(any(feature = "client", feature = "server"))] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into UpdatePetApplicationSlashXmlRequest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom>> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_values: header::IntoHeaderValue>) -> std::result::Result { + let hdr_values : Vec = hdr_values.0.into_iter().map(|hdr_value| { + hdr_value.to_string() + }).collect(); + + match hyper::header::HeaderValue::from_str(&hdr_values.join(", ")) { + std::result::Result::Ok(hdr_value) => std::result::Result::Ok(hdr_value), + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to convert {:?} into a header - {}", + hdr_values, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_values: hyper::header::HeaderValue) -> std::result::Result { + match hdr_values.to_str() { + std::result::Result::Ok(hdr_values) => { + let hdr_values : std::vec::Vec = hdr_values + .split(',') + .filter_map(|hdr_value| match hdr_value.trim() { + "" => std::option::Option::None, + hdr_value => std::option::Option::Some({ + match ::from_str(hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into UpdatePetApplicationSlashXmlRequest - {}", + hdr_value, err)) + } + }) + }).collect::, String>>()?; + + std::result::Result::Ok(header::IntoHeaderValue(hdr_values)) + }, + std::result::Result::Err(e) => std::result::Result::Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_values, e)), + } + } +} + +impl UpdatePetApplicationSlashXmlRequest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn as_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] #[serde(rename = "User")] diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs index b0d83b6a7271..23e2184ede5a 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs @@ -345,6 +345,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -353,6 +354,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -389,6 +391,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -447,6 +450,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // */* response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("*/*") @@ -455,6 +459,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -519,6 +524,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // */* response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("*/*") @@ -527,6 +533,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -591,6 +598,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // */* response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("*/*") @@ -599,6 +607,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -663,6 +672,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // */* response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("*/*") @@ -671,6 +681,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -707,6 +718,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -803,6 +815,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -877,6 +890,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -885,6 +899,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -982,11 +997,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, TestEndpointParametersResponse::UserNotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, }, Err(_) => { @@ -1141,11 +1158,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, TestEnumParametersResponse::NotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, }, Err(_) => { @@ -1220,6 +1239,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1271,6 +1291,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1331,6 +1352,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -1409,6 +1431,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -1417,6 +1440,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -1475,7 +1499,64 @@ impl hyper::service::Service<(Request, C)> for Service where match result { Ok(body) => { let mut unused_elements : Vec = vec![]; - let param_body: Option = if !body.is_empty() { + // Body has multiple variant schemas + let param_body : + swagger::OneOf2 + = if body.is_empty() { + + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Missing body"))) + .expect("Unable to create Bad Request for missing body")) + + } else { + let content_type = headers.get(CONTENT_TYPE); + + let content_type = if let Some(content_type) = headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Missing Content-Type header"))) + .expect("Unable to create Bad Request for missing content type")) + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + match content_type { + Ok("application/json") => { + let param_body: Option = if !body.is_empty() { + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Couldn't parse body parameter body - doesn't match schema: {}", e))) + .expect("Unable to create Bad Request response for invalid body parameter body due to schema")), + } + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from("Missing required body parameter body")) + .expect("Unable to create Bad Request response for missing body parameter body")), + }; + + + + let param_body : models::AddPetApplicationSlashJsonRequest = models::AddPetApplicationSlashJsonRequest::from(param_body); + + swagger::OneOf2::::A(param_body) + }, + Ok("application/xml") => { + let param_body: Option = 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); @@ -1499,6 +1580,20 @@ impl hyper::service::Service<(Request, C)> for Service where }; + + let param_body : models::AddPetApplicationSlashXmlRequest = models::AddPetApplicationSlashXmlRequest::from(param_body); + + swagger::OneOf2::::B(param_body) + }, + _ => { + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Incorrect content type"))) + .expect("Unable to create Bad Request for incorrect content type")) + } + } + }; + let result = api_impl.add_pet( param_body, &context @@ -1521,6 +1616,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(405).expect("Unable to turn 405 into a StatusCode"); + }, }, Err(_) => { @@ -1594,6 +1690,11 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + let body = match body { + swagger::OneOf2::::A(body) => { + let body : Vec = body.into(); + + // application/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/xml") @@ -1602,11 +1703,28 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, + swagger::OneOf2::::B(body) => { + let body : Vec = body.into(); + + // application/json + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for application/json")); + // JSON Body + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + + }, + }; + }, FindPetsByStatusResponse::InvalidStatusValue => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -1674,6 +1792,11 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + let body = match body { + swagger::OneOf2::::A(body) => { + let body : Vec = body.into(); + + // application/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/xml") @@ -1682,11 +1805,28 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, + swagger::OneOf2::::B(body) => { + let body : Vec = body.into(); + + // application/json + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for application/json")); + // JSON Body + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + + }, + }; + }, FindPetsByTagsResponse::InvalidTagValue => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -1739,7 +1879,64 @@ impl hyper::service::Service<(Request, C)> for Service where match result { Ok(body) => { let mut unused_elements : Vec = vec![]; - let param_body: Option = if !body.is_empty() { + // Body has multiple variant schemas + let param_body : + swagger::OneOf2 + = if body.is_empty() { + + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Missing body"))) + .expect("Unable to create Bad Request for missing body")) + + } else { + let content_type = headers.get(CONTENT_TYPE); + + let content_type = if let Some(content_type) = headers.get(CONTENT_TYPE) { + content_type.to_str() + } else { + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Missing Content-Type header"))) + .expect("Unable to create Bad Request for missing content type")) + }; + + let content_type = content_type.map(|s| + s.split(';').next().expect("Spliting content type header failed").trim()); + + match content_type { + Ok("application/json") => { + let param_body: Option = if !body.is_empty() { + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_body) => param_body, + Err(e) => return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Couldn't parse body parameter body - doesn't match schema: {}", e))) + .expect("Unable to create Bad Request response for invalid body parameter body due to schema")), + } + } else { + None + }; + let param_body = match param_body { + Some(param_body) => param_body, + None => return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from("Missing required body parameter body")) + .expect("Unable to create Bad Request response for missing body parameter body")), + }; + + + + let param_body : models::UpdatePetApplicationSlashJsonRequest = models::UpdatePetApplicationSlashJsonRequest::from(param_body); + + swagger::OneOf2::::A(param_body) + }, + Ok("application/xml") => { + let param_body: Option = 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); @@ -1763,6 +1960,20 @@ impl hyper::service::Service<(Request, C)> for Service where }; + + let param_body : models::UpdatePetApplicationSlashXmlRequest = models::UpdatePetApplicationSlashXmlRequest::from(param_body); + + swagger::OneOf2::::B(param_body) + }, + _ => { + return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Incorrect content type"))) + .expect("Unable to create Bad Request for incorrect content type")) + } + } + }; + let result = api_impl.update_pet( param_body, &context @@ -1785,16 +1996,19 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, UpdatePetResponse::PetNotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, UpdatePetResponse::ValidationException => { *response.status_mut() = StatusCode::from_u16(405).expect("Unable to turn 405 into a StatusCode"); + }, }, Err(_) => { @@ -1906,6 +2120,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -1970,6 +2185,11 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + let body = match body { + swagger::OneOf2::::A(body) => { + let body : models::Pet = body.into(); + + // application/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/xml") @@ -1978,16 +2198,34 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, + swagger::OneOf2::::B(body) => { + let body : models::Pet = body.into(); + + // application/json + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for application/json")); + // JSON Body + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + + }, + }; + }, GetPetByIdResponse::InvalidIDSupplied => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, GetPetByIdResponse::PetNotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, }, Err(_) => { @@ -2087,6 +2325,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(405).expect("Unable to turn 405 into a StatusCode"); + }, }, Err(_) => { @@ -2285,6 +2524,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -2293,6 +2533,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -2339,6 +2580,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -2347,6 +2589,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -2415,6 +2658,11 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + let body = match body { + swagger::OneOf2::::A(body) => { + let body : models::Order = body.into(); + + // application/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/xml") @@ -2423,11 +2671,28 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, + swagger::OneOf2::::B(body) => { + let body : models::Order = body.into(); + + // application/json + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for application/json")); + // JSON Body + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + + }, + }; + }, PlaceOrderResponse::InvalidOrder => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -2488,11 +2753,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, DeleteOrderResponse::OrderNotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, }, Err(_) => { @@ -2547,6 +2814,11 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + let body = match body { + swagger::OneOf2::::A(body) => { + let body : models::Order = body.into(); + + // application/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/xml") @@ -2555,16 +2827,34 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, + swagger::OneOf2::::B(body) => { + let body : models::Order = body.into(); + + // application/json + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for application/json")); + // JSON Body + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + + }, + }; + }, GetOrderByIdResponse::InvalidIDSupplied => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, GetOrderByIdResponse::OrderNotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, }, Err(_) => { @@ -2633,6 +2923,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(0).expect("Unable to turn 0 into a StatusCode"); + }, }, Err(_) => { @@ -2707,6 +2998,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(0).expect("Unable to turn 0 into a StatusCode"); + }, }, Err(_) => { @@ -2781,6 +3073,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(0).expect("Unable to turn 0 into a StatusCode"); + }, }, Err(_) => { @@ -2908,6 +3201,11 @@ impl hyper::service::Service<(Request, C)> for Service where x_expires_after ); } + let body = match body { + swagger::OneOf2::::A(body) => { + let body : String = body.into(); + + // application/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/xml") @@ -2916,11 +3214,28 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, + swagger::OneOf2::::B(body) => { + let body : String = body.into(); + + // application/json + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for application/json")); + // JSON Body + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + + }, + }; + }, LoginUserResponse::InvalidUsername => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, }, Err(_) => { @@ -2951,6 +3266,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(0).expect("Unable to turn 0 into a StatusCode"); + }, }, Err(_) => { @@ -3005,11 +3321,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, DeleteUserResponse::UserNotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, }, Err(_) => { @@ -3064,6 +3382,11 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + let body = match body { + swagger::OneOf2::::A(body) => { + let body : models::User = body.into(); + + // application/xml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/xml") @@ -3072,16 +3395,34 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, + swagger::OneOf2::::B(body) => { + let body : models::User = body.into(); + + // application/json + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for application/json")); + // JSON Body + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + + }, + }; + }, GetUserByNameResponse::InvalidUsernameSupplied => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, GetUserByNameResponse::UserNotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, }, Err(_) => { @@ -3174,11 +3515,13 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + }, UpdateUserResponse::UserNotFound => { *response.status_mut() = StatusCode::from_u16(404).expect("Unable to turn 404 into a StatusCode"); + }, }, Err(_) => { diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs index 22eb1b5814c8..4227a87db401 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs @@ -413,6 +413,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -443,6 +446,7 @@ impl Api for Client where match response.status().as_u16() { 201 => { + let (header, body) = response.into_parts(); Ok( PingGetResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/server/mod.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/server/mod.rs index 04b60fe04545..69c89d5f970a 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/server/mod.rs @@ -172,6 +172,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode"); + }, }, Err(_) => { diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs index a88ea9dea0ae..b55bf45e4b36 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs @@ -421,6 +421,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -432,17 +435,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // */* let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(AllOfGetResponse::OK (body) ) @@ -500,6 +505,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -511,6 +519,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( DummyGetResponse::Success ) @@ -569,16 +578,8 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; - // Consumes basic body - // Body parameter - let body = serde_json::to_string(¶m_nested_response).expect("impossible to fail to serialize"); - *request.body_mut() = Body::from(body); + // No schema variants - let header = "application/json"; - request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) { - Ok(h) => h, - Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) - }); let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { @@ -591,6 +592,7 @@ impl Api for Client where match response.status().as_u16() { 200 => { + let (header, body) = response.into_parts(); Ok( DummyPutResponse::Success ) @@ -648,6 +650,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -659,17 +664,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/json let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(FileResponseGetResponse::Success (body) ) @@ -727,6 +734,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -738,16 +748,18 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // application/yaml let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = body.to_string(); + Ok(GetStructuredYamlResponse::OK (body) ) @@ -806,6 +818,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = param_body; @@ -817,6 +832,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -828,16 +844,18 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // text/html let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = body.to_string(); + Ok(HtmlPostResponse::Success (body) ) @@ -896,6 +914,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = param_value; @@ -907,6 +928,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -918,6 +940,7 @@ impl Api for Client where match response.status().as_u16() { 204 => { + let (header, body) = response.into_parts(); Ok( PostYamlResponse::OK ) @@ -975,6 +998,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -986,17 +1012,19 @@ impl Api for Client where match response.status().as_u16() { 200 => { - let body = response.into_body(); + let (header, body) = response.into_parts(); let body = body .into_raw() .map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?; + // */* let body = str::from_utf8(&body) .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?; let body = serde_json::from_str::(body) .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e)))?; + Ok(RawJsonGetResponse::Success (body) ) @@ -1055,6 +1083,9 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create request: {}", e))) }; + // No schema variants + // Basic schema + // Consumes basic body // Body parameter let body = serde_json::to_string(¶m_value).expect("impossible to fail to serialize"); @@ -1066,6 +1097,7 @@ impl Api for Client where Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e))) }); + let header = HeaderValue::from_str(Has::::get(context).0.as_str()); request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header { Ok(h) => h, @@ -1077,6 +1109,7 @@ impl Api for Client where match response.status().as_u16() { 204 => { + let (header, body) = response.into_parts(); Ok( SoloObjectPostResponse::OK ) diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs index d2e153e4ac52..75c7181655af 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs @@ -184,6 +184,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // */* response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("*/*") @@ -192,6 +193,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -222,6 +224,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -290,6 +293,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + }, }, Err(_) => { @@ -326,6 +330,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/json response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") @@ -334,6 +339,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -364,6 +370,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // application/yaml response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/yaml") @@ -372,6 +379,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = body; *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -393,6 +401,7 @@ impl hyper::service::Service<(Request, C)> for Service where let result = body.into_raw().await; match result { Ok(body) => { + let mut unused_elements : Vec = vec![]; let param_body: Option = if !body.is_empty() { match String::from_utf8(body.to_vec()) { Ok(param_body) => Some(param_body), @@ -423,12 +432,19 @@ impl hyper::service::Service<(Request, C)> for Service where HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); + if !unused_elements.is_empty() { + response.headers_mut().insert( + HeaderName::from_static("warning"), + HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) + .expect("Unable to create Warning header value")); + } match result { Ok(rsp) => match rsp { HtmlPostResponse::Success (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // text/html response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("text/html") @@ -437,6 +453,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = body; *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -464,6 +481,7 @@ impl hyper::service::Service<(Request, C)> for Service where let result = body.into_raw().await; match result { Ok(body) => { + let mut unused_elements : Vec = vec![]; let param_value: Option = if !body.is_empty() { match String::from_utf8(body.to_vec()) { Ok(param_value) => Some(param_value), @@ -494,12 +512,19 @@ impl hyper::service::Service<(Request, C)> for Service where HeaderValue::from_str((&context as &dyn Has).get().0.clone().as_str()) .expect("Unable to create X-Span-ID header value")); + if !unused_elements.is_empty() { + response.headers_mut().insert( + HeaderName::from_static("warning"), + HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) + .expect("Unable to create Warning header value")); + } match result { Ok(rsp) => match rsp { PostYamlResponse::OK => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + }, }, Err(_) => { @@ -536,6 +561,7 @@ impl hyper::service::Service<(Request, C)> for Service where (body) => { *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + // */* response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("*/*") @@ -544,6 +570,7 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); + }, }, Err(_) => { @@ -612,6 +639,7 @@ impl hyper::service::Service<(Request, C)> for Service where => { *response.status_mut() = StatusCode::from_u16(204).expect("Unable to turn 204 into a StatusCode"); + }, }, Err(_) => { From 9cc212a6ab7f4ecca5b211455e7a073745b87566 Mon Sep 17 00:00:00 2001 From: Richard Whitehouse Date: Wed, 21 Aug 2024 15:42:03 +0100 Subject: [PATCH 3/6] [Core] Restore null check --- .../java/org/openapitools/codegen/DefaultCodegen.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 1dba3ec86a78..7b9ec367007f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -7871,7 +7871,6 @@ public CodegenParameter fromRequestBody(RequestBody body, String opId, Set schemas = ModelUtils.getSchemasFromRequestBody(body); @@ -7903,7 +7902,6 @@ public CodegenParameter fromRequestBody(RequestBody body, String opId, Set entry : schemas.entrySet()) { - if (schemas.size() > 1 && supportsMultipleRequestTypes) { codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); codegenParameter.required = true; @@ -7917,6 +7915,12 @@ public CodegenParameter fromRequestBody(RequestBody body, String opId, Set Date: Thu, 22 Aug 2024 13:41:00 +0100 Subject: [PATCH 4/6] [Core] Fix nested form params --- .../codegen/CodegenParameter.java | 11 +- .../openapitools/codegen/DefaultCodegen.java | 180 +++++++++--------- .../codegen/languages/RustServerCodegen.java | 6 - 3 files changed, 88 insertions(+), 109 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index bb6539b7cede..84799c030026 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -134,10 +134,6 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { * If this is a schema variant, this gives the schema variant type */ public String variantType; - /** - * If this is a body schema, representing a simple form, these are the form parameters - */ - public List formParams; private Integer maxProperties; private Integer minProperties; public boolean isNull; @@ -257,9 +253,6 @@ public CodegenParameter copy() { if (this.schemaVariants != null) { output.schemaVariants = new ArrayList(this.schemaVariants); } - if (this.formParams != null) { - output.formParams = new ArrayList(this.formParams); - } output.hasValidation = this.hasValidation; output.isNullable = this.isNullable; output.isDeprecated = this.isDeprecated; @@ -316,7 +309,7 @@ public int hashCode() { hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content, requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties, nameInPascalCase, nameInCamelCase, nameInLowerCase, nameInSnakeCase, - schemaVariants, variantType, formParams); + schemaVariants, variantType); } @Override @@ -423,7 +416,6 @@ public boolean equals(Object o) { Objects.equals(getMinItems(), that.getMinItems()) && Objects.equals(contentType, that.contentType) && Objects.equals(multipleOf, that.multipleOf) && - Objects.equals(formParams, that.formParams) && Objects.equals(schemaVariants, that.schemaVariants) && Objects.equals(variantType, that.variantType); } @@ -541,7 +533,6 @@ public String toString() { sb.append(", schemaIsFromAdditionalProperties=").append(schemaIsFromAdditionalProperties); sb.append(", schemaVariants=").append(schemaVariants); sb.append(", variantType=").append(variantType); - sb.append(", formParams=").append(formParams); sb.append('}'); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 7b9ec367007f..bf87b26e8019 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -7945,106 +7945,100 @@ public CodegenParameter fromRequestBody(RequestBody body, String opId, Set Date: Thu, 22 Aug 2024 16:58:49 +0100 Subject: [PATCH 5/6] [Core] Further fix to formParams --- .../java/org/openapitools/codegen/CodegenResponse.java | 7 ------- .../java/org/openapitools/codegen/DefaultCodegen.java | 9 +-------- .../codegen/languages/RustServerCodegen.java | 6 ------ 3 files changed, 1 insertion(+), 21 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index b8c5ee0ef83c..4cc29e754048 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -124,13 +124,6 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { */ public String variantType; - /** - * This is required if the response is some form of complex body type. - * - * e.g. multipart/related or form parameters - */ - public List formParams = new ArrayList(); - @Override public int hashCode() { return Objects.hash(headers, code, message, examples, dataType, baseType, containerType, containerTypeMapped, hasHeaders, diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index bf87b26e8019..3a51f0564718 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -4691,7 +4691,7 @@ public CodegenOperation fromOperation(String path, boolean simpleForm = false; - if (bodySchemas != null && bodySchemas.size() == 1) { + if (bodySchemas != null && (bodySchemas.size() == 1 || !supportsMultipleRequestTypes)) { LOGGER.debug("Op: " + op.operationId + " has request body with single schema"); Map.Entry entry = bodySchemas.entrySet().iterator().next(); @@ -4972,13 +4972,6 @@ public CodegenResponse fromResponse(String opId, String responseCode, ApiRespons Schema responseSchema = entry.getValue(); - if (isForm(r.contentType)) { - Schema formSchema = ModelUtils.getReferencedSchema(this.openAPI, responseSchema); - r.formParams = fromSchemaToFormParameters(formSchema, - response.getContent().get(r.contentType), new TreeSet()); - LOGGER.info("Created form parameters for " + opId + "-" + responseCode + " :: " + r.formParams); - } - if (this.openAPI != null && this.openAPI.getComponents() != null && !ModelUtils.isGenerateAliasAsModel()) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java index f15623837e67..8784e4f90516 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java @@ -936,12 +936,6 @@ private void postProcessOperationWithModels(CodegenOperation op, List header.nameInLowerCase = header.baseName.toLowerCase(Locale.ROOT); } - for (CodegenResponse rsp : op.responses) { - for (CodegenParameter param : rsp.formParams) { - processParam(param, op); - } - } - if (op.authMethods != null) { boolean headerAuthMethods = false; From 179ec8c388560a55c359828c08f85b74264b1752 Mon Sep 17 00:00:00 2001 From: Richard Whitehouse Date: Thu, 19 Sep 2024 16:24:34 +0100 Subject: [PATCH 6/6] Update Javadoc --- .../openapitools/codegen/DefaultCodegen.java | 20 +++++++++++++++++++ .../codegen/utils/ModelUtils.java | 19 ++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 89958123b8bb..05296f4fa3bc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -445,6 +445,11 @@ private void registerMustacheLambdas() { additionalProperties.put("lambda", lambdas); } + /** + * Create a codegen model map for the given model for the given request/response variant codegen model + * + * @param cm Codegen model for the new request/response variant + */ @SuppressWarnings({"static-method"}) public ModelsMap createModelForVariant(CodegenModel cm) { // We need to force this not to be an alias, as we need to provide some way @@ -459,6 +464,12 @@ public ModelsMap createModelForVariant(CodegenModel cm) { return modelsMap; } + /** + * Handle generation of request/response variant models for the given paths. + * + * @param items Paths to generate for + * @param objs Models map to update + */ public void generateVariantModelsForPathItems(Map items, Map objs) { if (items != null) { for (Map.Entry e : items.entrySet()) { @@ -469,6 +480,14 @@ public void generateVariantModelsForPathItems(Map items, Map objs) { if (supportsMultipleRequestTypes || supportsMultipleResponseTypes) { String opId = getOrGenerateOperationId(op, key, method.toString()); @@ -4901,6 +4920,7 @@ public boolean isParameterNameUnique(CodegenParameter p, List /** * Convert OAS Response object to Codegen Response object * + * @param opId Operation ID * @param responseCode HTTP response code * @param response OAS Response object * @return Codegen Response object diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java index 0562ba28235e..1edef639ae23 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java @@ -1293,6 +1293,25 @@ private static MediaType getFirstMediaTypeFromContent(Content content) { return entry.getValue(); } + /** + * Return the schemas from a specified OAS 'content' section. + *

+ * For example, given the following OAS, this method returns the XYZ and WXY schemas, + * indexed by "application/json" and "application/xml" respectively. + *

+ * responses: + * '200': + * content: + * application/json: + * schema: + * $ref: '#/components/schemas/XYZ' + * application/xml: + * schema: + * $ref: '#/components/schemas/WXY' + * + * @param content a 'content' section in the OAS specification. + * @return the schemas, indexed by content type. + */ private static Map getSchemasFromContent(Content content) { if (content == null || content.isEmpty()) { return null;