From 9a141864ab95de9c6c1e3290ecb70c9c3e10062b Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 00:13:29 +0800 Subject: [PATCH 01/22] add rust generator (1st release) --- bin/rust-petstore.sh | 31 ++ bin/windows/rust-petstore.bat | 10 + .../io/swagger/codegen/DefaultCodegen.java | 2 +- .../swagger/codegen/InlineModelResolver.java | 8 +- .../codegen/languages/RustClientCodegen.java | 515 ++++++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../src/main/resources/rust/.travis.yml | 8 + .../src/main/resources/rust/Cargo.mustache | 17 + .../src/main/resources/rust/README.mustache | 96 ++++ .../src/main/resources/rust/api.mustache | 102 ++++ .../main/resources/rust/api_client.mustache | 422 ++++++++++++++ .../src/main/resources/rust/api_doc.mustache | 50 ++ .../src/main/resources/rust/api_mod.mustache | 44 ++ .../main/resources/rust/api_response.mustache | 35 ++ .../src/main/resources/rust/client.mustache | 55 ++ .../resources/rust/configuration.mustache | 16 + .../main/resources/rust/git_push.sh.mustache | 52 ++ .../main/resources/rust/gitignore.mustache | 3 + .../src/main/resources/rust/lib.rs | 10 + .../src/main/resources/rust/model.mustache | 57 ++ .../main/resources/rust/model_doc.mustache | 11 + .../main/resources/rust/model_mod.mustache | 6 + .../resources/rust/partial_header.mustache | 13 + .../petstore/rust/.swagger-codegen-ignore | 23 + .../petstore/rust/.swagger-codegen/VERSION | 1 + samples/client/petstore/rust/.travis.yml | 8 + samples/client/petstore/rust/Cargo.toml | 6 +- samples/client/petstore/rust/README.md | 97 ++++ .../client/petstore/rust/docs/ApiResponse.md | 12 + samples/client/petstore/rust/docs/Category.md | 11 + samples/client/petstore/rust/docs/Order.md | 15 + samples/client/petstore/rust/docs/Pet.md | 15 + samples/client/petstore/rust/docs/PetApi.md | 269 +++++++++ samples/client/petstore/rust/docs/StoreApi.md | 117 ++++ samples/client/petstore/rust/docs/Tag.md | 11 + samples/client/petstore/rust/docs/User.md | 17 + samples/client/petstore/rust/docs/UserApi.md | 231 ++++++++ samples/client/petstore/rust/git_push.sh | 52 ++ samples/client/petstore/rust/src/apis/api.rs | 95 ++++ .../petstore/rust/src/apis/api_client.rs | 423 ++++++++++++++ .../client/petstore/rust/src/apis/client.rs | 89 ++- .../petstore/rust/src/apis/configuration.rs | 12 +- .../client/petstore/rust/src/apis/pet_api.rs | 137 ++++- .../petstore/rust/src/apis/store_api.rs | 93 ++++ .../client/petstore/rust/src/apis/user_api.rs | 176 ++++++ .../petstore/rust/src/models/api_response.rs | 60 ++ .../petstore/rust/src/models/category.rs | 51 +- .../client/petstore/rust/src/models/mod.rs | 16 +- .../client/petstore/rust/src/models/order.rs | 94 ++++ .../client/petstore/rust/src/models/pet.rs | 84 ++- .../client/petstore/rust/src/models/tag.rs | 51 +- .../client/petstore/rust/src/models/user.rs | 116 ++++ 52 files changed, 3894 insertions(+), 52 deletions(-) create mode 100755 bin/rust-petstore.sh create mode 100644 bin/windows/rust-petstore.bat create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/rust/.travis.yml create mode 100644 modules/swagger-codegen/src/main/resources/rust/Cargo.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/api_client.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/api_doc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/api_mod.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/api_response.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/client.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/configuration.mustache create mode 100755 modules/swagger-codegen/src/main/resources/rust/git_push.sh.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/gitignore.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/lib.rs create mode 100644 modules/swagger-codegen/src/main/resources/rust/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/model_doc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/model_mod.mustache create mode 100644 modules/swagger-codegen/src/main/resources/rust/partial_header.mustache create mode 100644 samples/client/petstore/rust/.swagger-codegen-ignore create mode 100644 samples/client/petstore/rust/.swagger-codegen/VERSION create mode 100644 samples/client/petstore/rust/.travis.yml create mode 100644 samples/client/petstore/rust/README.md create mode 100644 samples/client/petstore/rust/docs/ApiResponse.md create mode 100644 samples/client/petstore/rust/docs/Category.md create mode 100644 samples/client/petstore/rust/docs/Order.md create mode 100644 samples/client/petstore/rust/docs/Pet.md create mode 100644 samples/client/petstore/rust/docs/PetApi.md create mode 100644 samples/client/petstore/rust/docs/StoreApi.md create mode 100644 samples/client/petstore/rust/docs/Tag.md create mode 100644 samples/client/petstore/rust/docs/User.md create mode 100644 samples/client/petstore/rust/docs/UserApi.md create mode 100644 samples/client/petstore/rust/git_push.sh create mode 100644 samples/client/petstore/rust/src/apis/api.rs create mode 100644 samples/client/petstore/rust/src/apis/api_client.rs create mode 100644 samples/client/petstore/rust/src/apis/store_api.rs create mode 100644 samples/client/petstore/rust/src/apis/user_api.rs create mode 100644 samples/client/petstore/rust/src/models/api_response.rs create mode 100644 samples/client/petstore/rust/src/models/order.rs create mode 100644 samples/client/petstore/rust/src/models/user.rs diff --git a/bin/rust-petstore.sh b/bin/rust-petstore.sh new file mode 100755 index 00000000000..1e08b616a11 --- /dev/null +++ b/bin/rust-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=$(ls -ld "$SCRIPT") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=$(dirname "$SCRIPT")/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=$(dirname "$SCRIPT")/.. + APP_DIR=$(cd "${APP_DIR}"; pwd) +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate -t modules/swagger-codegen/src/main/resources/rust -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l rust -o samples/client/petstore/rust $@" + +java ${JAVA_OPTS} -jar ${executable} ${ags} diff --git a/bin/windows/rust-petstore.bat b/bin/windows/rust-petstore.bat new file mode 100644 index 00000000000..70645379abb --- /dev/null +++ b/bin/windows/rust-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l rust -o samples\client\petstore\rust + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 92f1a483c0f..474a1750059 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -3611,7 +3611,7 @@ public String addRegularExpressionDelimiter(String pattern) { * writes it back to additionalProperties to be usable as a boolean in * mustache files. * - * @param propertyKey + * @param propertyKey property key * @return property value as boolean */ public boolean convertPropertyToBooleanAndWriteBack(String propertyKey) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java index 34b0906fd10..e82da878e8d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/InlineModelResolver.java @@ -385,8 +385,8 @@ public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") S /** * Make a RefProperty * - * @param ref - * @param property + * @param ref new property name + * @param property Property * @return */ public Property makeRefProperty(String ref, Property property) { @@ -398,8 +398,8 @@ public Property makeRefProperty(String ref, Property property) { /** * Copy vendor extensions from Property to another Property * - * @param source - * @param target + * @param source source property + * @param target target property */ public void copyVendorExtensions(Property source, AbstractProperty target) { Map vendorExtensions = source.getVendorExtensions(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java new file mode 100644 index 00000000000..984298914bd --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -0,0 +1,515 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.parameters.Parameter; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { + static Logger LOGGER = LoggerFactory.getLogger(RustClientCodegen.class); + + protected String packageName = "swagger"; + protected String packageVersion = "1.0.0"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + protected String apiFolder = "src/apis"; + protected String modelFolder= "src/models"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "rust"; + } + + public String getHelp() { + return "Generates a Rust client library (beta)."; + } + + public RustClientCodegen() { + super(); + outputFolder = "generated-code/rust"; + modelTemplateFiles.put("model.mustache", ".rs"); + apiTemplateFiles.put("api.mustache", ".rs"); + + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + embeddedTemplateDir = templateDir = "rust"; + + setReservedWordsLowerCase( + Arrays.asList( + "abstract", "alignof", "as", "become", "box", + "break", "const", "continue", "crate", "do", + "else", "enum", "extern", "false", "final", + "fn", "for", "if", "impl", "in", + "let", "loop", "macro", "match", "mod", + "move", "mut", "offsetof", "override", "priv", + "proc", "pub", "pure", "ref", "return", + "Self", "self", "sizeof", "static", "struct", + "super", "trait", "true", "type", "typeof", + "unsafe", "unsized", "use", "virtual", "where", + "while", "yield" + ) + ); + + defaultIncludes = new HashSet( + Arrays.asList( + "map", + "array") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "i8", "i16", "i32", "i64", + "u8", "u16", "u32", "u64", + "f32", "f64", + "char", "bool") + ); + + instantiationTypes.clear(); + /*instantiationTypes.put("array", "GoArray"); + instantiationTypes.put("map", "GoMap");*/ + + typeMapping.clear(); + typeMapping.put("integer", "i32"); + typeMapping.put("long", "i64"); + typeMapping.put("number", "f32"); + typeMapping.put("float", "f32"); + typeMapping.put("double", "f64"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "String"); + typeMapping.put("UUID", "String"); + typeMapping.put("date", "string"); + typeMapping.put("DateTime", "String"); + typeMapping.put("password", "String"); + typeMapping.put("file", "File"); + // map binary to string as a workaround + // the correct solution is to use []byte + typeMapping.put("binary", "String"); + typeMapping.put("ByteArray", "String"); + typeMapping.put("object", "Object"); + + importMapping = new HashMap(); + importMapping.put("time.Time", "time"); + importMapping.put("*os.File", "os"); + importMapping.put("os", "io/ioutil"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Rust package name (convention: lowercase).") + .defaultValue("swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Rust package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + + } + + @Override + public void processOpts() { + super.processOpts(); + + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + else { + setPackageName("swagger"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } + else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + modelPackage = packageName; + apiPackage = packageName; + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("configuration.mustache", apiFolder, "configuration.rs")); + supportingFiles.add(new SupportingFile("api_client.mustache", apiFolder, "api_client.rs")); + supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); + + supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.rs")); + supportingFiles.add(new SupportingFile("api_mod.mustache", apiFolder, "api.rs")); + supportingFiles.add(new SupportingFile("model_mod.mustache", modelFolder, "mod.rs")); + supportingFiles.add(new SupportingFile("lib.rs", "src", "lib.rs")); + supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml")); + } + + @Override + public String escapeReservedWord(String name) + { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return camelize(name) + '_'; + } + + @Override + public String apiFileFolder() { + return (outputFolder + File.separator + apiFolder).replaceAll("/", File.separator); + } + + public String modelFileFolder() { + return (outputFolder + File.separator + modelFolder).replaceAll("/", File.separator); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = sanitizeName(name.replaceAll("-", "_")); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // snake_case, e.g. PetId => pet_id + name = underscore(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name)) + name = escapeReservedWord(name); + + // for reserved word or word starting with number, append _ + if (name.matches("^\\d.*")) + name = "var_" + name; + + return name; + } + + @Override + public String toParamName(String name) { + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // camelize the model name + // phone_number => PhoneNumber + return camelize(toModelFilename(name)); + } + + @Override + public String toModelFilename(String name) { + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + name = sanitizeName(name); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + return underscore(name); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // e.g. PetApi.rs => pet_api.rs + return underscore(name) + "_api"; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[]" + getTypeDeclaration(inner); + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner); + } + //return super.getTypeDeclaration(p); + + // Not using the supertype invocation, because we want to UpperCamelize + // the type. + String swaggerType = getSwaggerType(p); + if (typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + + if(typeMapping.containsValue(swaggerType)) { + return swaggerType; + } + + if(languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + + return toModelName(swaggerType); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return (type); + } + else + type = swaggerType; + return type; + } + + @Override + public String toOperationId(String operationId) { + String sanitizedOperationId = sanitizeName(operationId); + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(sanitizedOperationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize("call_" + operationId)); + sanitizedOperationId = "call_" + sanitizedOperationId; + } + + return camelize(sanitizedOperationId); + } + + @Override + public Map postProcessOperations(Map objs) { + @SuppressWarnings("unchecked") + Map objectMap = (Map) objs.get("operations"); + @SuppressWarnings("unchecked") + List operations = (List) objectMap.get("operation"); + for (CodegenOperation operation : operations) { + // http method verb conversion (e.g. PUT => Put) + operation.httpMethod = camelize(operation.httpMethod.toLowerCase()); + } + + // remove model imports to avoid error + List> imports = (List>) objs.get("imports"); + if (imports == null) + return objs; + + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(apiPackage())) + iterator.remove(); + } + + // if their is a return type, import encoding/json + for (CodegenOperation operation : operations) { + if(operation.returnBaseType != null ) { + imports.add(createMapping("import", "encoding/json")); + break; //just need to import once + } + } + + // this will only import "fmt" if there are items in pathParams + for (CodegenOperation operation : operations) { + if(operation.pathParams != null && operation.pathParams.size() > 0) { + imports.add(createMapping("import", "fmt")); + break; //just need to import once + } + } + + // recursively add import for mapping one type to multiple imports + List> recursiveImports = (List>) objs.get("imports"); + if (recursiveImports == null) + return objs; + + ListIterator> listIterator = imports.listIterator(); + while (listIterator.hasNext()) { + String _import = listIterator.next().get("import"); + // if the import package happens to be found in the importMapping (key) + // add the corresponding import package to the list + if (importMapping.containsKey(_import)) { + listIterator.add(createMapping("import", importMapping.get(_import))); + } + } + + return objs; + } + + @Override + public Map postProcessModels(Map objs) { + // remove model imports to avoid error + List> imports = (List>) objs.get("imports"); + final String prefix = modelPackage(); + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(prefix)) + iterator.remove(); + } + + // recursively add import for mapping one type to multiple imports + List> recursiveImports = (List>) objs.get("imports"); + if (recursiveImports == null) + return objs; + + ListIterator> listIterator = imports.listIterator(); + while (listIterator.hasNext()) { + String _import = listIterator.next().get("import"); + // if the import package happens to be found in the importMapping (key) + // add the corresponding import package to the list + if (importMapping.containsKey(_import)) { + listIterator.add(createMapping("import", importMapping.get(_import))); + } + } + + return postProcessModelsEnum(objs); + } + + public Map createMapping(String key, String value){ + Map customImport = new HashMap(); + customImport.put(key, value); + + return customImport; + } + + @Override + protected boolean needToImport(String type) { + return !defaultIncludes.contains(type) + && !languageSpecificPrimitives.contains(type); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + + @Override + public String toEnumValue(String value, String datatype) { + if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + return value; + } else { + return escapeText(value); + } + } + + @Override + public String toEnumDefaultValue(String value, String datatype) { + return datatype + "_" + value; + } + + @Override + public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + + // number + if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + String varName = name; + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + return varName; + } + + // for symbol, e.g. $, # + if (getSymbolName(name) != null) { + return getSymbolName(name).toUpperCase(); + } + + // string + String enumName = sanitizeName(underscore(name).toUpperCase()); + enumName = enumName.replaceFirst("^_", ""); + enumName = enumName.replaceFirst("_$", ""); + + if (isReservedWord(enumName) || enumName.matches("\\d.*")) { // reserved word or starts with number + return escapeReservedWord(enumName); + } else { + return enumName; + } + } + + @Override + public String toEnumName(CodegenProperty property) { + String enumName = underscore(toModelName(property.name)).toUpperCase(); + + // remove [] for array or map of enum + enumName = enumName.replace("[]", ""); + + if (enumName.matches("\\d.*")) { // starts with number + return "_" + enumName; + } else { + return enumName; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index e0cd25f8358..432430a178a 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -52,6 +52,7 @@ io.swagger.codegen.languages.Qt5CPPGenerator io.swagger.codegen.languages.Rails5ServerCodegen io.swagger.codegen.languages.RestbedCodegen io.swagger.codegen.languages.RubyClientCodegen +io.swagger.codegen.languages.RustClientCodegen io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen io.swagger.codegen.languages.SilexServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/rust/.travis.yml b/modules/swagger-codegen/src/main/resources/rust/.travis.yml new file mode 100644 index 00000000000..f5cb2ce9a5a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache b/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache new file mode 100644 index 00000000000..560f8cc333b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache @@ -0,0 +1,17 @@ +[package] +name = "{{{pacakgeName}}}" +version = "{{{packageVersion}}}" +authors = ["Swagger Codegen team and contributors"] + +[dependencies] +serde = "*" +serde_derive = "*" +serde_yaml = "*" +serde_json = "*" +base64 = "*" +futures = "*" +hyper = "*" +url = "*" + +[dev-dependencies] +tokio-core = "*" diff --git a/modules/swagger-codegen/src/main/resources/rust/README.mustache b/modules/swagger-codegen/src/main/resources/rust/README.mustache new file mode 100644 index 00000000000..0e89ca61846 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/README.mustache @@ -0,0 +1,96 @@ +# Go API client for {{packageName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Installation +Put the package under your project folder and add the following in import: +``` + "./{{packageName}}" +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization +{{^authMethods}} Endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}} +## {{{name}}} +{{#isApiKey}}- **Type**: API key + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. + }) + r, err := client.Service.Operation(auth, args) +``` +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextBasicAuth, sw.BasicAuth{ + UserName: "username", + Password: "password", + }) + r, err := client.Service.Operation(auth, args) +``` +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING") + r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automaticly refresh tokens and perform user authentication. +``` + import "golang.org/x/oauth2" + + / .. Perform OAuth2 round trip request and obtain a token .. // + + tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) + auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) + r, err := client.Service.Operation(auth, args) +``` +{{/isOAuth}} +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache new file mode 100644 index 00000000000..a6f877e53cc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -0,0 +1,102 @@ +{{>partial_header}} +use std::rc::Rc; +use std::borrow::Borrow; + +use hyper; +use serde_json; +use futures; +use futures::{Future, Stream}; + +use super::{Error, configuration, models}; + +pub struct {{{classname}}}Impl { + configuration: Rc>, +} + +impl {{{classname}}}Impl { + pub fn new(configuration: Rc>) -> {{{classname}}}Impl { + {{{classname}}}Impl { + configuration: configuration, + } + } +} + +{{#operations}} +{{#operation}} +pub trait {{classname}} { + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>; +} +{{/operation}} +{{/operations}} + + +{{#operations}} +{{#operation}} +impl{{classname}} for {{classname}}Impl { + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{{datatype}}}{{/allParams}}) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::{{httpMethod}}, + format!("{}{{path}}", configuration.base_path).parse().unwrap()); + + {{#hasQueryParams}} + {{#queryParams}} + {{#required}} + // TODO query parameter {{baseName}}({{paramName}}) + {{/required}} + {{^required}} + // TODO query parameter {{baseName}}({{paramName}}) Optional + {{/required}} + {{/queryParams}} + {{/hasQueryParams}} + {{#hasHeaderParams}} + {{#headerParams}} + {{#required}} + // TODO header parameter {{baseName}}({{paramName}}) + {{/required}} + {{^required}} + // TODO header parameter {{baseName}}({{paramName}}) Optional + {{/required}} + {{/headerParams}} + {{/hasHeaderParams}} + {{#hasFormParams}} + {{#formParams}} + {{#isFile}} + {{^required}} + // TODO form parameter (file) {{baseName}}({{paramName}}) Optional + {{/required}} + {{/isFile}} + {{^isFile}} + {{#required}} + // TODO form parameter {{baseName}}({{paramName}}) + {{/required}} + {{^required}} + // TODO form parameter {{baseName}}({{paramName}}) Optional + {{/required}} + {{/isFile}} + {{/formParams}} + {{/hasFormParams}} + {{#hasBodyParam}} + {{#bodyParams}} + // body params + {{#required}} + let serialized = serde_json::to_string({{{paramName}}}).unwrap(); + req.headers_mut().set(hyper::header::ContentType::json()); + req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); + req.set_body(serialized); + + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) + {{/required}} + {{^required}} + // TODO optional body parameter + {{/required}} + {{/bodyParams}} + {{/hasBodyParam}} + } +} +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/rust/api_client.mustache b/modules/swagger-codegen/src/main/resources/rust/api_client.mustache new file mode 100644 index 00000000000..eac78242445 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/api_client.mustache @@ -0,0 +1,422 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "fmt" + "errors" + "io" + "mime/multipart" + "golang.org/x/oauth2" + "golang.org/x/net/context" + "net/http" + "net/url" + "time" + "os" + "path/filepath" + "reflect" + "regexp" + "strings" + "unicode/utf8" + "strconv" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") + xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") +) + +// APIClient manages communication with the {{appName}} API v{{version}} +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services +{{#apiInfo}} +{{#apis}} +{{#operations}} + {{classname}} *{{classname}}Service +{{/operations}} +{{/apis}} +{{/apiInfo}} +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + +{{#apiInfo}} + // API Services +{{#apis}} +{{#operations}} + c.{{classname}} = (*{{classname}}Service)(&c.common) +{{/operations}} +{{/apis}} +{{/apiInfo}} + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } + + return fmt.Sprintf("%v", obj) +} + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} + +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath (path string) { + c.cfg.BasePath = path +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest ( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form paramters and file if available. + if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + // Setup path and query paramters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + // Walk through any authentication. + if ctx != nil { + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer " + auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) (error) { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) (time.Time) { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) (int) { + return utf8.RuneCountInString(s) +} + diff --git a/modules/swagger-codegen/src/main/resources/rust/api_doc.mustache b/modules/swagger-codegen/src/main/resources/rust/api_doc.mustache new file mode 100644 index 00000000000..70d0b96ce86 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/api_doc.mustache @@ -0,0 +1,50 @@ +# {{invokerPackage}}\{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#authMethods}}ctx, {{/authMethods}}{{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}}) +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Required Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{#authMethods}} + **ctx** | **context.Context** | context containing the authentication | nil if no authentication{{/authMethods}}{{/-last}}{{/allParams}}{{#allParams}}{{#required}} + **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}} + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. +{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}} + **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/allParams}}{{/hasOptionalParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[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) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache new file mode 100644 index 00000000000..d5086f19668 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache @@ -0,0 +1,44 @@ +use hyper; +use serde_json; + +#[derive(Debug)] +pub enum Error { + Hyper(hyper::Error), + Serde(serde_json::Error), +} + +impl From for Error { + fn from(e: hyper::Error) -> Self { + return Error::Hyper(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + return Error::Serde(e) + } +} + +use super::models; + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#summary}} +//{{{summary}}} +{{/summary}} +mod {{classFilename}}_func; +pub use self::{{classFilename}}::{{{operationId}}}; +{{#-last}} + +mod {{classFilename}}_api; +pub use self::{{classFilename}}::{{classname}}; +{{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +pub mod configuration; +pub mod client; diff --git a/modules/swagger-codegen/src/main/resources/rust/api_response.mustache b/modules/swagger-codegen/src/main/resources/rust/api_response.mustache new file mode 100644 index 00000000000..00ab14a5124 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/api_response.mustache @@ -0,0 +1,35 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "net/http" +) + +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the swagger operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/modules/swagger-codegen/src/main/resources/rust/client.mustache b/modules/swagger-codegen/src/main/resources/rust/client.mustache new file mode 100644 index 00000000000..c5248ed8158 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/client.mustache @@ -0,0 +1,55 @@ +use std::rc::Rc; + +use hyper; +use super::configuration::Configuration; +use super::pet_api; + +pub struct APIClient { + configuration: Rc>, +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{classFilename}}: Box<{{classFilename}}::{{classname}}>, + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +} + +impl APIClient { + pub fn new(configuration: Configuration) -> APIClient { + let rc = Rc::new(configuration); + + APIClient { + configuration: rc.clone(), +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{classFilename}}: Box::new({{classFilename}}::{{classname}}Impl::new(rc.clone())), + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + } + } + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + pub fn {{classFilename}}(&self) -> &{{classFilename}}::{{classname}}{ + self.{{classFilename}}.as_ref() + } + +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +} diff --git a/modules/swagger-codegen/src/main/resources/rust/configuration.mustache b/modules/swagger-codegen/src/main/resources/rust/configuration.mustache new file mode 100644 index 00000000000..59e82af56b1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/configuration.mustache @@ -0,0 +1,16 @@ +{{>partial_header}} +use hyper; + +pub struct Configuration { + pub base_path: String, + pub client: hyper::client::Client, +} + +impl Configuration { + pub fn new(client: hyper::client::Client) -> Configuration { + Configuration { + base_path: "{{{basePath}}}".to_owned(), + client: client, + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/rust/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/rust/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/rust/gitignore.mustache b/modules/swagger-codegen/src/main/resources/rust/gitignore.mustache new file mode 100644 index 00000000000..6aa106405a4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/gitignore.mustache @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +Cargo.lock diff --git a/modules/swagger-codegen/src/main/resources/rust/lib.rs b/modules/swagger-codegen/src/main/resources/rust/lib.rs new file mode 100644 index 00000000000..2ad195c6fb1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/lib.rs @@ -0,0 +1,10 @@ +#[macro_use] +extern crate serde_derive; + +extern crate hyper; +extern crate serde_json; +extern crate futures; +extern crate url; + +pub mod apis; +pub mod models; diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache new file mode 100644 index 00000000000..02487be62a7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -0,0 +1,57 @@ +{{>partial_header}} +{{#models}} +{{#model}} +{{#description}} +// {{{classname}}} : {{{description}}} +{{/description}} + +#[derive(Debug, Serialize, Deserialize)] +pub struct {{classname}} { +{{#vars}} + {{#description}} + // {{{description}}} + {{/description}} + #[serde(rename = "{{baseName}}")] {{name}}: {{^required}}Option<{{/required}}{{{datatype}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} +{{/vars}} +} + +impl {{classname}} { + {{#description}} + // {{{description}}} + {{/description}} + pub fn new({{#requiredVars}}{{name}}: {{{datatype}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{classname}} { + {{classname}} { + {{#vars}} + {{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}Vec:new(){{/isListContainer}}{{#isMapContainer}}Hash:new(){{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} + {{/vars}} + } + } + + {{#vars}} + pub fn set_{{name}}(&mut self, {{name}}: {{{datatype}}}) { + self.{{name}} = Some({{name}}); + } + + pub fn with_{{name}}(mut self, {{name}}: {{{datatype}}}) -> {{classname}} { + self.{{name}} = Some({{name}}); + self + } + + {{/vars}} +} + +{{#isEnum}} +// TODO enum +// List of {{{name}}} +//const ( +// {{#allowableValues}} +// {{#enumVars}} +// {{name}} {{{classname}}} = "{{{value}}}" +// {{/enumVars}} +// {{/allowableValues}} +//) +{{/isEnum}} + + +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/rust/model_doc.mustache b/modules/swagger-codegen/src/main/resources/rust/model_doc.mustache new file mode 100644 index 00000000000..25537b2c5ed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/model_doc.mustache @@ -0,0 +1,11 @@ +{{#models}}{{#model}}# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{{datatype}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{^isContainer}}{{^isDateTime}}*{{/isDateTime}}{{/isContainer}}{{{datatype}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache new file mode 100644 index 00000000000..78d402893cb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache @@ -0,0 +1,6 @@ +{{#models}} +{{#model}} +mod {{{classname}}}; +pub use self::{{{classFilename}}}::{{{classname}}}; +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/rust/partial_header.mustache b/modules/swagger-codegen/src/main/resources/rust/partial_header.mustache new file mode 100644 index 00000000000..b655ebb8269 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/partial_header.mustache @@ -0,0 +1,13 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ diff --git a/samples/client/petstore/rust/.swagger-codegen-ignore b/samples/client/petstore/rust/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/rust/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/rust/.swagger-codegen/VERSION b/samples/client/petstore/rust/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/client/petstore/rust/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/.travis.yml b/samples/client/petstore/rust/.travis.yml new file mode 100644 index 00000000000..f5cb2ce9a5a --- /dev/null +++ b/samples/client/petstore/rust/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/client/petstore/rust/Cargo.toml b/samples/client/petstore/rust/Cargo.toml index 8c2c024a747..33f7fd35202 100644 --- a/samples/client/petstore/rust/Cargo.toml +++ b/samples/client/petstore/rust/Cargo.toml @@ -1,7 +1,7 @@ [package] -name = "petstore-client" -version = "0.1.0" -authors = ["Vladimir Pouzanov "] +name = "" +version = "1.0.0" +authors = ["Swagger Codegen team and contributors"] [dependencies] serde = "*" diff --git a/samples/client/petstore/rust/README.md b/samples/client/petstore/rust/README.md new file mode 100644 index 00000000000..32ad5365bdf --- /dev/null +++ b/samples/client/petstore/rust/README.md @@ -0,0 +1,97 @@ +# Go API client for swagger + +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: io.swagger.codegen.languages.RustClientCodegen + +## Installation +Put the package under your project folder and add the following in import: +``` + "./swagger" +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **Post** /pet | Add a new pet to the store +*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **Delete** /pet/{petId} | Deletes a pet +*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **Get** /pet/findByStatus | Finds Pets by status +*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **Get** /pet/findByTags | Finds Pets by tags +*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **Get** /pet/{petId} | Find pet by ID +*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **Put** /pet | Update an existing pet +*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **Post** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **Post** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **Delete** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **Get** /store/inventory | Returns pet inventories by status +*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **Get** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **Post** /store/order | Place an order for a pet +*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **Post** /user | Create user +*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **Post** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **Post** /user/createWithList | Creates list of users with given input array +*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **Delete** /user/{username} | Delete user +*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **Get** /user/{username} | Get user by user name +*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **Get** /user/login | Logs user into the system +*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **Get** /user/logout | Logs out current logged in user session +*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **Put** /user/{username} | Updated user + + +## Documentation For Models + + - [ApiResponse](docs/ApiResponse.md) + - [Category](docs/Category.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation For Authorization + +## api_key +- **Type**: API key + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. + }) + r, err := client.Service.Operation(auth, args) +``` +## petstore_auth +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING") + r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automaticly refresh tokens and perform user authentication. +``` + import "golang.org/x/oauth2" + + / .. Perform OAuth2 round trip request and obtain a token .. // + + tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) + auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) + r, err := client.Service.Operation(auth, args) +``` + +## Author + +apiteam@swagger.io + diff --git a/samples/client/petstore/rust/docs/ApiResponse.md b/samples/client/petstore/rust/docs/ApiResponse.md new file mode 100644 index 00000000000..96854847df7 --- /dev/null +++ b/samples/client/petstore/rust/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **i32** | | [optional] [default to null] +**Type_** | [***String**](String.md) | | [optional] [default to null] +**message** | [***String**](String.md) | | [optional] [default to null] + +[[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/client/petstore/rust/docs/Category.md b/samples/client/petstore/rust/docs/Category.md new file mode 100644 index 00000000000..5843acca301 --- /dev/null +++ b/samples/client/petstore/rust/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [optional] [default to null] +**name** | [***String**](String.md) | | [optional] [default to null] + +[[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/client/petstore/rust/docs/Order.md b/samples/client/petstore/rust/docs/Order.md new file mode 100644 index 00000000000..4221d13f4f5 --- /dev/null +++ b/samples/client/petstore/rust/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [optional] [default to null] +**pet_id** | **i64** | | [optional] [default to null] +**quantity** | **i32** | | [optional] [default to null] +**ship_date** | [**String**](String.md) | | [optional] [default to null] +**status** | [***String**](String.md) | Order Status | [optional] [default to null] +**complete** | **bool** | | [optional] [default to null] + +[[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/client/petstore/rust/docs/Pet.md b/samples/client/petstore/rust/docs/Pet.md new file mode 100644 index 00000000000..d62db6fea1e --- /dev/null +++ b/samples/client/petstore/rust/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [optional] [default to null] +**category** | [***Category**](Category.md) | | [optional] [default to null] +**name** | [***String**](String.md) | | [default to null] +**photo_urls** | [**[]String**](String.md) | | [default to null] +**tags** | [**[]Tag**](Tag.md) | | [optional] [default to null] +**status** | [***String**](String.md) | pet status in the store | [optional] [default to null] + +[[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/client/petstore/rust/docs/PetApi.md b/samples/client/petstore/rust/docs/PetApi.md new file mode 100644 index 00000000000..7f930cc1185 --- /dev/null +++ b/samples/client/petstore/rust/docs/PetApi.md @@ -0,0 +1,269 @@ +# \PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AddPet**](PetApi.md#AddPet) | **Post** /pet | Add a new pet to the store +[**DeletePet**](PetApi.md#DeletePet) | **Delete** /pet/{petId} | Deletes a pet +[**FindPetsByStatus**](PetApi.md#FindPetsByStatus) | **Get** /pet/findByStatus | Finds Pets by status +[**FindPetsByTags**](PetApi.md#FindPetsByTags) | **Get** /pet/findByTags | Finds Pets by tags +[**GetPetById**](PetApi.md#GetPetById) | **Get** /pet/{petId} | Find pet by ID +[**UpdatePet**](PetApi.md#UpdatePet) | **Put** /pet | Update an existing pet +[**UpdatePetWithForm**](PetApi.md#UpdatePetWithForm) | **Post** /pet/{petId} | Updates a pet in the store with form data +[**UploadFile**](PetApi.md#UploadFile) | **Post** /pet/{petId}/uploadImage | uploads an image + + +# **AddPet** +> AddPet(ctx, body) +Add a new pet to the store + + + +### Required Parameters + +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 | + +### Return type + + (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: 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) + +# **DeletePet** +> DeletePet(ctx, pet_id, optional) +Deletes a pet + + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet_id** | **i64**| Pet id to delete | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **i64**| Pet id to delete | + **api_key** | **String**| | + +### Return type + + (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **FindPetsByStatus** +> []Pet FindPetsByStatus(ctx, status) +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **status** | [**[]String**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**[]Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **FindPetsByTags** +> []Pet FindPetsByTags(ctx, tags) +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **tags** | [**[]String**](String.md)| Tags to filter by | + +### Return type + +[**[]Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **GetPetById** +> Pet GetPetById(ctx, pet_id) +Find pet by ID + +Returns a single pet + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet_id** | **i64**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **UpdatePet** +> UpdatePet(ctx, body) +Update an existing pet + + + +### Required Parameters + +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 | + +### Return type + + (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: 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) + +# **UpdatePetWithForm** +> UpdatePetWithForm(ctx, pet_id, optional) +Updates a pet in the store with form data + + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet_id** | **i64**| ID of pet that needs to be updated | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **i64**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | + **status** | **String**| Updated status of the pet | + +### Return type + + (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + +# **UploadFile** +> ApiResponse UploadFile(ctx, pet_id, optional) +uploads an image + + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **pet_id** | **i64**| ID of pet to update | + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet_id** | **i64**| ID of pet to update | + **additional_metadata** | **String**| Additional data to pass to server | + **file** | **File**| file to upload | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: 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/client/petstore/rust/docs/StoreApi.md b/samples/client/petstore/rust/docs/StoreApi.md new file mode 100644 index 00000000000..b3ab8232ef4 --- /dev/null +++ b/samples/client/petstore/rust/docs/StoreApi.md @@ -0,0 +1,117 @@ +# \StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DeleteOrder**](StoreApi.md#DeleteOrder) | **Delete** /store/order/{orderId} | Delete purchase order by ID +[**GetInventory**](StoreApi.md#GetInventory) | **Get** /store/inventory | Returns pet inventories by status +[**GetOrderById**](StoreApi.md#GetOrderById) | **Get** /store/order/{orderId} | Find purchase order by ID +[**PlaceOrder**](StoreApi.md#PlaceOrder) | **Post** /store/order | Place an order for a pet + + +# **DeleteOrder** +> DeleteOrder(order_id) +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **String**| ID of the order that needs to be deleted | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **GetInventory** +> map[string]i32 GetInventory(ctx, ) +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Required Parameters +This endpoint does not need any parameter. + +### Return type + +[**map[string]i32**](map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: 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) + +# **GetOrderById** +> Order GetOrderById(order_id) +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **i64**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **PlaceOrder** +> Order PlaceOrder(body) +Place an order for a pet + + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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/client/petstore/rust/docs/Tag.md b/samples/client/petstore/rust/docs/Tag.md new file mode 100644 index 00000000000..5c43d3701ac --- /dev/null +++ b/samples/client/petstore/rust/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [optional] [default to null] +**name** | [***String**](String.md) | | [optional] [default to null] + +[[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/client/petstore/rust/docs/User.md b/samples/client/petstore/rust/docs/User.md new file mode 100644 index 00000000000..bf3783d161a --- /dev/null +++ b/samples/client/petstore/rust/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **i64** | | [optional] [default to null] +**username** | [***String**](String.md) | | [optional] [default to null] +**first_name** | [***String**](String.md) | | [optional] [default to null] +**last_name** | [***String**](String.md) | | [optional] [default to null] +**email** | [***String**](String.md) | | [optional] [default to null] +**password** | [***String**](String.md) | | [optional] [default to null] +**phone** | [***String**](String.md) | | [optional] [default to null] +**user_status** | **i32** | User Status | [optional] [default to null] + +[[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/client/petstore/rust/docs/UserApi.md b/samples/client/petstore/rust/docs/UserApi.md new file mode 100644 index 00000000000..1444919a6da --- /dev/null +++ b/samples/client/petstore/rust/docs/UserApi.md @@ -0,0 +1,231 @@ +# \UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**CreateUser**](UserApi.md#CreateUser) | **Post** /user | Create user +[**CreateUsersWithArrayInput**](UserApi.md#CreateUsersWithArrayInput) | **Post** /user/createWithArray | Creates list of users with given input array +[**CreateUsersWithListInput**](UserApi.md#CreateUsersWithListInput) | **Post** /user/createWithList | Creates list of users with given input array +[**DeleteUser**](UserApi.md#DeleteUser) | **Delete** /user/{username} | Delete user +[**GetUserByName**](UserApi.md#GetUserByName) | **Get** /user/{username} | Get user by user name +[**LoginUser**](UserApi.md#LoginUser) | **Get** /user/login | Logs user into the system +[**LogoutUser**](UserApi.md#LogoutUser) | **Get** /user/logout | Logs out current logged in user session +[**UpdateUser**](UserApi.md#UpdateUser) | **Put** /user/{username} | Updated user + + +# **CreateUser** +> CreateUser(body) +Create user + +This can only be done by the logged in user. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **CreateUsersWithArrayInput** +> CreateUsersWithArrayInput(body) +Creates list of users with given input array + + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[]User**](User.md)| List of user object | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **CreateUsersWithListInput** +> CreateUsersWithListInput(body) +Creates list of users with given input array + + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[]User**](User.md)| List of user object | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **DeleteUser** +> DeleteUser(username) +Delete user + +This can only be done by the logged in user. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **GetUserByName** +> User GetUserByName(username) +Get user by user name + + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **LoginUser** +> String LoginUser(username, password) +Logs user into the system + + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +[**String**](String.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **LogoutUser** +> LogoutUser() +Logs out current logged in user session + + + +### Required Parameters +This endpoint does not need any parameter. + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **UpdateUser** +> UpdateUser(username, body) +Updated user + +This can only be done by the logged in user. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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/client/petstore/rust/git_push.sh b/samples/client/petstore/rust/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/rust/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/rust/src/apis/api.rs b/samples/client/petstore/rust/src/apis/api.rs new file mode 100644 index 00000000000..e0429480fd1 --- /dev/null +++ b/samples/client/petstore/rust/src/apis/api.rs @@ -0,0 +1,95 @@ +use hyper; +use serde_json; + +#[derive(Debug)] +pub enum Error { + Hyper(hyper::Error), + Serde(serde_json::Error), +} + +impl From for Error { + fn from(e: hyper::Error) -> Self { + return Error::Hyper(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + return Error::Serde(e) + } +} + +use super::models; + +//Add a new pet to the store +mod pet_api_func; +pub use self::pet_api::AddPet; +//Deletes a pet +mod pet_api_func; +pub use self::pet_api::DeletePet; +//Finds Pets by status +mod pet_api_func; +pub use self::pet_api::FindPetsByStatus; +//Finds Pets by tags +mod pet_api_func; +pub use self::pet_api::FindPetsByTags; +//Find pet by ID +mod pet_api_func; +pub use self::pet_api::GetPetById; +//Update an existing pet +mod pet_api_func; +pub use self::pet_api::UpdatePet; +//Updates a pet in the store with form data +mod pet_api_func; +pub use self::pet_api::UpdatePetWithForm; +//uploads an image +mod pet_api_func; +pub use self::pet_api::UploadFile; + +mod pet_api_api; +pub use self::pet_api::PetApi; +//Delete purchase order by ID +mod store_api_func; +pub use self::store_api::DeleteOrder; +//Returns pet inventories by status +mod store_api_func; +pub use self::store_api::GetInventory; +//Find purchase order by ID +mod store_api_func; +pub use self::store_api::GetOrderById; +//Place an order for a pet +mod store_api_func; +pub use self::store_api::PlaceOrder; + +mod store_api_api; +pub use self::store_api::StoreApi; +//Create user +mod user_api_func; +pub use self::user_api::CreateUser; +//Creates list of users with given input array +mod user_api_func; +pub use self::user_api::CreateUsersWithArrayInput; +//Creates list of users with given input array +mod user_api_func; +pub use self::user_api::CreateUsersWithListInput; +//Delete user +mod user_api_func; +pub use self::user_api::DeleteUser; +//Get user by user name +mod user_api_func; +pub use self::user_api::GetUserByName; +//Logs user into the system +mod user_api_func; +pub use self::user_api::LoginUser; +//Logs out current logged in user session +mod user_api_func; +pub use self::user_api::LogoutUser; +//Updated user +mod user_api_func; +pub use self::user_api::UpdateUser; + +mod user_api_api; +pub use self::user_api::UserApi; + +pub mod configuration; +pub mod client; diff --git a/samples/client/petstore/rust/src/apis/api_client.rs b/samples/client/petstore/rust/src/apis/api_client.rs new file mode 100644 index 00000000000..38ef3eb8066 --- /dev/null +++ b/samples/client/petstore/rust/src/apis/api_client.rs @@ -0,0 +1,423 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package swagger + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "fmt" + "errors" + "io" + "mime/multipart" + "golang.org/x/oauth2" + "golang.org/x/net/context" + "net/http" + "net/url" + "time" + "os" + "path/filepath" + "reflect" + "regexp" + "strings" + "unicode/utf8" + "strconv" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") + xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") +) + +// APIClient manages communication with the Swagger Petstore API v1.0.0 +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + PetApi *PetApiService + StoreApi *StoreApiService + UserApi *UserApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.PetApi = (*PetApiService)(&c.common) + c.StoreApi = (*StoreApiService)(&c.common) + c.UserApi = (*UserApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } + + return fmt.Sprintf("%v", obj) +} + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} + +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath (path string) { + c.cfg.BasePath = path +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest ( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form paramters and file if available. + if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + // Setup path and query paramters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + // Walk through any authentication. + if ctx != nil { + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer " + auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) (error) { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) (time.Time) { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) (int) { + return utf8.RuneCountInString(s) +} + diff --git a/samples/client/petstore/rust/src/apis/client.rs b/samples/client/petstore/rust/src/apis/client.rs index 606f0eba578..352bea11951 100644 --- a/samples/client/petstore/rust/src/apis/client.rs +++ b/samples/client/petstore/rust/src/apis/client.rs @@ -6,8 +6,9 @@ use super::pet_api; pub struct APIClient { configuration: Rc>, - - pet_api: Box, + pet_api: Box, + store_api: Box, + user_api: Box, } impl APIClient { @@ -16,11 +17,91 @@ impl APIClient { APIClient { configuration: rc.clone(), - pet_api: Box::new(pet_api::PetAPIImpl::new(rc.clone())), + pet_api: Box::new(pet_api::PetApiImpl::new(rc.clone())), + store_api: Box::new(store_api::StoreApiImpl::new(rc.clone())), + user_api: Box::new(user_api::UserApiImpl::new(rc.clone())), } } - pub fn pet_api(&self) -> &pet_api::PetAPI { + pub fn pet_api(&self) -> &pet_api::PetApi{ + self.pet_api.as_ref() + } + + pub fn pet_api(&self) -> &pet_api::PetApi{ + self.pet_api.as_ref() + } + + pub fn pet_api(&self) -> &pet_api::PetApi{ + self.pet_api.as_ref() + } + + pub fn pet_api(&self) -> &pet_api::PetApi{ + self.pet_api.as_ref() + } + + pub fn pet_api(&self) -> &pet_api::PetApi{ + self.pet_api.as_ref() + } + + pub fn pet_api(&self) -> &pet_api::PetApi{ + self.pet_api.as_ref() + } + + pub fn pet_api(&self) -> &pet_api::PetApi{ + self.pet_api.as_ref() + } + + pub fn pet_api(&self) -> &pet_api::PetApi{ self.pet_api.as_ref() } + + pub fn store_api(&self) -> &store_api::StoreApi{ + self.store_api.as_ref() + } + + pub fn store_api(&self) -> &store_api::StoreApi{ + self.store_api.as_ref() + } + + pub fn store_api(&self) -> &store_api::StoreApi{ + self.store_api.as_ref() + } + + pub fn store_api(&self) -> &store_api::StoreApi{ + self.store_api.as_ref() + } + + pub fn user_api(&self) -> &user_api::UserApi{ + self.user_api.as_ref() + } + + pub fn user_api(&self) -> &user_api::UserApi{ + self.user_api.as_ref() + } + + pub fn user_api(&self) -> &user_api::UserApi{ + self.user_api.as_ref() + } + + pub fn user_api(&self) -> &user_api::UserApi{ + self.user_api.as_ref() + } + + pub fn user_api(&self) -> &user_api::UserApi{ + self.user_api.as_ref() + } + + pub fn user_api(&self) -> &user_api::UserApi{ + self.user_api.as_ref() + } + + pub fn user_api(&self) -> &user_api::UserApi{ + self.user_api.as_ref() + } + + pub fn user_api(&self) -> &user_api::UserApi{ + self.user_api.as_ref() + } + + } diff --git a/samples/client/petstore/rust/src/apis/configuration.rs b/samples/client/petstore/rust/src/apis/configuration.rs index 25b4d645f3e..9ea9213594e 100644 --- a/samples/client/petstore/rust/src/apis/configuration.rs +++ b/samples/client/petstore/rust/src/apis/configuration.rs @@ -1,3 +1,13 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + use hyper; pub struct Configuration { @@ -8,7 +18,7 @@ pub struct Configuration { impl Configuration { pub fn new(client: hyper::client::Client) -> Configuration { Configuration { - base_path: "http://petstore.swagger.io:80/v2".to_owned(), + base_path: "http://petstore.swagger.io/v2".to_owned(), client: client, } } diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index d413b95664b..6f3f89d6b1f 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -1,3 +1,13 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + use std::rc::Rc; use std::borrow::Borrow; @@ -8,29 +18,53 @@ use futures::{Future, Stream}; use super::{Error, configuration, models}; -pub trait PetAPI { - fn add_pet(&self, pet: &models::Pet) -> Box>; -} - -pub struct PetAPIImpl { +pub struct PetApiImpl { configuration: Rc>, } -impl PetAPIImpl { - pub fn new(configuration: Rc>) -> PetAPIImpl { - PetAPIImpl { +impl PetApiImpl { + pub fn new(configuration: Rc>) -> PetApiImpl { + PetApiImpl { configuration: configuration, } } } -implPetAPI for PetAPIImpl { - fn add_pet(&self, pet: &models::Pet) -> Box> { +pub trait PetApi { + fn AddPet(&self, body: Pet) -> Box>; +} +pub trait PetApi { + fn DeletePet(&self, pet_id: i64, api_key: String) -> Box>; +} +pub trait PetApi { + fn FindPetsByStatus(&self, status: []String) -> Box>; +} +pub trait PetApi { + fn FindPetsByTags(&self, tags: []String) -> Box>; +} +pub trait PetApi { + fn GetPetById(&self, pet_id: i64) -> Box>; +} +pub trait PetApi { + fn UpdatePet(&self, body: Pet) -> Box>; +} +pub trait PetApi { + fn UpdatePetWithForm(&self, pet_id: i64, name: String, status: String) -> Box>; +} +pub trait PetApi { + fn UploadFile(&self, pet_id: i64, additional_metadata: String, file: File) -> Box>; +} + + +implPetApi for PetApiImpl { + fn AddPet(&self, body: ) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, format!("{}/pet", configuration.base_path).parse().unwrap()); - let serialized = serde_json::to_string(pet).unwrap(); + + // body params + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -42,3 +76,84 @@ implPetAPI for PetAPIImpl { ) } } +implPetApi for PetApiImpl { + fn DeletePet(&self, pet_id: api_key: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Delete, + format!("{}/pet/{petId}", configuration.base_path).parse().unwrap()); + + // TODO header parameter api_key(api_key) Optional + } +} +implPetApi for PetApiImpl { + fn FindPetsByStatus(&self, status: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Get, + format!("{}/pet/findByStatus", configuration.base_path).parse().unwrap()); + + // TODO query parameter status(status) + } +} +implPetApi for PetApiImpl { + fn FindPetsByTags(&self, tags: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Get, + format!("{}/pet/findByTags", configuration.base_path).parse().unwrap()); + + // TODO query parameter tags(tags) + } +} +implPetApi for PetApiImpl { + fn GetPetById(&self, pet_id: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Get, + format!("{}/pet/{petId}", configuration.base_path).parse().unwrap()); + + } +} +implPetApi for PetApiImpl { + fn UpdatePet(&self, body: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Put, + format!("{}/pet", configuration.base_path).parse().unwrap()); + + // body params + let serialized = serde_json::to_string(body).unwrap(); + req.headers_mut().set(hyper::header::ContentType::json()); + req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); + req.set_body(serialized); + + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) + } +} +implPetApi for PetApiImpl { + fn UpdatePetWithForm(&self, pet_id: name: status: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Post, + format!("{}/pet/{petId}", configuration.base_path).parse().unwrap()); + + // TODO form parameter name(name) Optional + // TODO form parameter status(status) Optional + } +} +implPetApi for PetApiImpl { + fn UploadFile(&self, pet_id: additional_metadata: file: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Post, + format!("{}/pet/{petId}/uploadImage", configuration.base_path).parse().unwrap()); + + // TODO form parameter additionalMetadata(additional_metadata) Optional + // TODO form parameter (file) file(file) Optional + } +} diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs new file mode 100644 index 00000000000..bb7002ce7c9 --- /dev/null +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -0,0 +1,93 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +use std::rc::Rc; +use std::borrow::Borrow; + +use hyper; +use serde_json; +use futures; +use futures::{Future, Stream}; + +use super::{Error, configuration, models}; + +pub struct StoreApiImpl { + configuration: Rc>, +} + +impl StoreApiImpl { + pub fn new(configuration: Rc>) -> StoreApiImpl { + StoreApiImpl { + configuration: configuration, + } + } +} + +pub trait StoreApi { + fn DeleteOrder(&self, order_id: String) -> Box>; +} +pub trait StoreApi { + fn GetInventory(&self, ) -> Box>; +} +pub trait StoreApi { + fn GetOrderById(&self, order_id: i64) -> Box>; +} +pub trait StoreApi { + fn PlaceOrder(&self, body: Order) -> Box>; +} + + +implStoreApi for StoreApiImpl { + fn DeleteOrder(&self, order_id: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Delete, + format!("{}/store/order/{orderId}", configuration.base_path).parse().unwrap()); + + } +} +implStoreApi for StoreApiImpl { + fn GetInventory(&self, ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Get, + format!("{}/store/inventory", configuration.base_path).parse().unwrap()); + + } +} +implStoreApi for StoreApiImpl { + fn GetOrderById(&self, order_id: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Get, + format!("{}/store/order/{orderId}", configuration.base_path).parse().unwrap()); + + } +} +implStoreApi for StoreApiImpl { + fn PlaceOrder(&self, body: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Post, + format!("{}/store/order", configuration.base_path).parse().unwrap()); + + // body params + let serialized = serde_json::to_string(body).unwrap(); + req.headers_mut().set(hyper::header::ContentType::json()); + req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); + req.set_body(serialized); + + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) + } +} diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs new file mode 100644 index 00000000000..8b2e76d711f --- /dev/null +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -0,0 +1,176 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +use std::rc::Rc; +use std::borrow::Borrow; + +use hyper; +use serde_json; +use futures; +use futures::{Future, Stream}; + +use super::{Error, configuration, models}; + +pub struct UserApiImpl { + configuration: Rc>, +} + +impl UserApiImpl { + pub fn new(configuration: Rc>) -> UserApiImpl { + UserApiImpl { + configuration: configuration, + } + } +} + +pub trait UserApi { + fn CreateUser(&self, body: User) -> Box>; +} +pub trait UserApi { + fn CreateUsersWithArrayInput(&self, body: []User) -> Box>; +} +pub trait UserApi { + fn CreateUsersWithListInput(&self, body: []User) -> Box>; +} +pub trait UserApi { + fn DeleteUser(&self, username: String) -> Box>; +} +pub trait UserApi { + fn GetUserByName(&self, username: String) -> Box>; +} +pub trait UserApi { + fn LoginUser(&self, username: String, password: String) -> Box>; +} +pub trait UserApi { + fn LogoutUser(&self, ) -> Box>; +} +pub trait UserApi { + fn UpdateUser(&self, username: String, body: User) -> Box>; +} + + +implUserApi for UserApiImpl { + fn CreateUser(&self, body: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Post, + format!("{}/user", configuration.base_path).parse().unwrap()); + + // body params + let serialized = serde_json::to_string(body).unwrap(); + req.headers_mut().set(hyper::header::ContentType::json()); + req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); + req.set_body(serialized); + + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) + } +} +implUserApi for UserApiImpl { + fn CreateUsersWithArrayInput(&self, body: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Post, + format!("{}/user/createWithArray", configuration.base_path).parse().unwrap()); + + // body params + let serialized = serde_json::to_string(body).unwrap(); + req.headers_mut().set(hyper::header::ContentType::json()); + req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); + req.set_body(serialized); + + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) + } +} +implUserApi for UserApiImpl { + fn CreateUsersWithListInput(&self, body: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Post, + format!("{}/user/createWithList", configuration.base_path).parse().unwrap()); + + // body params + let serialized = serde_json::to_string(body).unwrap(); + req.headers_mut().set(hyper::header::ContentType::json()); + req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); + req.set_body(serialized); + + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) + } +} +implUserApi for UserApiImpl { + fn DeleteUser(&self, username: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Delete, + format!("{}/user/{username}", configuration.base_path).parse().unwrap()); + + } +} +implUserApi for UserApiImpl { + fn GetUserByName(&self, username: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Get, + format!("{}/user/{username}", configuration.base_path).parse().unwrap()); + + } +} +implUserApi for UserApiImpl { + fn LoginUser(&self, username: password: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Get, + format!("{}/user/login", configuration.base_path).parse().unwrap()); + + // TODO query parameter username(username) + // TODO query parameter password(password) + } +} +implUserApi for UserApiImpl { + fn LogoutUser(&self, ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Get, + format!("{}/user/logout", configuration.base_path).parse().unwrap()); + + } +} +implUserApi for UserApiImpl { + fn UpdateUser(&self, username: body: ) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + let mut req = hyper::Request::new( + hyper::Method::Put, + format!("{}/user/{username}", configuration.base_path).parse().unwrap()); + + // body params + let serialized = serde_json::to_string(body).unwrap(); + req.headers_mut().set(hyper::header::ContentType::json()); + req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); + req.set_body(serialized); + + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) + } +} diff --git a/samples/client/petstore/rust/src/models/api_response.rs b/samples/client/petstore/rust/src/models/api_response.rs new file mode 100644 index 00000000000..a52d28cc6bf --- /dev/null +++ b/samples/client/petstore/rust/src/models/api_response.rs @@ -0,0 +1,60 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +// ApiResponse : Describes the result of uploading an image resource + +#[derive(Debug, Serialize, Deserialize)] +pub struct ApiResponse { + #[serde(rename = "code")] code: Option, + #[serde(rename = "type")] Type_: Option, + #[serde(rename = "message")] message: Option +} + +impl ApiResponse { + // Describes the result of uploading an image resource + pub fn new() -> ApiResponse { + ApiResponse { + code: None, + Type_: None, + message: None + } + } + + pub fn set_code(&mut self, code: i32) { + self.code = Some(code); + } + + pub fn with_code(mut self, code: i32) -> ApiResponse { + self.code = Some(code); + self + } + + pub fn set_Type_(&mut self, Type_: String) { + self.Type_ = Some(Type_); + } + + pub fn with_Type_(mut self, Type_: String) -> ApiResponse { + self.Type_ = Some(Type_); + self + } + + pub fn set_message(&mut self, message: String) { + self.message = Some(message); + } + + pub fn with_message(mut self, message: String) -> ApiResponse { + self.message = Some(message); + self + } + +} + + + diff --git a/samples/client/petstore/rust/src/models/category.rs b/samples/client/petstore/rust/src/models/category.rs index c69e9d147bb..0dc4ed24a9b 100644 --- a/samples/client/petstore/rust/src/models/category.rs +++ b/samples/client/petstore/rust/src/models/category.rs @@ -1,8 +1,49 @@ -/// Pet catehgry -/// -/// A category for a pet +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +// Category : A category for a pet + #[derive(Debug, Serialize, Deserialize)] pub struct Category { - id: Option, - name: Option, + #[serde(rename = "id")] id: Option, + #[serde(rename = "name")] name: Option } + +impl Category { + // A category for a pet + pub fn new() -> Category { + Category { + id: None, + name: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> Category { + self.id = Some(id); + self + } + + pub fn set_name(&mut self, name: String) { + self.name = Some(name); + } + + pub fn with_name(mut self, name: String) -> Category { + self.name = Some(name); + self + } + +} + + + diff --git a/samples/client/petstore/rust/src/models/mod.rs b/samples/client/petstore/rust/src/models/mod.rs index 4b8e81e42d6..0e3f0a77596 100644 --- a/samples/client/petstore/rust/src/models/mod.rs +++ b/samples/client/petstore/rust/src/models/mod.rs @@ -1,8 +1,12 @@ -mod pet; -pub use self::pet::Pet; - -mod category; +mod ApiResponse; +pub use self::api_response::ApiResponse; +mod Category; pub use self::category::Category; - -mod tag; +mod Order; +pub use self::order::Order; +mod Pet; +pub use self::pet::Pet; +mod Tag; pub use self::tag::Tag; +mod User; +pub use self::user::User; diff --git a/samples/client/petstore/rust/src/models/order.rs b/samples/client/petstore/rust/src/models/order.rs new file mode 100644 index 00000000000..857277fc081 --- /dev/null +++ b/samples/client/petstore/rust/src/models/order.rs @@ -0,0 +1,94 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +// Order : An order for a pets from the pet store + +#[derive(Debug, Serialize, Deserialize)] +pub struct Order { + #[serde(rename = "id")] id: Option, + #[serde(rename = "petId")] pet_id: Option, + #[serde(rename = "quantity")] quantity: Option, + #[serde(rename = "shipDate")] ship_date: Option, + // Order Status + #[serde(rename = "status")] status: Option, + #[serde(rename = "complete")] complete: Option +} + +impl Order { + // An order for a pets from the pet store + pub fn new() -> Order { + Order { + id: None, + pet_id: None, + quantity: None, + ship_date: None, + status: None, + complete: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> Order { + self.id = Some(id); + self + } + + pub fn set_pet_id(&mut self, pet_id: i64) { + self.pet_id = Some(pet_id); + } + + pub fn with_pet_id(mut self, pet_id: i64) -> Order { + self.pet_id = Some(pet_id); + self + } + + pub fn set_quantity(&mut self, quantity: i32) { + self.quantity = Some(quantity); + } + + pub fn with_quantity(mut self, quantity: i32) -> Order { + self.quantity = Some(quantity); + self + } + + pub fn set_ship_date(&mut self, ship_date: String) { + self.ship_date = Some(ship_date); + } + + pub fn with_ship_date(mut self, ship_date: String) -> Order { + self.ship_date = Some(ship_date); + self + } + + pub fn set_status(&mut self, status: String) { + self.status = Some(status); + } + + pub fn with_status(mut self, status: String) -> Order { + self.status = Some(status); + self + } + + pub fn set_complete(&mut self, complete: bool) { + self.complete = Some(complete); + } + + pub fn with_complete(mut self, complete: bool) -> Order { + self.complete = Some(complete); + self + } + +} + + + diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index c812a0dbccb..8623d999b70 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -1,25 +1,36 @@ -/// a Pet -/// -/// A pet for sale in the pet store +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +// Pet : A pet for sale in the pet store + #[derive(Debug, Serialize, Deserialize)] pub struct Pet { - id: Option, - category: Option, - name: String, - #[serde(rename = "photoUrls")] photo_urls: Vec, - tags: Vec, - status: Option, + #[serde(rename = "id")] id: Option, + #[serde(rename = "category")] category: Option, + #[serde(rename = "name")] name: String, + #[serde(rename = "photoUrls")] photo_urls: []String, + #[serde(rename = "tags")] tags: Option<[]Tag>, + // pet status in the store + #[serde(rename = "status")] status: Option } impl Pet { - pub fn new(name: String, photo_urls: Vec) -> Pet { + // A pet for sale in the pet store + pub fn new(name: String, photo_urls: []String) -> Pet { Pet { id: None, category: None, name: name, photo_urls: photo_urls, - tags: Vec::new(), - status: None, + tags: Vec:new(), + status: None } } @@ -31,4 +42,53 @@ impl Pet { self.id = Some(id); self } + + pub fn set_category(&mut self, category: Category) { + self.category = Some(category); + } + + pub fn with_category(mut self, category: Category) -> Pet { + self.category = Some(category); + self + } + + pub fn set_name(&mut self, name: String) { + self.name = Some(name); + } + + pub fn with_name(mut self, name: String) -> Pet { + self.name = Some(name); + self + } + + pub fn set_photo_urls(&mut self, photo_urls: []String) { + self.photo_urls = Some(photo_urls); + } + + pub fn with_photo_urls(mut self, photo_urls: []String) -> Pet { + self.photo_urls = Some(photo_urls); + self + } + + pub fn set_tags(&mut self, tags: []Tag) { + self.tags = Some(tags); + } + + pub fn with_tags(mut self, tags: []Tag) -> Pet { + self.tags = Some(tags); + self + } + + pub fn set_status(&mut self, status: String) { + self.status = Some(status); + } + + pub fn with_status(mut self, status: String) -> Pet { + self.status = Some(status); + self + } + } + + + diff --git a/samples/client/petstore/rust/src/models/tag.rs b/samples/client/petstore/rust/src/models/tag.rs index 2ebb742c8f7..f9f62346378 100644 --- a/samples/client/petstore/rust/src/models/tag.rs +++ b/samples/client/petstore/rust/src/models/tag.rs @@ -1,8 +1,49 @@ -/// Pet Tag -/// -/// A tag for a pet +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +// Tag : A tag for a pet + #[derive(Debug, Serialize, Deserialize)] pub struct Tag { - id: Option, - name: Option, + #[serde(rename = "id")] id: Option, + #[serde(rename = "name")] name: Option } + +impl Tag { + // A tag for a pet + pub fn new() -> Tag { + Tag { + id: None, + name: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> Tag { + self.id = Some(id); + self + } + + pub fn set_name(&mut self, name: String) { + self.name = Some(name); + } + + pub fn with_name(mut self, name: String) -> Tag { + self.name = Some(name); + self + } + +} + + + diff --git a/samples/client/petstore/rust/src/models/user.rs b/samples/client/petstore/rust/src/models/user.rs new file mode 100644 index 00000000000..0f61dad805a --- /dev/null +++ b/samples/client/petstore/rust/src/models/user.rs @@ -0,0 +1,116 @@ +/* + * Swagger Petstore + * + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +// User : A User who is purchasing from the pet store + +#[derive(Debug, Serialize, Deserialize)] +pub struct User { + #[serde(rename = "id")] id: Option, + #[serde(rename = "username")] username: Option, + #[serde(rename = "firstName")] first_name: Option, + #[serde(rename = "lastName")] last_name: Option, + #[serde(rename = "email")] email: Option, + #[serde(rename = "password")] password: Option, + #[serde(rename = "phone")] phone: Option, + // User Status + #[serde(rename = "userStatus")] user_status: Option +} + +impl User { + // A User who is purchasing from the pet store + pub fn new() -> User { + User { + id: None, + username: None, + first_name: None, + last_name: None, + email: None, + password: None, + phone: None, + user_status: None + } + } + + pub fn set_id(&mut self, id: i64) { + self.id = Some(id); + } + + pub fn with_id(mut self, id: i64) -> User { + self.id = Some(id); + self + } + + pub fn set_username(&mut self, username: String) { + self.username = Some(username); + } + + pub fn with_username(mut self, username: String) -> User { + self.username = Some(username); + self + } + + pub fn set_first_name(&mut self, first_name: String) { + self.first_name = Some(first_name); + } + + pub fn with_first_name(mut self, first_name: String) -> User { + self.first_name = Some(first_name); + self + } + + pub fn set_last_name(&mut self, last_name: String) { + self.last_name = Some(last_name); + } + + pub fn with_last_name(mut self, last_name: String) -> User { + self.last_name = Some(last_name); + self + } + + pub fn set_email(&mut self, email: String) { + self.email = Some(email); + } + + pub fn with_email(mut self, email: String) -> User { + self.email = Some(email); + self + } + + pub fn set_password(&mut self, password: String) { + self.password = Some(password); + } + + pub fn with_password(mut self, password: String) -> User { + self.password = Some(password); + self + } + + pub fn set_phone(&mut self, phone: String) { + self.phone = Some(phone); + } + + pub fn with_phone(mut self, phone: String) -> User { + self.phone = Some(phone); + self + } + + pub fn set_user_status(&mut self, user_status: i32) { + self.user_status = Some(user_status); + } + + pub fn with_user_status(mut self, user_status: i32) -> User { + self.user_status = Some(user_status); + self + } + +} + + + From 93ef7b071a59e270411ed2d7ac52d9c2871d5555 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 02:28:00 +0800 Subject: [PATCH 02/22] update based on feedback --- .../codegen/languages/RustClientCodegen.java | 101 +---- .../src/main/resources/rust/.travis.yml | 9 +- .../src/main/resources/rust/Cargo.mustache | 2 +- .../src/main/resources/rust/api.mustache | 33 +- .../main/resources/rust/api_client.mustache | 422 ------------------ .../src/main/resources/rust/api_mod.mustache | 6 +- .../main/resources/rust/api_response.mustache | 16 +- .../src/main/resources/rust/client.mustache | 2 + .../src/main/resources/rust/model.mustache | 32 +- .../main/resources/rust/model_mod.mustache | 2 +- samples/client/petstore/rust/.travis.yml | 9 +- samples/client/petstore/rust/Cargo.toml | 2 +- .../client/petstore/rust/docs/ApiResponse.md | 4 +- samples/client/petstore/rust/docs/Category.md | 2 +- samples/client/petstore/rust/docs/Order.md | 4 +- samples/client/petstore/rust/docs/Pet.md | 8 +- samples/client/petstore/rust/docs/PetApi.md | 12 +- samples/client/petstore/rust/docs/StoreApi.md | 4 +- samples/client/petstore/rust/docs/Tag.md | 2 +- samples/client/petstore/rust/docs/User.md | 12 +- samples/client/petstore/rust/docs/UserApi.md | 6 +- .../petstore/rust/src/apis/api_client.rs | 86 ++-- .../client/petstore/rust/src/apis/client.rs | 68 --- samples/client/petstore/rust/src/apis/mod.rs | 59 ++- .../client/petstore/rust/src/apis/pet_api.rs | 94 ++-- .../petstore/rust/src/apis/store_api.rs | 40 +- .../client/petstore/rust/src/apis/user_api.rs | 86 ++-- .../petstore/rust/src/models/api_response.rs | 4 +- .../petstore/rust/src/models/category.rs | 4 +- .../client/petstore/rust/src/models/mod.rs | 12 +- .../client/petstore/rust/src/models/order.rs | 6 +- .../client/petstore/rust/src/models/pet.rs | 32 +- .../client/petstore/rust/src/models/tag.rs | 4 +- .../client/petstore/rust/src/models/user.rs | 6 +- 34 files changed, 300 insertions(+), 891 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/rust/api_client.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index 984298914bd..8013862cbbc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -74,7 +74,7 @@ public RustClientCodegen() { "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f32", "f64", - "char", "bool") + "char", "bool", "String", "Vec") ); instantiationTypes.clear(); @@ -93,17 +93,15 @@ public RustClientCodegen() { typeMapping.put("date", "string"); typeMapping.put("DateTime", "String"); typeMapping.put("password", "String"); + // TODO what should 'file' mapped to typeMapping.put("file", "File"); - // map binary to string as a workaround - // the correct solution is to use []byte - typeMapping.put("binary", "String"); + typeMapping.put("binary", "Vec"); typeMapping.put("ByteArray", "String"); + // TODO what should 'object' mapped to typeMapping.put("object", "Object"); - importMapping = new HashMap(); - importMapping.put("time.Time", "time"); - importMapping.put("*os.File", "os"); - importMapping.put("os", "io/ioutil"); + // no need for rust + //importMapping = new HashMap(); cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Rust package name (convention: lowercase).") @@ -154,11 +152,10 @@ public void processOpts() { supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("configuration.mustache", apiFolder, "configuration.rs")); - supportingFiles.add(new SupportingFile("api_client.mustache", apiFolder, "api_client.rs")); supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.rs")); - supportingFiles.add(new SupportingFile("api_mod.mustache", apiFolder, "api.rs")); + supportingFiles.add(new SupportingFile("api_mod.mustache", apiFolder, "mod.rs")); supportingFiles.add(new SupportingFile("model_mod.mustache", modelFolder, "mod.rs")); supportingFiles.add(new SupportingFile("lib.rs", "src", "lib.rs")); supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml")); @@ -278,13 +275,13 @@ public String getTypeDeclaration(Property p) { if(p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); - return "[]" + getTypeDeclaration(inner); + return "Vec<" + getTypeDeclaration(inner) + ">"; } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string]" + getTypeDeclaration(inner); + return getSwaggerType(p) + "[TODO]" + getTypeDeclaration(inner); } //return super.getTypeDeclaration(p); @@ -344,89 +341,9 @@ public Map postProcessOperations(Map objs) { operation.httpMethod = camelize(operation.httpMethod.toLowerCase()); } - // remove model imports to avoid error - List> imports = (List>) objs.get("imports"); - if (imports == null) - return objs; - - Iterator> iterator = imports.iterator(); - while (iterator.hasNext()) { - String _import = iterator.next().get("import"); - if (_import.startsWith(apiPackage())) - iterator.remove(); - } - - // if their is a return type, import encoding/json - for (CodegenOperation operation : operations) { - if(operation.returnBaseType != null ) { - imports.add(createMapping("import", "encoding/json")); - break; //just need to import once - } - } - - // this will only import "fmt" if there are items in pathParams - for (CodegenOperation operation : operations) { - if(operation.pathParams != null && operation.pathParams.size() > 0) { - imports.add(createMapping("import", "fmt")); - break; //just need to import once - } - } - - // recursively add import for mapping one type to multiple imports - List> recursiveImports = (List>) objs.get("imports"); - if (recursiveImports == null) - return objs; - - ListIterator> listIterator = imports.listIterator(); - while (listIterator.hasNext()) { - String _import = listIterator.next().get("import"); - // if the import package happens to be found in the importMapping (key) - // add the corresponding import package to the list - if (importMapping.containsKey(_import)) { - listIterator.add(createMapping("import", importMapping.get(_import))); - } - } - return objs; } - @Override - public Map postProcessModels(Map objs) { - // remove model imports to avoid error - List> imports = (List>) objs.get("imports"); - final String prefix = modelPackage(); - Iterator> iterator = imports.iterator(); - while (iterator.hasNext()) { - String _import = iterator.next().get("import"); - if (_import.startsWith(prefix)) - iterator.remove(); - } - - // recursively add import for mapping one type to multiple imports - List> recursiveImports = (List>) objs.get("imports"); - if (recursiveImports == null) - return objs; - - ListIterator> listIterator = imports.listIterator(); - while (listIterator.hasNext()) { - String _import = listIterator.next().get("import"); - // if the import package happens to be found in the importMapping (key) - // add the corresponding import package to the list - if (importMapping.containsKey(_import)) { - listIterator.add(createMapping("import", importMapping.get(_import))); - } - } - - return postProcessModelsEnum(objs); - } - - public Map createMapping(String key, String value){ - Map customImport = new HashMap(); - customImport.put(key, value); - - return customImport; - } - @Override protected boolean needToImport(String type) { return !defaultIncludes.contains(type) diff --git a/modules/swagger-codegen/src/main/resources/rust/.travis.yml b/modules/swagger-codegen/src/main/resources/rust/.travis.yml index f5cb2ce9a5a..22761ba7ee1 100644 --- a/modules/swagger-codegen/src/main/resources/rust/.travis.yml +++ b/modules/swagger-codegen/src/main/resources/rust/.travis.yml @@ -1,8 +1 @@ -language: go - -install: - - go get -d -v . - -script: - - go build -v ./ - +language: rust diff --git a/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache b/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache index 560f8cc333b..614745d5088 100644 --- a/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache @@ -1,5 +1,5 @@ [package] -name = "{{{pacakgeName}}}" +name = "{{{packageName}}}" version = "{{{packageVersion}}}" authors = ["Swagger Codegen team and contributors"] diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index a6f877e53cc..24eb5c694f6 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -21,41 +21,41 @@ impl {{{classname}}}Impl { } } +pub trait {{classname}} { {{#operations}} {{#operation}} -pub trait {{classname}} { - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>; -} + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>; {{/operation}} {{/operations}} +} +impl{{classname}} for {{classname}}Impl { {{#operations}} {{#operation}} -impl{{classname}} for {{classname}}Impl { - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{{datatype}}}{{/allParams}}) -> Box> { + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{{dataType}}}{{/allParams}}) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::{{httpMethod}}, - format!("{}{{path}}", configuration.base_path).parse().unwrap()); + format!("{{path}}", configuration.base_path).parse().unwrap()); {{#hasQueryParams}} {{#queryParams}} {{#required}} - // TODO query parameter {{baseName}}({{paramName}}) + /// TODO query parameter {{baseName}}({{paramName}}) {{/required}} {{^required}} - // TODO query parameter {{baseName}}({{paramName}}) Optional + /// TODO query parameter {{baseName}}({{paramName}}) Optional {{/required}} {{/queryParams}} {{/hasQueryParams}} {{#hasHeaderParams}} {{#headerParams}} {{#required}} - // TODO header parameter {{baseName}}({{paramName}}) + /// TODO header parameter {{baseName}}({{paramName}}) {{/required}} {{^required}} - // TODO header parameter {{baseName}}({{paramName}}) Optional + /// TODO header parameter {{baseName}}({{paramName}}) Optional {{/required}} {{/headerParams}} {{/hasHeaderParams}} @@ -63,22 +63,22 @@ impl{{classname}} for {{classname}}Impl { {{#formParams}} {{#isFile}} {{^required}} - // TODO form parameter (file) {{baseName}}({{paramName}}) Optional + /// TODO form parameter (file) {{baseName}}({{paramName}}) Optional {{/required}} {{/isFile}} {{^isFile}} {{#required}} - // TODO form parameter {{baseName}}({{paramName}}) + /// TODO form parameter {{baseName}}({{paramName}}) {{/required}} {{^required}} - // TODO form parameter {{baseName}}({{paramName}}) Optional + /// TODO form parameter {{baseName}}({{paramName}}) Optional {{/required}} {{/isFile}} {{/formParams}} {{/hasFormParams}} {{#hasBodyParam}} {{#bodyParams}} - // body params + /// body params {{#required}} let serialized = serde_json::to_string({{{paramName}}}).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); @@ -92,11 +92,12 @@ impl{{classname}} for {{classname}}Impl { ) {{/required}} {{^required}} - // TODO optional body parameter + /// TODO optional body parameter {{/required}} {{/bodyParams}} {{/hasBodyParam}} } -} + {{/operation}} {{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/rust/api_client.mustache b/modules/swagger-codegen/src/main/resources/rust/api_client.mustache deleted file mode 100644 index eac78242445..00000000000 --- a/modules/swagger-codegen/src/main/resources/rust/api_client.mustache +++ /dev/null @@ -1,422 +0,0 @@ -{{>partial_header}} -package {{packageName}} - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "errors" - "io" - "mime/multipart" - "golang.org/x/oauth2" - "golang.org/x/net/context" - "net/http" - "net/url" - "time" - "os" - "path/filepath" - "reflect" - "regexp" - "strings" - "unicode/utf8" - "strconv" -) - -var ( - jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") - xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") -) - -// APIClient manages communication with the {{appName}} API v{{version}} -// In most cases there should be only one, shared, APIClient. -type APIClient struct { - cfg *Configuration - common service // Reuse a single struct instead of allocating one for each service on the heap. - - // API Services -{{#apiInfo}} -{{#apis}} -{{#operations}} - {{classname}} *{{classname}}Service -{{/operations}} -{{/apis}} -{{/apiInfo}} -} - -type service struct { - client *APIClient -} - -// NewAPIClient creates a new API client. Requires a userAgent string describing your application. -// optionally a custom http.Client to allow for advanced features such as caching. -func NewAPIClient(cfg *Configuration) *APIClient { - if cfg.HTTPClient == nil { - cfg.HTTPClient = http.DefaultClient - } - - c := &APIClient{} - c.cfg = cfg - c.common.client = c - -{{#apiInfo}} - // API Services -{{#apis}} -{{#operations}} - c.{{classname}} = (*{{classname}}Service)(&c.common) -{{/operations}} -{{/apis}} -{{/apiInfo}} - - return c -} - -func atoi(in string) (int, error) { - return strconv.Atoi(in) -} - - -// selectHeaderContentType select a content type from the available list. -func selectHeaderContentType(contentTypes []string) string { - if len(contentTypes) == 0 { - return "" - } - if contains(contentTypes, "application/json") { - return "application/json" - } - return contentTypes[0] // use the first content type specified in 'consumes' -} - -// selectHeaderAccept join all accept types and return -func selectHeaderAccept(accepts []string) string { - if len(accepts) == 0 { - return "" - } - - if contains(accepts, "application/json") { - return "application/json" - } - - return strings.Join(accepts, ",") -} - -// contains is a case insenstive match, finding needle in a haystack -func contains(haystack []string, needle string) bool { - for _, a := range haystack { - if strings.ToLower(a) == strings.ToLower(needle) { - return true - } - } - return false -} - -// Verify optional parameters are of the correct type. -func typeCheckParameter(obj interface{}, expected string, name string) error { - // Make sure there is an object. - if obj == nil { - return nil - } - - // Check the type is as expected. - if reflect.TypeOf(obj).String() != expected { - return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) - } - return nil -} - -// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. -func parameterToString(obj interface{}, collectionFormat string) string { - var delimiter string - - switch collectionFormat { - case "pipes": - delimiter = "|" - case "ssv": - delimiter = " " - case "tsv": - delimiter = "\t" - case "csv": - delimiter = "," - } - - if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") - } - - return fmt.Sprintf("%v", obj) -} - -// callAPI do the request. -func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { - return c.cfg.HTTPClient.Do(request) -} - -// Change base path to allow switching to mocks -func (c *APIClient) ChangeBasePath (path string) { - c.cfg.BasePath = path -} - -// prepareRequest build the request -func (c *APIClient) prepareRequest ( - ctx context.Context, - path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams url.Values, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { - - var body *bytes.Buffer - - // Detect postBody type and post. - if postBody != nil { - contentType := headerParams["Content-Type"] - if contentType == "" { - contentType = detectContentType(postBody) - headerParams["Content-Type"] = contentType - } - - body, err = setBody(postBody, contentType) - if err != nil { - return nil, err - } - } - - // add form paramters and file if available. - if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { - if body != nil { - return nil, errors.New("Cannot specify postBody and multipart form at the same time.") - } - body = &bytes.Buffer{} - w := multipart.NewWriter(body) - - for k, v := range formParams { - for _, iv := range v { - if strings.HasPrefix(k, "@") { // file - err = addFile(w, k[1:], iv) - if err != nil { - return nil, err - } - } else { // form value - w.WriteField(k, iv) - } - } - } - if len(fileBytes) > 0 && fileName != "" { - w.Boundary() - //_, fileNm := filepath.Split(fileName) - part, err := w.CreateFormFile("file", filepath.Base(fileName)) - if err != nil { - return nil, err - } - _, err = part.Write(fileBytes) - if err != nil { - return nil, err - } - // Set the Boundary in the Content-Type - headerParams["Content-Type"] = w.FormDataContentType() - } - - // Set Content-Length - headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) - w.Close() - } - - // Setup path and query paramters - url, err := url.Parse(path) - if err != nil { - return nil, err - } - - // Adding Query Param - query := url.Query() - for k, v := range queryParams { - for _, iv := range v { - query.Add(k, iv) - } - } - - // Encode the parameters. - url.RawQuery = query.Encode() - - // Generate a new request - if body != nil { - localVarRequest, err = http.NewRequest(method, url.String(), body) - } else { - localVarRequest, err = http.NewRequest(method, url.String(), nil) - } - if err != nil { - return nil, err - } - - // add header parameters, if any - if len(headerParams) > 0 { - headers := http.Header{} - for h, v := range headerParams { - headers.Set(h, v) - } - localVarRequest.Header = headers - } - - // Add the user agent to the request. - localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) - - // Walk through any authentication. - if ctx != nil { - // OAuth2 authentication - if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { - // We were able to grab an oauth2 token from the context - var latestToken *oauth2.Token - if latestToken, err = tok.Token(); err != nil { - return nil, err - } - - latestToken.SetAuthHeader(localVarRequest) - } - - // Basic HTTP Authentication - if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { - localVarRequest.SetBasicAuth(auth.UserName, auth.Password) - } - - // AccessToken Authentication - if auth, ok := ctx.Value(ContextAccessToken).(string); ok { - localVarRequest.Header.Add("Authorization", "Bearer " + auth) - } - } - - for header, value := range c.cfg.DefaultHeader { - localVarRequest.Header.Add(header, value) - } - - return localVarRequest, nil -} - - -// Add a file to the multipart request -func addFile(w *multipart.Writer, fieldName, path string) error { - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - - part, err := w.CreateFormFile(fieldName, filepath.Base(path)) - if err != nil { - return err - } - _, err = io.Copy(part, file) - - return err -} - -// Prevent trying to import "fmt" -func reportError(format string, a ...interface{}) (error) { - return fmt.Errorf(format, a...) -} - -// Set request body from an interface{} -func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { - if bodyBuf == nil { - bodyBuf = &bytes.Buffer{} - } - - if reader, ok := body.(io.Reader); ok { - _, err = bodyBuf.ReadFrom(reader) - } else if b, ok := body.([]byte); ok { - _, err = bodyBuf.Write(b) - } else if s, ok := body.(string); ok { - _, err = bodyBuf.WriteString(s) - } else if jsonCheck.MatchString(contentType) { - err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { - xml.NewEncoder(bodyBuf).Encode(body) - } - - if err != nil { - return nil, err - } - - if bodyBuf.Len() == 0 { - err = fmt.Errorf("Invalid body type %s\n", contentType) - return nil, err - } - return bodyBuf, nil -} - -// detectContentType method is used to figure out `Request.Body` content type for request header -func detectContentType(body interface{}) string { - contentType := "text/plain; charset=utf-8" - kind := reflect.TypeOf(body).Kind() - - switch kind { - case reflect.Struct, reflect.Map, reflect.Ptr: - contentType = "application/json; charset=utf-8" - case reflect.String: - contentType = "text/plain; charset=utf-8" - default: - if b, ok := body.([]byte); ok { - contentType = http.DetectContentType(b) - } else if kind == reflect.Slice { - contentType = "application/json; charset=utf-8" - } - } - - return contentType -} - - -// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go -type cacheControl map[string]string - -func parseCacheControl(headers http.Header) cacheControl { - cc := cacheControl{} - ccHeader := headers.Get("Cache-Control") - for _, part := range strings.Split(ccHeader, ",") { - part = strings.Trim(part, " ") - if part == "" { - continue - } - if strings.ContainsRune(part, '=') { - keyval := strings.Split(part, "=") - cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") - } else { - cc[part] = "" - } - } - return cc -} - -// CacheExpires helper function to determine remaining time before repeating a request. -func CacheExpires(r *http.Response) (time.Time) { - // Figure out when the cache expires. - var expires time.Time - now, err := time.Parse(time.RFC1123, r.Header.Get("date")) - if err != nil { - return time.Now() - } - respCacheControl := parseCacheControl(r.Header) - - if maxAge, ok := respCacheControl["max-age"]; ok { - lifetime, err := time.ParseDuration(maxAge + "s") - if err != nil { - expires = now - } - expires = now.Add(lifetime) - } else { - expiresHeader := r.Header.Get("Expires") - if expiresHeader != "" { - expires, err = time.Parse(time.RFC1123, expiresHeader) - if err != nil { - expires = now - } - } - } - return expires -} - -func strlen(s string) (int) { - return utf8.RuneCountInString(s) -} - diff --git a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache index d5086f19668..c60d10ec4f5 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache @@ -23,17 +23,17 @@ use super::models; {{#apiInfo}} {{#apis}} +mod {{classFilename}}; {{#operations}} {{#operation}} {{#summary}} -//{{{summary}}} +///{{{summary}}} {{/summary}} -mod {{classFilename}}_func; pub use self::{{classFilename}}::{{{operationId}}}; {{#-last}} -mod {{classFilename}}_api; pub use self::{{classFilename}}::{{classname}}; + {{/-last}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/rust/api_response.mustache b/modules/swagger-codegen/src/main/resources/rust/api_response.mustache index 00ab14a5124..73a4f0e9ef1 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api_response.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api_response.mustache @@ -8,17 +8,17 @@ import ( type APIResponse struct { *http.Response `json:"-"` Message string `json:"message,omitempty"` - // Operation is the name of the swagger operation. + /// Operation is the name of the swagger operation. Operation string `json:"operation,omitempty"` - // RequestURL is the request URL. This value is always available, even if the - // embedded *http.Response is nil. + /// RequestURL is the request URL. This value is always available, even if the + /// embedded *http.Response is nil. RequestURL string `json:"url,omitempty"` - // Method is the HTTP method used for the request. This value is always - // available, even if the embedded *http.Response is nil. + /// Method is the HTTP method used for the request. This value is always + /// available, even if the embedded *http.Response is nil. Method string `json:"method,omitempty"` - // Payload holds the contents of the response body (which may be nil or empty). - // This is provided here as the raw response.Body() reader will have already - // been drained. + /// Payload holds the contents of the response body (which may be nil or empty). + /// This is provided here as the raw response.Body() reader will have already + /// been drained. Payload []byte `json:"-"` } diff --git a/modules/swagger-codegen/src/main/resources/rust/client.mustache b/modules/swagger-codegen/src/main/resources/rust/client.mustache index c5248ed8158..d840b8a1684 100644 --- a/modules/swagger-codegen/src/main/resources/rust/client.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/client.mustache @@ -43,10 +43,12 @@ impl APIClient { {{#apis}} {{#operations}} {{#operation}} +{{#-last}} pub fn {{classFilename}}(&self) -> &{{classFilename}}::{{classname}}{ self.{{classFilename}}.as_ref() } +{{/-last}} {{/operation}} {{/operations}} {{/apis}} diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache index 02487be62a7..425628b71bf 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -2,38 +2,38 @@ {{#models}} {{#model}} {{#description}} -// {{{classname}}} : {{{description}}} +/// {{{classname}}} : {{{description}}} {{/description}} #[derive(Debug, Serialize, Deserialize)] pub struct {{classname}} { {{#vars}} {{#description}} - // {{{description}}} + /// {{{description}}} {{/description}} - #[serde(rename = "{{baseName}}")] {{name}}: {{^required}}Option<{{/required}}{{{datatype}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} + #[serde(rename = "{{baseName}}")] {{name}}: {{^required}}Option<{{/required}}{{^isPrimitiveType}}{{^isContainer}}super::{{/isContainer}}{{/isPrimitiveType}}{{{datatype}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} } impl {{classname}} { {{#description}} - // {{{description}}} + /// {{{description}}} {{/description}} pub fn new({{#requiredVars}}{{name}}: {{{datatype}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{classname}} { {{classname}} { {{#vars}} - {{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}Vec:new(){{/isListContainer}}{{#isMapContainer}}Hash:new(){{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} + {{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}Hash:new(){{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} } } {{#vars}} pub fn set_{{name}}(&mut self, {{name}}: {{{datatype}}}) { - self.{{name}} = Some({{name}}); + self.{{name}} = {{^required}}Some({{name}}){{/required}}{{#required}}{{name}}{{/required}}; } pub fn with_{{name}}(mut self, {{name}}: {{{datatype}}}) -> {{classname}} { - self.{{name}} = Some({{name}}); + self.{{name}} = {{^required}}Some({{name}}){{/required}}{{#required}}{{name}}{{/required}}; self } @@ -41,15 +41,15 @@ impl {{classname}} { } {{#isEnum}} -// TODO enum -// List of {{{name}}} -//const ( -// {{#allowableValues}} -// {{#enumVars}} -// {{name}} {{{classname}}} = "{{{value}}}" -// {{/enumVars}} -// {{/allowableValues}} -//) +/// TODO enum +/// List of {{{name}}} +///const ( +/// {{#allowableValues}} +/// {{#enumVars}} +/// {{name}} {{{classname}}} = "{{{value}}}" +/// {{/enumVars}} +/// {{/allowableValues}} +///) {{/isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache index 78d402893cb..daddc889b81 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache @@ -1,6 +1,6 @@ {{#models}} {{#model}} -mod {{{classname}}}; +mod {{{classFilename}}}; pub use self::{{{classFilename}}}::{{{classname}}}; {{/model}} {{/models}} diff --git a/samples/client/petstore/rust/.travis.yml b/samples/client/petstore/rust/.travis.yml index f5cb2ce9a5a..22761ba7ee1 100644 --- a/samples/client/petstore/rust/.travis.yml +++ b/samples/client/petstore/rust/.travis.yml @@ -1,8 +1 @@ -language: go - -install: - - go get -d -v . - -script: - - go build -v ./ - +language: rust diff --git a/samples/client/petstore/rust/Cargo.toml b/samples/client/petstore/rust/Cargo.toml index 33f7fd35202..ad18ef78781 100644 --- a/samples/client/petstore/rust/Cargo.toml +++ b/samples/client/petstore/rust/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "" +name = "swagger" version = "1.0.0" authors = ["Swagger Codegen team and contributors"] diff --git a/samples/client/petstore/rust/docs/ApiResponse.md b/samples/client/petstore/rust/docs/ApiResponse.md index 96854847df7..d9d362765f2 100644 --- a/samples/client/petstore/rust/docs/ApiResponse.md +++ b/samples/client/petstore/rust/docs/ApiResponse.md @@ -4,8 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **i32** | | [optional] [default to null] -**Type_** | [***String**](String.md) | | [optional] [default to null] -**message** | [***String**](String.md) | | [optional] [default to null] +**Type_** | **String** | | [optional] [default to null] +**message** | **String** | | [optional] [default to null] [[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/client/petstore/rust/docs/Category.md b/samples/client/petstore/rust/docs/Category.md index 5843acca301..6481bb566cd 100644 --- a/samples/client/petstore/rust/docs/Category.md +++ b/samples/client/petstore/rust/docs/Category.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **i64** | | [optional] [default to null] -**name** | [***String**](String.md) | | [optional] [default to null] +**name** | **String** | | [optional] [default to null] [[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/client/petstore/rust/docs/Order.md b/samples/client/petstore/rust/docs/Order.md index 4221d13f4f5..8a91ed5952a 100644 --- a/samples/client/petstore/rust/docs/Order.md +++ b/samples/client/petstore/rust/docs/Order.md @@ -6,8 +6,8 @@ Name | Type | Description | Notes **id** | **i64** | | [optional] [default to null] **pet_id** | **i64** | | [optional] [default to null] **quantity** | **i32** | | [optional] [default to null] -**ship_date** | [**String**](String.md) | | [optional] [default to null] -**status** | [***String**](String.md) | Order Status | [optional] [default to null] +**ship_date** | **String** | | [optional] [default to null] +**status** | **String** | Order Status | [optional] [default to null] **complete** | **bool** | | [optional] [default to null] [[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/client/petstore/rust/docs/Pet.md b/samples/client/petstore/rust/docs/Pet.md index d62db6fea1e..1ed8471002b 100644 --- a/samples/client/petstore/rust/docs/Pet.md +++ b/samples/client/petstore/rust/docs/Pet.md @@ -5,10 +5,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **i64** | | [optional] [default to null] **category** | [***Category**](Category.md) | | [optional] [default to null] -**name** | [***String**](String.md) | | [default to null] -**photo_urls** | [**[]String**](String.md) | | [default to null] -**tags** | [**[]Tag**](Tag.md) | | [optional] [default to null] -**status** | [***String**](String.md) | pet status in the store | [optional] [default to null] +**name** | **String** | | [default to null] +**photo_urls** | **Vec** | | [default to null] +**tags** | [**Vec**](Tag.md) | | [optional] [default to null] +**status** | **String** | pet status in the store | [optional] [default to null] [[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/client/petstore/rust/docs/PetApi.md b/samples/client/petstore/rust/docs/PetApi.md index 7f930cc1185..14ad460f06f 100644 --- a/samples/client/petstore/rust/docs/PetApi.md +++ b/samples/client/petstore/rust/docs/PetApi.md @@ -80,7 +80,7 @@ Name | Type | Description | Notes [[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) # **FindPetsByStatus** -> []Pet FindPetsByStatus(ctx, status) +> Vec FindPetsByStatus(ctx, status) Finds Pets by status Multiple status values can be provided with comma separated strings @@ -90,11 +90,11 @@ Multiple status values can be provided with comma separated strings Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **status** | [**[]String**](String.md)| Status values that need to be considered for filter | + **status** | [**Vec<String>**](String.md)| Status values that need to be considered for filter | ### Return type -[**[]Pet**](Pet.md) +[**Vec**](Pet.md) ### Authorization @@ -108,7 +108,7 @@ Name | Type | Description | Notes [[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) # **FindPetsByTags** -> []Pet FindPetsByTags(ctx, tags) +> Vec FindPetsByTags(ctx, tags) Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -118,11 +118,11 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **tags** | [**[]String**](String.md)| Tags to filter by | + **tags** | [**Vec<String>**](String.md)| Tags to filter by | ### Return type -[**[]Pet**](Pet.md) +[**Vec**](Pet.md) ### Authorization diff --git a/samples/client/petstore/rust/docs/StoreApi.md b/samples/client/petstore/rust/docs/StoreApi.md index b3ab8232ef4..8dca9d3cb6f 100644 --- a/samples/client/petstore/rust/docs/StoreApi.md +++ b/samples/client/petstore/rust/docs/StoreApi.md @@ -38,7 +38,7 @@ No authorization required [[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) # **GetInventory** -> map[string]i32 GetInventory(ctx, ) +> map[TODO]i32 GetInventory(ctx, ) Returns pet inventories by status Returns a map of status codes to quantities @@ -48,7 +48,7 @@ This endpoint does not need any parameter. ### Return type -[**map[string]i32**](map.md) +[**map[TODO]i32**](map.md) ### Authorization diff --git a/samples/client/petstore/rust/docs/Tag.md b/samples/client/petstore/rust/docs/Tag.md index 5c43d3701ac..9c69cde1e03 100644 --- a/samples/client/petstore/rust/docs/Tag.md +++ b/samples/client/petstore/rust/docs/Tag.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **i64** | | [optional] [default to null] -**name** | [***String**](String.md) | | [optional] [default to null] +**name** | **String** | | [optional] [default to null] [[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/client/petstore/rust/docs/User.md b/samples/client/petstore/rust/docs/User.md index bf3783d161a..d9b1f2a95b8 100644 --- a/samples/client/petstore/rust/docs/User.md +++ b/samples/client/petstore/rust/docs/User.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **i64** | | [optional] [default to null] -**username** | [***String**](String.md) | | [optional] [default to null] -**first_name** | [***String**](String.md) | | [optional] [default to null] -**last_name** | [***String**](String.md) | | [optional] [default to null] -**email** | [***String**](String.md) | | [optional] [default to null] -**password** | [***String**](String.md) | | [optional] [default to null] -**phone** | [***String**](String.md) | | [optional] [default to null] +**username** | **String** | | [optional] [default to null] +**first_name** | **String** | | [optional] [default to null] +**last_name** | **String** | | [optional] [default to null] +**email** | **String** | | [optional] [default to null] +**password** | **String** | | [optional] [default to null] +**phone** | **String** | | [optional] [default to null] **user_status** | **i32** | User Status | [optional] [default to null] [[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/client/petstore/rust/docs/UserApi.md b/samples/client/petstore/rust/docs/UserApi.md index 1444919a6da..b5acb681de7 100644 --- a/samples/client/petstore/rust/docs/UserApi.md +++ b/samples/client/petstore/rust/docs/UserApi.md @@ -51,7 +51,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[]User**](User.md)| List of user object | + **body** | [**Vec<User>**](User.md)| List of user object | ### Return type @@ -78,7 +78,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**[]User**](User.md)| List of user object | + **body** | [**Vec<User>**](User.md)| List of user object | ### Return type @@ -164,7 +164,7 @@ Name | Type | Description | Notes ### Return type -[**String**](String.md) +**String** ### Authorization diff --git a/samples/client/petstore/rust/src/apis/api_client.rs b/samples/client/petstore/rust/src/apis/api_client.rs index 38ef3eb8066..f629d8b8910 100644 --- a/samples/client/petstore/rust/src/apis/api_client.rs +++ b/samples/client/petstore/rust/src/apis/api_client.rs @@ -37,13 +37,13 @@ var ( xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") ) -// APIClient manages communication with the Swagger Petstore API v1.0.0 -// In most cases there should be only one, shared, APIClient. +/// APIClient manages communication with the Swagger Petstore API v1.0.0 +/// In most cases there should be only one, shared, APIClient. type APIClient struct { cfg *Configuration - common service // Reuse a single struct instead of allocating one for each service on the heap. + common service /// Reuse a single struct instead of allocating one for each service on the heap. - // API Services + /// API Services PetApi *PetApiService StoreApi *StoreApiService UserApi *UserApiService @@ -53,8 +53,8 @@ type service struct { client *APIClient } -// NewAPIClient creates a new API client. Requires a userAgent string describing your application. -// optionally a custom http.Client to allow for advanced features such as caching. +/// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +/// optionally a custom http.Client to allow for advanced features such as caching. func NewAPIClient(cfg *Configuration) *APIClient { if cfg.HTTPClient == nil { cfg.HTTPClient = http.DefaultClient @@ -64,7 +64,7 @@ func NewAPIClient(cfg *Configuration) *APIClient { c.cfg = cfg c.common.client = c - // API Services + /// API Services c.PetApi = (*PetApiService)(&c.common) c.StoreApi = (*StoreApiService)(&c.common) c.UserApi = (*UserApiService)(&c.common) @@ -77,7 +77,7 @@ func atoi(in string) (int, error) { } -// selectHeaderContentType select a content type from the available list. +/// selectHeaderContentType select a content type from the available list. func selectHeaderContentType(contentTypes []string) string { if len(contentTypes) == 0 { return "" @@ -85,10 +85,10 @@ func selectHeaderContentType(contentTypes []string) string { if contains(contentTypes, "application/json") { return "application/json" } - return contentTypes[0] // use the first content type specified in 'consumes' + return contentTypes[0] /// use the first content type specified in 'consumes' } -// selectHeaderAccept join all accept types and return +/// selectHeaderAccept join all accept types and return func selectHeaderAccept(accepts []string) string { if len(accepts) == 0 { return "" @@ -101,7 +101,7 @@ func selectHeaderAccept(accepts []string) string { return strings.Join(accepts, ",") } -// contains is a case insenstive match, finding needle in a haystack +/// contains is a case insenstive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { if strings.ToLower(a) == strings.ToLower(needle) { @@ -111,21 +111,21 @@ func contains(haystack []string, needle string) bool { return false } -// Verify optional parameters are of the correct type. +/// Verify optional parameters are of the correct type. func typeCheckParameter(obj interface{}, expected string, name string) error { - // Make sure there is an object. + /// Make sure there is an object. if obj == nil { return nil } - // Check the type is as expected. + /// Check the type is as expected. if reflect.TypeOf(obj).String() != expected { return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) } return nil } -// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +/// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. func parameterToString(obj interface{}, collectionFormat string) string { var delimiter string @@ -147,17 +147,17 @@ func parameterToString(obj interface{}, collectionFormat string) string { return fmt.Sprintf("%v", obj) } -// callAPI do the request. +/// callAPI do the request. func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { return c.cfg.HTTPClient.Do(request) } -// Change base path to allow switching to mocks +/// Change base path to allow switching to mocks func (c *APIClient) ChangeBasePath (path string) { c.cfg.BasePath = path } -// prepareRequest build the request +/// prepareRequest build the request func (c *APIClient) prepareRequest ( ctx context.Context, path string, method string, @@ -170,7 +170,7 @@ func (c *APIClient) prepareRequest ( var body *bytes.Buffer - // Detect postBody type and post. + /// Detect postBody type and post. if postBody != nil { contentType := headerParams["Content-Type"] if contentType == "" { @@ -184,7 +184,7 @@ func (c *APIClient) prepareRequest ( } } - // add form paramters and file if available. + /// add form paramters and file if available. if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") @@ -194,19 +194,19 @@ func (c *APIClient) prepareRequest ( for k, v := range formParams { for _, iv := range v { - if strings.HasPrefix(k, "@") { // file + if strings.HasPrefix(k, "@") { /// file err = addFile(w, k[1:], iv) if err != nil { return nil, err } - } else { // form value + } else { /// form value w.WriteField(k, iv) } } } if len(fileBytes) > 0 && fileName != "" { w.Boundary() - //_, fileNm := filepath.Split(fileName) + ///_, fileNm := filepath.Split(fileName) part, err := w.CreateFormFile("file", filepath.Base(fileName)) if err != nil { return nil, err @@ -215,22 +215,22 @@ func (c *APIClient) prepareRequest ( if err != nil { return nil, err } - // Set the Boundary in the Content-Type + /// Set the Boundary in the Content-Type headerParams["Content-Type"] = w.FormDataContentType() } - // Set Content-Length + /// Set Content-Length headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) w.Close() } - // Setup path and query paramters + /// Setup path and query paramters url, err := url.Parse(path) if err != nil { return nil, err } - // Adding Query Param + /// Adding Query Param query := url.Query() for k, v := range queryParams { for _, iv := range v { @@ -238,10 +238,10 @@ func (c *APIClient) prepareRequest ( } } - // Encode the parameters. + /// Encode the parameters. url.RawQuery = query.Encode() - // Generate a new request + /// Generate a new request if body != nil { localVarRequest, err = http.NewRequest(method, url.String(), body) } else { @@ -251,7 +251,7 @@ func (c *APIClient) prepareRequest ( return nil, err } - // add header parameters, if any + /// add header parameters, if any if len(headerParams) > 0 { headers := http.Header{} for h, v := range headerParams { @@ -260,14 +260,14 @@ func (c *APIClient) prepareRequest ( localVarRequest.Header = headers } - // Add the user agent to the request. + /// Add the user agent to the request. localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) - // Walk through any authentication. + /// Walk through any authentication. if ctx != nil { - // OAuth2 authentication + /// OAuth2 authentication if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { - // We were able to grab an oauth2 token from the context + /// We were able to grab an oauth2 token from the context var latestToken *oauth2.Token if latestToken, err = tok.Token(); err != nil { return nil, err @@ -276,12 +276,12 @@ func (c *APIClient) prepareRequest ( latestToken.SetAuthHeader(localVarRequest) } - // Basic HTTP Authentication + /// Basic HTTP Authentication if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { localVarRequest.SetBasicAuth(auth.UserName, auth.Password) } - // AccessToken Authentication + /// AccessToken Authentication if auth, ok := ctx.Value(ContextAccessToken).(string); ok { localVarRequest.Header.Add("Authorization", "Bearer " + auth) } @@ -295,7 +295,7 @@ func (c *APIClient) prepareRequest ( } -// Add a file to the multipart request +/// Add a file to the multipart request func addFile(w *multipart.Writer, fieldName, path string) error { file, err := os.Open(path) if err != nil { @@ -312,12 +312,12 @@ func addFile(w *multipart.Writer, fieldName, path string) error { return err } -// Prevent trying to import "fmt" +/// Prevent trying to import "fmt" func reportError(format string, a ...interface{}) (error) { return fmt.Errorf(format, a...) } -// Set request body from an interface{} +/// Set request body from an interface{} func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { bodyBuf = &bytes.Buffer{} @@ -346,7 +346,7 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e return bodyBuf, nil } -// detectContentType method is used to figure out `Request.Body` content type for request header +/// detectContentType method is used to figure out `Request.Body` content type for request header func detectContentType(body interface{}) string { contentType := "text/plain; charset=utf-8" kind := reflect.TypeOf(body).Kind() @@ -368,7 +368,7 @@ func detectContentType(body interface{}) string { } -// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +/// Ripped from https:///github.com/gregjones/httpcache/blob/master/httpcache.go type cacheControl map[string]string func parseCacheControl(headers http.Header) cacheControl { @@ -389,9 +389,9 @@ func parseCacheControl(headers http.Header) cacheControl { return cc } -// CacheExpires helper function to determine remaining time before repeating a request. +/// CacheExpires helper function to determine remaining time before repeating a request. func CacheExpires(r *http.Response) (time.Time) { - // Figure out when the cache expires. + /// Figure out when the cache expires. var expires time.Time now, err := time.Parse(time.RFC1123, r.Header.Get("date")) if err != nil { diff --git a/samples/client/petstore/rust/src/apis/client.rs b/samples/client/petstore/rust/src/apis/client.rs index 352bea11951..c239fc77a76 100644 --- a/samples/client/petstore/rust/src/apis/client.rs +++ b/samples/client/petstore/rust/src/apis/client.rs @@ -27,78 +27,10 @@ impl APIClient { self.pet_api.as_ref() } - pub fn pet_api(&self) -> &pet_api::PetApi{ - self.pet_api.as_ref() - } - - pub fn pet_api(&self) -> &pet_api::PetApi{ - self.pet_api.as_ref() - } - - pub fn pet_api(&self) -> &pet_api::PetApi{ - self.pet_api.as_ref() - } - - pub fn pet_api(&self) -> &pet_api::PetApi{ - self.pet_api.as_ref() - } - - pub fn pet_api(&self) -> &pet_api::PetApi{ - self.pet_api.as_ref() - } - - pub fn pet_api(&self) -> &pet_api::PetApi{ - self.pet_api.as_ref() - } - - pub fn pet_api(&self) -> &pet_api::PetApi{ - self.pet_api.as_ref() - } - - pub fn store_api(&self) -> &store_api::StoreApi{ - self.store_api.as_ref() - } - - pub fn store_api(&self) -> &store_api::StoreApi{ - self.store_api.as_ref() - } - pub fn store_api(&self) -> &store_api::StoreApi{ self.store_api.as_ref() } - pub fn store_api(&self) -> &store_api::StoreApi{ - self.store_api.as_ref() - } - - pub fn user_api(&self) -> &user_api::UserApi{ - self.user_api.as_ref() - } - - pub fn user_api(&self) -> &user_api::UserApi{ - self.user_api.as_ref() - } - - pub fn user_api(&self) -> &user_api::UserApi{ - self.user_api.as_ref() - } - - pub fn user_api(&self) -> &user_api::UserApi{ - self.user_api.as_ref() - } - - pub fn user_api(&self) -> &user_api::UserApi{ - self.user_api.as_ref() - } - - pub fn user_api(&self) -> &user_api::UserApi{ - self.user_api.as_ref() - } - - pub fn user_api(&self) -> &user_api::UserApi{ - self.user_api.as_ref() - } - pub fn user_api(&self) -> &user_api::UserApi{ self.user_api.as_ref() } diff --git a/samples/client/petstore/rust/src/apis/mod.rs b/samples/client/petstore/rust/src/apis/mod.rs index b1cba2957ef..3bbd5aa7148 100644 --- a/samples/client/petstore/rust/src/apis/mod.rs +++ b/samples/client/petstore/rust/src/apis/mod.rs @@ -21,17 +21,58 @@ impl From for Error { use super::models; -mod get_pet_by_id_api; -pub use self::get_pet_by_id_api::get_pet_by_id; +mod pet_api; +///Add a new pet to the store +pub use self::pet_api::AddPet; +///Deletes a pet +pub use self::pet_api::DeletePet; +///Finds Pets by status +pub use self::pet_api::FindPetsByStatus; +///Finds Pets by tags +pub use self::pet_api::FindPetsByTags; +///Find pet by ID +pub use self::pet_api::GetPetById; +///Update an existing pet +pub use self::pet_api::UpdatePet; +///Updates a pet in the store with form data +pub use self::pet_api::UpdatePetWithForm; +///uploads an image +pub use self::pet_api::UploadFile; + +pub use self::pet_api::PetApi; + +mod store_api; +///Delete purchase order by ID +pub use self::store_api::DeleteOrder; +///Returns pet inventories by status +pub use self::store_api::GetInventory; +///Find purchase order by ID +pub use self::store_api::GetOrderById; +///Place an order for a pet +pub use self::store_api::PlaceOrder; + +pub use self::store_api::StoreApi; -mod update_pet_with_form_api; -pub use self::update_pet_with_form_api::update_pet_with_form; +mod user_api; +///Create user +pub use self::user_api::CreateUser; +///Creates list of users with given input array +pub use self::user_api::CreateUsersWithArrayInput; +///Creates list of users with given input array +pub use self::user_api::CreateUsersWithListInput; +///Delete user +pub use self::user_api::DeleteUser; +///Get user by user name +pub use self::user_api::GetUserByName; +///Logs user into the system +pub use self::user_api::LoginUser; +///Logs out current logged in user session +pub use self::user_api::LogoutUser; +///Updated user +pub use self::user_api::UpdateUser; + +pub use self::user_api::UserApi; -mod add_pet_api; -pub use self::add_pet_api::add_pet; pub mod configuration; pub mod client; - -mod pet_api; -pub use self::pet_api::PetAPI; diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index 6f3f89d6b1f..be167baf734 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -32,38 +32,24 @@ impl PetApiImpl { pub trait PetApi { fn AddPet(&self, body: Pet) -> Box>; -} -pub trait PetApi { fn DeletePet(&self, pet_id: i64, api_key: String) -> Box>; -} -pub trait PetApi { - fn FindPetsByStatus(&self, status: []String) -> Box>; -} -pub trait PetApi { - fn FindPetsByTags(&self, tags: []String) -> Box>; -} -pub trait PetApi { - fn GetPetById(&self, pet_id: i64) -> Box>; -} -pub trait PetApi { + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>>; + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>>; + fn GetPetById(&self, pet_id: i64) -> Box>; fn UpdatePet(&self, body: Pet) -> Box>; -} -pub trait PetApi { fn UpdatePetWithForm(&self, pet_id: i64, name: String, status: String) -> Box>; -} -pub trait PetApi { - fn UploadFile(&self, pet_id: i64, additional_metadata: String, file: File) -> Box>; + fn UploadFile(&self, pet_id: i64, additional_metadata: String, file: File) -> Box>; } implPetApi for PetApiImpl { - fn AddPet(&self, body: ) -> Box> { + fn AddPet(&self, body: Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("{}/pet", configuration.base_path).parse().unwrap()); + format!("/pet", configuration.base_path).parse().unwrap()); - // body params + /// body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -75,54 +61,49 @@ implPetApi for PetApiImpl { .and_then(|_| futures::future::ok(())) ) } -} -implPetApi for PetApiImpl { - fn DeletePet(&self, pet_id: api_key: ) -> Box> { + + fn DeletePet(&self, pet_id: i64api_key: String) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, - format!("{}/pet/{petId}", configuration.base_path).parse().unwrap()); + format!("/pet/{petId}", configuration.base_path).parse().unwrap()); - // TODO header parameter api_key(api_key) Optional + /// TODO header parameter api_key(api_key) Optional } -} -implPetApi for PetApiImpl { - fn FindPetsByStatus(&self, status: ) -> Box> { + + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("{}/pet/findByStatus", configuration.base_path).parse().unwrap()); + format!("/pet/findByStatus", configuration.base_path).parse().unwrap()); - // TODO query parameter status(status) + /// TODO query parameter status(status) } -} -implPetApi for PetApiImpl { - fn FindPetsByTags(&self, tags: ) -> Box> { + + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("{}/pet/findByTags", configuration.base_path).parse().unwrap()); + format!("/pet/findByTags", configuration.base_path).parse().unwrap()); - // TODO query parameter tags(tags) + /// TODO query parameter tags(tags) } -} -implPetApi for PetApiImpl { - fn GetPetById(&self, pet_id: ) -> Box> { + + fn GetPetById(&self, pet_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("{}/pet/{petId}", configuration.base_path).parse().unwrap()); + format!("/pet/{petId}", configuration.base_path).parse().unwrap()); } -} -implPetApi for PetApiImpl { - fn UpdatePet(&self, body: ) -> Box> { + + fn UpdatePet(&self, body: Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Put, - format!("{}/pet", configuration.base_path).parse().unwrap()); + format!("/pet", configuration.base_path).parse().unwrap()); - // body params + /// body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -134,26 +115,25 @@ implPetApi for PetApiImpl { .and_then(|_| futures::future::ok(())) ) } -} -implPetApi for PetApiImpl { - fn UpdatePetWithForm(&self, pet_id: name: status: ) -> Box> { + + fn UpdatePetWithForm(&self, pet_id: i64name: Stringstatus: String) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("{}/pet/{petId}", configuration.base_path).parse().unwrap()); + format!("/pet/{petId}", configuration.base_path).parse().unwrap()); - // TODO form parameter name(name) Optional - // TODO form parameter status(status) Optional + /// TODO form parameter name(name) Optional + /// TODO form parameter status(status) Optional } -} -implPetApi for PetApiImpl { - fn UploadFile(&self, pet_id: additional_metadata: file: ) -> Box> { + + fn UploadFile(&self, pet_id: i64additional_metadata: Stringfile: File) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("{}/pet/{petId}/uploadImage", configuration.base_path).parse().unwrap()); + format!("/pet/{petId}/uploadImage", configuration.base_path).parse().unwrap()); - // TODO form parameter additionalMetadata(additional_metadata) Optional - // TODO form parameter (file) file(file) Optional + /// TODO form parameter additionalMetadata(additional_metadata) Optional + /// TODO form parameter (file) file(file) Optional } + } diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index bb7002ce7c9..387dd7cfbd8 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -32,53 +32,44 @@ impl StoreApiImpl { pub trait StoreApi { fn DeleteOrder(&self, order_id: String) -> Box>; -} -pub trait StoreApi { - fn GetInventory(&self, ) -> Box>; -} -pub trait StoreApi { - fn GetOrderById(&self, order_id: i64) -> Box>; -} -pub trait StoreApi { - fn PlaceOrder(&self, body: Order) -> Box>; + fn GetInventory(&self, ) -> Box>; + fn GetOrderById(&self, order_id: i64) -> Box>; + fn PlaceOrder(&self, body: Order) -> Box>; } implStoreApi for StoreApiImpl { - fn DeleteOrder(&self, order_id: ) -> Box> { + fn DeleteOrder(&self, order_id: String) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, - format!("{}/store/order/{orderId}", configuration.base_path).parse().unwrap()); + format!("/store/order/{orderId}", configuration.base_path).parse().unwrap()); } -} -implStoreApi for StoreApiImpl { - fn GetInventory(&self, ) -> Box> { + + fn GetInventory(&self, ) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("{}/store/inventory", configuration.base_path).parse().unwrap()); + format!("/store/inventory", configuration.base_path).parse().unwrap()); } -} -implStoreApi for StoreApiImpl { - fn GetOrderById(&self, order_id: ) -> Box> { + + fn GetOrderById(&self, order_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("{}/store/order/{orderId}", configuration.base_path).parse().unwrap()); + format!("/store/order/{orderId}", configuration.base_path).parse().unwrap()); } -} -implStoreApi for StoreApiImpl { - fn PlaceOrder(&self, body: ) -> Box> { + + fn PlaceOrder(&self, body: Order) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("{}/store/order", configuration.base_path).parse().unwrap()); + format!("/store/order", configuration.base_path).parse().unwrap()); - // body params + /// body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -90,4 +81,5 @@ implStoreApi for StoreApiImpl { .and_then(|_| futures::future::ok(())) ) } + } diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index 8b2e76d711f..f0b2e4d50ac 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -32,38 +32,24 @@ impl UserApiImpl { pub trait UserApi { fn CreateUser(&self, body: User) -> Box>; -} -pub trait UserApi { - fn CreateUsersWithArrayInput(&self, body: []User) -> Box>; -} -pub trait UserApi { - fn CreateUsersWithListInput(&self, body: []User) -> Box>; -} -pub trait UserApi { + fn CreateUsersWithArrayInput(&self, body: Vec) -> Box>; + fn CreateUsersWithListInput(&self, body: Vec) -> Box>; fn DeleteUser(&self, username: String) -> Box>; -} -pub trait UserApi { - fn GetUserByName(&self, username: String) -> Box>; -} -pub trait UserApi { - fn LoginUser(&self, username: String, password: String) -> Box>; -} -pub trait UserApi { + fn GetUserByName(&self, username: String) -> Box>; + fn LoginUser(&self, username: String, password: String) -> Box>; fn LogoutUser(&self, ) -> Box>; -} -pub trait UserApi { fn UpdateUser(&self, username: String, body: User) -> Box>; } implUserApi for UserApiImpl { - fn CreateUser(&self, body: ) -> Box> { + fn CreateUser(&self, body: User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("{}/user", configuration.base_path).parse().unwrap()); + format!("/user", configuration.base_path).parse().unwrap()); - // body params + /// body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -75,15 +61,14 @@ implUserApi for UserApiImpl { .and_then(|_| futures::future::ok(())) ) } -} -implUserApi for UserApiImpl { - fn CreateUsersWithArrayInput(&self, body: ) -> Box> { + + fn CreateUsersWithArrayInput(&self, body: Vec) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("{}/user/createWithArray", configuration.base_path).parse().unwrap()); + format!("/user/createWithArray", configuration.base_path).parse().unwrap()); - // body params + /// body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -95,15 +80,14 @@ implUserApi for UserApiImpl { .and_then(|_| futures::future::ok(())) ) } -} -implUserApi for UserApiImpl { - fn CreateUsersWithListInput(&self, body: ) -> Box> { + + fn CreateUsersWithListInput(&self, body: Vec) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("{}/user/createWithList", configuration.base_path).parse().unwrap()); + format!("/user/createWithList", configuration.base_path).parse().unwrap()); - // body params + /// body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -115,53 +99,48 @@ implUserApi for UserApiImpl { .and_then(|_| futures::future::ok(())) ) } -} -implUserApi for UserApiImpl { - fn DeleteUser(&self, username: ) -> Box> { + + fn DeleteUser(&self, username: String) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, - format!("{}/user/{username}", configuration.base_path).parse().unwrap()); + format!("/user/{username}", configuration.base_path).parse().unwrap()); } -} -implUserApi for UserApiImpl { - fn GetUserByName(&self, username: ) -> Box> { + + fn GetUserByName(&self, username: String) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("{}/user/{username}", configuration.base_path).parse().unwrap()); + format!("/user/{username}", configuration.base_path).parse().unwrap()); } -} -implUserApi for UserApiImpl { - fn LoginUser(&self, username: password: ) -> Box> { + + fn LoginUser(&self, username: Stringpassword: String) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("{}/user/login", configuration.base_path).parse().unwrap()); + format!("/user/login", configuration.base_path).parse().unwrap()); - // TODO query parameter username(username) - // TODO query parameter password(password) + /// TODO query parameter username(username) + /// TODO query parameter password(password) } -} -implUserApi for UserApiImpl { + fn LogoutUser(&self, ) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("{}/user/logout", configuration.base_path).parse().unwrap()); + format!("/user/logout", configuration.base_path).parse().unwrap()); } -} -implUserApi for UserApiImpl { - fn UpdateUser(&self, username: body: ) -> Box> { + + fn UpdateUser(&self, username: Stringbody: User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Put, - format!("{}/user/{username}", configuration.base_path).parse().unwrap()); + format!("/user/{username}", configuration.base_path).parse().unwrap()); - // body params + /// body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -173,4 +152,5 @@ implUserApi for UserApiImpl { .and_then(|_| futures::future::ok(())) ) } + } diff --git a/samples/client/petstore/rust/src/models/api_response.rs b/samples/client/petstore/rust/src/models/api_response.rs index a52d28cc6bf..d8272a6f64d 100644 --- a/samples/client/petstore/rust/src/models/api_response.rs +++ b/samples/client/petstore/rust/src/models/api_response.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// ApiResponse : Describes the result of uploading an image resource +/// ApiResponse : Describes the result of uploading an image resource #[derive(Debug, Serialize, Deserialize)] pub struct ApiResponse { @@ -18,7 +18,7 @@ pub struct ApiResponse { } impl ApiResponse { - // Describes the result of uploading an image resource + /// Describes the result of uploading an image resource pub fn new() -> ApiResponse { ApiResponse { code: None, diff --git a/samples/client/petstore/rust/src/models/category.rs b/samples/client/petstore/rust/src/models/category.rs index 0dc4ed24a9b..39c4979e5f9 100644 --- a/samples/client/petstore/rust/src/models/category.rs +++ b/samples/client/petstore/rust/src/models/category.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// Category : A category for a pet +/// Category : A category for a pet #[derive(Debug, Serialize, Deserialize)] pub struct Category { @@ -17,7 +17,7 @@ pub struct Category { } impl Category { - // A category for a pet + /// A category for a pet pub fn new() -> Category { Category { id: None, diff --git a/samples/client/petstore/rust/src/models/mod.rs b/samples/client/petstore/rust/src/models/mod.rs index 0e3f0a77596..b4495b6a5fc 100644 --- a/samples/client/petstore/rust/src/models/mod.rs +++ b/samples/client/petstore/rust/src/models/mod.rs @@ -1,12 +1,12 @@ -mod ApiResponse; +mod api_response; pub use self::api_response::ApiResponse; -mod Category; +mod category; pub use self::category::Category; -mod Order; +mod order; pub use self::order::Order; -mod Pet; +mod pet; pub use self::pet::Pet; -mod Tag; +mod tag; pub use self::tag::Tag; -mod User; +mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/src/models/order.rs b/samples/client/petstore/rust/src/models/order.rs index 857277fc081..c012ed37fde 100644 --- a/samples/client/petstore/rust/src/models/order.rs +++ b/samples/client/petstore/rust/src/models/order.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// Order : An order for a pets from the pet store +/// Order : An order for a pets from the pet store #[derive(Debug, Serialize, Deserialize)] pub struct Order { @@ -16,13 +16,13 @@ pub struct Order { #[serde(rename = "petId")] pet_id: Option, #[serde(rename = "quantity")] quantity: Option, #[serde(rename = "shipDate")] ship_date: Option, - // Order Status + /// Order Status #[serde(rename = "status")] status: Option, #[serde(rename = "complete")] complete: Option } impl Order { - // An order for a pets from the pet store + /// An order for a pets from the pet store pub fn new() -> Order { Order { id: None, diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index 8623d999b70..246ecbf0845 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -8,28 +8,28 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// Pet : A pet for sale in the pet store +/// Pet : A pet for sale in the pet store #[derive(Debug, Serialize, Deserialize)] pub struct Pet { #[serde(rename = "id")] id: Option, - #[serde(rename = "category")] category: Option, + #[serde(rename = "category")] category: Option, #[serde(rename = "name")] name: String, - #[serde(rename = "photoUrls")] photo_urls: []String, - #[serde(rename = "tags")] tags: Option<[]Tag>, - // pet status in the store + #[serde(rename = "photoUrls")] photo_urls: Vec, + #[serde(rename = "tags")] tags: Option>, + /// pet status in the store #[serde(rename = "status")] status: Option } impl Pet { - // A pet for sale in the pet store - pub fn new(name: String, photo_urls: []String) -> Pet { + /// A pet for sale in the pet store + pub fn new(name: String, photo_urls: Vec) -> Pet { Pet { id: None, category: None, name: name, photo_urls: photo_urls, - tags: Vec:new(), + tags: None, status: None } } @@ -53,28 +53,28 @@ impl Pet { } pub fn set_name(&mut self, name: String) { - self.name = Some(name); + self.name = name; } pub fn with_name(mut self, name: String) -> Pet { - self.name = Some(name); + self.name = name; self } - pub fn set_photo_urls(&mut self, photo_urls: []String) { - self.photo_urls = Some(photo_urls); + pub fn set_photo_urls(&mut self, photo_urls: Vec) { + self.photo_urls = photo_urls; } - pub fn with_photo_urls(mut self, photo_urls: []String) -> Pet { - self.photo_urls = Some(photo_urls); + pub fn with_photo_urls(mut self, photo_urls: Vec) -> Pet { + self.photo_urls = photo_urls; self } - pub fn set_tags(&mut self, tags: []Tag) { + pub fn set_tags(&mut self, tags: Vec) { self.tags = Some(tags); } - pub fn with_tags(mut self, tags: []Tag) -> Pet { + pub fn with_tags(mut self, tags: Vec) -> Pet { self.tags = Some(tags); self } diff --git a/samples/client/petstore/rust/src/models/tag.rs b/samples/client/petstore/rust/src/models/tag.rs index f9f62346378..1ac30f30788 100644 --- a/samples/client/petstore/rust/src/models/tag.rs +++ b/samples/client/petstore/rust/src/models/tag.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// Tag : A tag for a pet +/// Tag : A tag for a pet #[derive(Debug, Serialize, Deserialize)] pub struct Tag { @@ -17,7 +17,7 @@ pub struct Tag { } impl Tag { - // A tag for a pet + /// A tag for a pet pub fn new() -> Tag { Tag { id: None, diff --git a/samples/client/petstore/rust/src/models/user.rs b/samples/client/petstore/rust/src/models/user.rs index 0f61dad805a..c6848bb0f32 100644 --- a/samples/client/petstore/rust/src/models/user.rs +++ b/samples/client/petstore/rust/src/models/user.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// User : A User who is purchasing from the pet store +/// User : A User who is purchasing from the pet store #[derive(Debug, Serialize, Deserialize)] pub struct User { @@ -19,12 +19,12 @@ pub struct User { #[serde(rename = "email")] email: Option, #[serde(rename = "password")] password: Option, #[serde(rename = "phone")] phone: Option, - // User Status + /// User Status #[serde(rename = "userStatus")] user_status: Option } impl User { - // A User who is purchasing from the pet store + /// A User who is purchasing from the pet store pub fn new() -> User { User { id: None, From 1d35a5e6c42104f694174ce56c6cf51c8c902a56 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 02:36:11 +0800 Subject: [PATCH 03/22] fix reserved keyword --- .../swagger/codegen/languages/RustClientCodegen.java | 2 +- samples/client/petstore/rust/docs/ApiResponse.md | 2 +- .../client/petstore/rust/src/models/api_response.rs | 12 ++++++------ 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index 8013862cbbc..2e2c421fdf7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -167,7 +167,7 @@ public String escapeReservedWord(String name) if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } - return camelize(name) + '_'; + return '_' + name; } @Override diff --git a/samples/client/petstore/rust/docs/ApiResponse.md b/samples/client/petstore/rust/docs/ApiResponse.md index d9d362765f2..a34664707bd 100644 --- a/samples/client/petstore/rust/docs/ApiResponse.md +++ b/samples/client/petstore/rust/docs/ApiResponse.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **i32** | | [optional] [default to null] -**Type_** | **String** | | [optional] [default to null] +**_type** | **String** | | [optional] [default to null] **message** | **String** | | [optional] [default to null] [[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/client/petstore/rust/src/models/api_response.rs b/samples/client/petstore/rust/src/models/api_response.rs index d8272a6f64d..47bf363daa0 100644 --- a/samples/client/petstore/rust/src/models/api_response.rs +++ b/samples/client/petstore/rust/src/models/api_response.rs @@ -13,7 +13,7 @@ #[derive(Debug, Serialize, Deserialize)] pub struct ApiResponse { #[serde(rename = "code")] code: Option, - #[serde(rename = "type")] Type_: Option, + #[serde(rename = "type")] _type: Option, #[serde(rename = "message")] message: Option } @@ -22,7 +22,7 @@ impl ApiResponse { pub fn new() -> ApiResponse { ApiResponse { code: None, - Type_: None, + _type: None, message: None } } @@ -36,12 +36,12 @@ impl ApiResponse { self } - pub fn set_Type_(&mut self, Type_: String) { - self.Type_ = Some(Type_); + pub fn set__type(&mut self, _type: String) { + self._type = Some(_type); } - pub fn with_Type_(mut self, Type_: String) -> ApiResponse { - self.Type_ = Some(Type_); + pub fn with__type(mut self, _type: String) -> ApiResponse { + self._type = Some(_type); self } From e220a778e3b31a03075dcf33c33703a9698e0099 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 02:40:07 +0800 Subject: [PATCH 04/22] fix string parameter --- .../swagger-codegen/src/main/resources/rust/api.mustache | 2 +- samples/client/petstore/rust/src/apis/pet_api.rs | 6 +++--- samples/client/petstore/rust/src/apis/store_api.rs | 2 +- samples/client/petstore/rust/src/apis/user_api.rs | 8 ++++---- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 24eb5c694f6..0b9c6946e49 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -33,7 +33,7 @@ pub trait {{classname}} { impl{{classname}} for {{classname}}Impl { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{{dataType}}}{{/allParams}}) -> Box> { + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::{{httpMethod}}, diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index be167baf734..ffddee86e07 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -62,7 +62,7 @@ implPetApi for PetApiImpl { ) } - fn DeletePet(&self, pet_id: i64api_key: String) -> Box> { + fn DeletePet(&self, pet_id: i64, api_key: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, @@ -116,7 +116,7 @@ implPetApi for PetApiImpl { ) } - fn UpdatePetWithForm(&self, pet_id: i64name: Stringstatus: String) -> Box> { + fn UpdatePetWithForm(&self, pet_id: i64, name: &str, status: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, @@ -126,7 +126,7 @@ implPetApi for PetApiImpl { /// TODO form parameter status(status) Optional } - fn UploadFile(&self, pet_id: i64additional_metadata: Stringfile: File) -> Box> { + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index 387dd7cfbd8..9332fd39578 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -39,7 +39,7 @@ pub trait StoreApi { implStoreApi for StoreApiImpl { - fn DeleteOrder(&self, order_id: String) -> Box> { + fn DeleteOrder(&self, order_id: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index f0b2e4d50ac..5b634112a35 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -100,7 +100,7 @@ implUserApi for UserApiImpl { ) } - fn DeleteUser(&self, username: String) -> Box> { + fn DeleteUser(&self, username: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, @@ -108,7 +108,7 @@ implUserApi for UserApiImpl { } - fn GetUserByName(&self, username: String) -> Box> { + fn GetUserByName(&self, username: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, @@ -116,7 +116,7 @@ implUserApi for UserApiImpl { } - fn LoginUser(&self, username: Stringpassword: String) -> Box> { + fn LoginUser(&self, username: &str, password: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, @@ -134,7 +134,7 @@ implUserApi for UserApiImpl { } - fn UpdateUser(&self, username: Stringbody: User) -> Box> { + fn UpdateUser(&self, username: &str, body: User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Put, From 9b50d2e350580759e2a4c40682f9e7df5cee2443 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 12:54:15 +0800 Subject: [PATCH 05/22] update returntype in method signature --- .../codegen/languages/RustClientCodegen.java | 15 +++++++ .../src/main/resources/rust/api.mustache | 22 +++++----- .../src/main/resources/rust/api_mod.mustache | 4 -- .../main/resources/rust/api_response.mustache | 35 ---------------- .../src/main/resources/rust/model.mustache | 24 +++++------ samples/client/petstore/rust/src/apis/mod.rs | 40 ------------------ .../client/petstore/rust/src/apis/pet_api.rs | 42 +++++++++---------- .../petstore/rust/src/apis/store_api.rs | 16 +++---- .../client/petstore/rust/src/apis/user_api.rs | 32 +++++++------- .../petstore/rust/src/models/api_response.rs | 4 +- .../petstore/rust/src/models/category.rs | 4 +- .../client/petstore/rust/src/models/order.rs | 6 +-- .../client/petstore/rust/src/models/pet.rs | 6 +-- .../client/petstore/rust/src/models/tag.rs | 4 +- .../client/petstore/rust/src/models/user.rs | 6 +-- 15 files changed, 98 insertions(+), 162 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/rust/api_response.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index 2e2c421fdf7..8b0bdbd33f3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -339,6 +339,21 @@ public Map postProcessOperations(Map objs) { for (CodegenOperation operation : operations) { // http method verb conversion (e.g. PUT => Put) operation.httpMethod = camelize(operation.httpMethod.toLowerCase()); + // update return type to conform to rust standard + if (operation.returnType != null) { + // array of model + if ( operation.returnType.startsWith("Vec") && !languageSpecificPrimitives.contains(operation.returnBaseType)) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if ( end > 0 ) { + operation.vendorExtensions.put("x-returnTypeInMethod", "Vec"); + operation.returnContainer = "Vec"; + } + } else if (!languageSpecificPrimitives.contains(operation.returnType)) { + // add super:: to model, e.g. super::pet + operation.vendorExtensions.put("x-returnTypeInMethod", "super::" + operation.returnType); + } + } } return objs; diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 0b9c6946e49..b556fe652d2 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -33,29 +33,29 @@ pub trait {{classname}} { impl{{classname}} for {{classname}}Impl { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::{{httpMethod}}, - format!("{{path}}", configuration.base_path).parse().unwrap()); + format!("{}{{path}}", configuration.base_path{{#allParams}}, {{paramName}}={{paramName}}{{/allParams}})); {{#hasQueryParams}} {{#queryParams}} {{#required}} - /// TODO query parameter {{baseName}}({{paramName}}) + // TODO query parameter {{baseName}}({{paramName}}) {{/required}} {{^required}} - /// TODO query parameter {{baseName}}({{paramName}}) Optional + // TODO query parameter {{baseName}}({{paramName}}) Optional {{/required}} {{/queryParams}} {{/hasQueryParams}} {{#hasHeaderParams}} {{#headerParams}} {{#required}} - /// TODO header parameter {{baseName}}({{paramName}}) + // TODO header parameter {{baseName}}({{paramName}}) {{/required}} {{^required}} - /// TODO header parameter {{baseName}}({{paramName}}) Optional + // TODO header parameter {{baseName}}({{paramName}}) Optional {{/required}} {{/headerParams}} {{/hasHeaderParams}} @@ -63,22 +63,22 @@ impl{{classname}} for {{classname}}Impl { {{#formParams}} {{#isFile}} {{^required}} - /// TODO form parameter (file) {{baseName}}({{paramName}}) Optional + // TODO form parameter (file) {{baseName}}({{paramName}}) Optional {{/required}} {{/isFile}} {{^isFile}} {{#required}} - /// TODO form parameter {{baseName}}({{paramName}}) + // TODO form parameter {{baseName}}({{paramName}}) {{/required}} {{^required}} - /// TODO form parameter {{baseName}}({{paramName}}) Optional + // TODO form parameter {{baseName}}({{paramName}}) Optional {{/required}} {{/isFile}} {{/formParams}} {{/hasFormParams}} {{#hasBodyParam}} {{#bodyParams}} - /// body params + // body params {{#required}} let serialized = serde_json::to_string({{{paramName}}}).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); @@ -92,7 +92,7 @@ impl{{classname}} for {{classname}}Impl { ) {{/required}} {{^required}} - /// TODO optional body parameter + // TODO optional body parameter {{/required}} {{/bodyParams}} {{/hasBodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache index c60d10ec4f5..2516931e218 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache @@ -26,10 +26,6 @@ use super::models; mod {{classFilename}}; {{#operations}} {{#operation}} -{{#summary}} -///{{{summary}}} -{{/summary}} -pub use self::{{classFilename}}::{{{operationId}}}; {{#-last}} pub use self::{{classFilename}}::{{classname}}; diff --git a/modules/swagger-codegen/src/main/resources/rust/api_response.mustache b/modules/swagger-codegen/src/main/resources/rust/api_response.mustache deleted file mode 100644 index 73a4f0e9ef1..00000000000 --- a/modules/swagger-codegen/src/main/resources/rust/api_response.mustache +++ /dev/null @@ -1,35 +0,0 @@ -{{>partial_header}} -package {{packageName}} - -import ( - "net/http" -) - -type APIResponse struct { - *http.Response `json:"-"` - Message string `json:"message,omitempty"` - /// Operation is the name of the swagger operation. - Operation string `json:"operation,omitempty"` - /// RequestURL is the request URL. This value is always available, even if the - /// embedded *http.Response is nil. - RequestURL string `json:"url,omitempty"` - /// Method is the HTTP method used for the request. This value is always - /// available, even if the embedded *http.Response is nil. - Method string `json:"method,omitempty"` - /// Payload holds the contents of the response body (which may be nil or empty). - /// This is provided here as the raw response.Body() reader will have already - /// been drained. - Payload []byte `json:"-"` -} - -func NewAPIResponse(r *http.Response) *APIResponse { - - response := &APIResponse{Response: r} - return response -} - -func NewAPIResponseWithError(errorMessage string) *APIResponse { - - response := &APIResponse{Message: errorMessage} - return response -} diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache index 425628b71bf..649a8876258 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -2,14 +2,14 @@ {{#models}} {{#model}} {{#description}} -/// {{{classname}}} : {{{description}}} +// {{{classname}}} : {{{description}}} {{/description}} #[derive(Debug, Serialize, Deserialize)] pub struct {{classname}} { {{#vars}} {{#description}} - /// {{{description}}} + // {{{description}}} {{/description}} #[serde(rename = "{{baseName}}")] {{name}}: {{^required}}Option<{{/required}}{{^isPrimitiveType}}{{^isContainer}}super::{{/isContainer}}{{/isPrimitiveType}}{{{datatype}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} @@ -17,7 +17,7 @@ pub struct {{classname}} { impl {{classname}} { {{#description}} - /// {{{description}}} + // {{{description}}} {{/description}} pub fn new({{#requiredVars}}{{name}}: {{{datatype}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{classname}} { {{classname}} { @@ -41,15 +41,15 @@ impl {{classname}} { } {{#isEnum}} -/// TODO enum -/// List of {{{name}}} -///const ( -/// {{#allowableValues}} -/// {{#enumVars}} -/// {{name}} {{{classname}}} = "{{{value}}}" -/// {{/enumVars}} -/// {{/allowableValues}} -///) +// TODO enum +// List of {{{name}}} +//const ( +// {{#allowableValues}} +// {{#enumVars}} +// {{name}} {{{classname}}} = "{{{value}}}" +// {{/enumVars}} +// {{/allowableValues}} +//) {{/isEnum}} diff --git a/samples/client/petstore/rust/src/apis/mod.rs b/samples/client/petstore/rust/src/apis/mod.rs index 3bbd5aa7148..21bcdf30082 100644 --- a/samples/client/petstore/rust/src/apis/mod.rs +++ b/samples/client/petstore/rust/src/apis/mod.rs @@ -22,54 +22,14 @@ impl From for Error { use super::models; mod pet_api; -///Add a new pet to the store -pub use self::pet_api::AddPet; -///Deletes a pet -pub use self::pet_api::DeletePet; -///Finds Pets by status -pub use self::pet_api::FindPetsByStatus; -///Finds Pets by tags -pub use self::pet_api::FindPetsByTags; -///Find pet by ID -pub use self::pet_api::GetPetById; -///Update an existing pet -pub use self::pet_api::UpdatePet; -///Updates a pet in the store with form data -pub use self::pet_api::UpdatePetWithForm; -///uploads an image -pub use self::pet_api::UploadFile; pub use self::pet_api::PetApi; mod store_api; -///Delete purchase order by ID -pub use self::store_api::DeleteOrder; -///Returns pet inventories by status -pub use self::store_api::GetInventory; -///Find purchase order by ID -pub use self::store_api::GetOrderById; -///Place an order for a pet -pub use self::store_api::PlaceOrder; pub use self::store_api::StoreApi; mod user_api; -///Create user -pub use self::user_api::CreateUser; -///Creates list of users with given input array -pub use self::user_api::CreateUsersWithArrayInput; -///Creates list of users with given input array -pub use self::user_api::CreateUsersWithListInput; -///Delete user -pub use self::user_api::DeleteUser; -///Get user by user name -pub use self::user_api::GetUserByName; -///Logs user into the system -pub use self::user_api::LoginUser; -///Logs out current logged in user session -pub use self::user_api::LogoutUser; -///Updated user -pub use self::user_api::UpdateUser; pub use self::user_api::UserApi; diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index ffddee86e07..380598b409c 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -47,9 +47,9 @@ implPetApi for PetApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("/pet", configuration.base_path).parse().unwrap()); + format!("{}/pet", configuration.base_path, body=body)); - /// body params + // body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -66,34 +66,34 @@ implPetApi for PetApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, - format!("/pet/{petId}", configuration.base_path).parse().unwrap()); + format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id, api_key=api_key)); - /// TODO header parameter api_key(api_key) Optional + // TODO header parameter api_key(api_key) Optional } - fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("/pet/findByStatus", configuration.base_path).parse().unwrap()); + format!("{}/pet/findByStatus", configuration.base_path, status=status)); - /// TODO query parameter status(status) + // TODO query parameter status(status) } - fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("/pet/findByTags", configuration.base_path).parse().unwrap()); + format!("{}/pet/findByTags", configuration.base_path, tags=tags)); - /// TODO query parameter tags(tags) + // TODO query parameter tags(tags) } - fn GetPetById(&self, pet_id: i64) -> Box> { + fn GetPetById(&self, pet_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("/pet/{petId}", configuration.base_path).parse().unwrap()); + format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id)); } @@ -101,9 +101,9 @@ implPetApi for PetApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Put, - format!("/pet", configuration.base_path).parse().unwrap()); + format!("{}/pet", configuration.base_path, body=body)); - /// body params + // body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -120,20 +120,20 @@ implPetApi for PetApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("/pet/{petId}", configuration.base_path).parse().unwrap()); + format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id, name=name, status=status)); - /// TODO form parameter name(name) Optional - /// TODO form parameter status(status) Optional + // TODO form parameter name(name) Optional + // TODO form parameter status(status) Optional } - fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box> { + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("/pet/{petId}/uploadImage", configuration.base_path).parse().unwrap()); + format!("{}/pet/{petId}/uploadImage", configuration.base_path, pet_id=pet_id, additional_metadata=additional_metadata, file=file)); - /// TODO form parameter additionalMetadata(additional_metadata) Optional - /// TODO form parameter (file) file(file) Optional + // TODO form parameter additionalMetadata(additional_metadata) Optional + // TODO form parameter (file) file(file) Optional } } diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index 9332fd39578..05ab63d4434 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -43,33 +43,33 @@ implStoreApi for StoreApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, - format!("/store/order/{orderId}", configuration.base_path).parse().unwrap()); + format!("{}/store/order/{orderId}", configuration.base_path, order_id=order_id)); } - fn GetInventory(&self, ) -> Box> { + fn GetInventory(&self, ) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("/store/inventory", configuration.base_path).parse().unwrap()); + format!("{}/store/inventory", configuration.base_path)); } - fn GetOrderById(&self, order_id: i64) -> Box> { + fn GetOrderById(&self, order_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("/store/order/{orderId}", configuration.base_path).parse().unwrap()); + format!("{}/store/order/{orderId}", configuration.base_path, order_id=order_id)); } - fn PlaceOrder(&self, body: Order) -> Box> { + fn PlaceOrder(&self, body: Order) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("/store/order", configuration.base_path).parse().unwrap()); + format!("{}/store/order", configuration.base_path, body=body)); - /// body params + // body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index 5b634112a35..24323212484 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -47,9 +47,9 @@ implUserApi for UserApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("/user", configuration.base_path).parse().unwrap()); + format!("{}/user", configuration.base_path, body=body)); - /// body params + // body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -66,9 +66,9 @@ implUserApi for UserApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("/user/createWithArray", configuration.base_path).parse().unwrap()); + format!("{}/user/createWithArray", configuration.base_path, body=body)); - /// body params + // body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -85,9 +85,9 @@ implUserApi for UserApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Post, - format!("/user/createWithList", configuration.base_path).parse().unwrap()); + format!("{}/user/createWithList", configuration.base_path, body=body)); - /// body params + // body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); @@ -104,33 +104,33 @@ implUserApi for UserApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Delete, - format!("/user/{username}", configuration.base_path).parse().unwrap()); + format!("{}/user/{username}", configuration.base_path, username=username)); } - fn GetUserByName(&self, username: &str) -> Box> { + fn GetUserByName(&self, username: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("/user/{username}", configuration.base_path).parse().unwrap()); + format!("{}/user/{username}", configuration.base_path, username=username)); } - fn LoginUser(&self, username: &str, password: &str) -> Box> { + fn LoginUser(&self, username: &str, password: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("/user/login", configuration.base_path).parse().unwrap()); + format!("{}/user/login", configuration.base_path, username=username, password=password)); - /// TODO query parameter username(username) - /// TODO query parameter password(password) + // TODO query parameter username(username) + // TODO query parameter password(password) } fn LogoutUser(&self, ) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, - format!("/user/logout", configuration.base_path).parse().unwrap()); + format!("{}/user/logout", configuration.base_path)); } @@ -138,9 +138,9 @@ implUserApi for UserApiImpl { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Put, - format!("/user/{username}", configuration.base_path).parse().unwrap()); + format!("{}/user/{username}", configuration.base_path, username=username, body=body)); - /// body params + // body params let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); diff --git a/samples/client/petstore/rust/src/models/api_response.rs b/samples/client/petstore/rust/src/models/api_response.rs index 47bf363daa0..ac8b1d6261d 100644 --- a/samples/client/petstore/rust/src/models/api_response.rs +++ b/samples/client/petstore/rust/src/models/api_response.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -/// ApiResponse : Describes the result of uploading an image resource +// ApiResponse : Describes the result of uploading an image resource #[derive(Debug, Serialize, Deserialize)] pub struct ApiResponse { @@ -18,7 +18,7 @@ pub struct ApiResponse { } impl ApiResponse { - /// Describes the result of uploading an image resource + // Describes the result of uploading an image resource pub fn new() -> ApiResponse { ApiResponse { code: None, diff --git a/samples/client/petstore/rust/src/models/category.rs b/samples/client/petstore/rust/src/models/category.rs index 39c4979e5f9..0dc4ed24a9b 100644 --- a/samples/client/petstore/rust/src/models/category.rs +++ b/samples/client/petstore/rust/src/models/category.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -/// Category : A category for a pet +// Category : A category for a pet #[derive(Debug, Serialize, Deserialize)] pub struct Category { @@ -17,7 +17,7 @@ pub struct Category { } impl Category { - /// A category for a pet + // A category for a pet pub fn new() -> Category { Category { id: None, diff --git a/samples/client/petstore/rust/src/models/order.rs b/samples/client/petstore/rust/src/models/order.rs index c012ed37fde..857277fc081 100644 --- a/samples/client/petstore/rust/src/models/order.rs +++ b/samples/client/petstore/rust/src/models/order.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -/// Order : An order for a pets from the pet store +// Order : An order for a pets from the pet store #[derive(Debug, Serialize, Deserialize)] pub struct Order { @@ -16,13 +16,13 @@ pub struct Order { #[serde(rename = "petId")] pet_id: Option, #[serde(rename = "quantity")] quantity: Option, #[serde(rename = "shipDate")] ship_date: Option, - /// Order Status + // Order Status #[serde(rename = "status")] status: Option, #[serde(rename = "complete")] complete: Option } impl Order { - /// An order for a pets from the pet store + // An order for a pets from the pet store pub fn new() -> Order { Order { id: None, diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index 246ecbf0845..ab51ae42b49 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -/// Pet : A pet for sale in the pet store +// Pet : A pet for sale in the pet store #[derive(Debug, Serialize, Deserialize)] pub struct Pet { @@ -17,12 +17,12 @@ pub struct Pet { #[serde(rename = "name")] name: String, #[serde(rename = "photoUrls")] photo_urls: Vec, #[serde(rename = "tags")] tags: Option>, - /// pet status in the store + // pet status in the store #[serde(rename = "status")] status: Option } impl Pet { - /// A pet for sale in the pet store + // A pet for sale in the pet store pub fn new(name: String, photo_urls: Vec) -> Pet { Pet { id: None, diff --git a/samples/client/petstore/rust/src/models/tag.rs b/samples/client/petstore/rust/src/models/tag.rs index 1ac30f30788..f9f62346378 100644 --- a/samples/client/petstore/rust/src/models/tag.rs +++ b/samples/client/petstore/rust/src/models/tag.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -/// Tag : A tag for a pet +// Tag : A tag for a pet #[derive(Debug, Serialize, Deserialize)] pub struct Tag { @@ -17,7 +17,7 @@ pub struct Tag { } impl Tag { - /// A tag for a pet + // A tag for a pet pub fn new() -> Tag { Tag { id: None, diff --git a/samples/client/petstore/rust/src/models/user.rs b/samples/client/petstore/rust/src/models/user.rs index c6848bb0f32..0f61dad805a 100644 --- a/samples/client/petstore/rust/src/models/user.rs +++ b/samples/client/petstore/rust/src/models/user.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -/// User : A User who is purchasing from the pet store +// User : A User who is purchasing from the pet store #[derive(Debug, Serialize, Deserialize)] pub struct User { @@ -19,12 +19,12 @@ pub struct User { #[serde(rename = "email")] email: Option, #[serde(rename = "password")] password: Option, #[serde(rename = "phone")] phone: Option, - /// User Status + // User Status #[serde(rename = "userStatus")] user_status: Option } impl User { - /// A User who is purchasing from the pet store + // A User who is purchasing from the pet store pub fn new() -> User { User { id: None, From 92b43ca37e38e6faf214bd73f054186434a86c07 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 16:16:28 +0800 Subject: [PATCH 06/22] add hash support, fix docstring --- .../swagger/codegen/languages/RustClientCodegen.java | 10 ++++------ .../src/main/resources/rust/model.mustache | 6 +++--- samples/client/petstore/rust/docs/StoreApi.md | 4 ++-- samples/client/petstore/rust/src/apis/store_api.rs | 4 ++-- .../client/petstore/rust/src/models/api_response.rs | 4 ++-- samples/client/petstore/rust/src/models/category.rs | 4 ++-- samples/client/petstore/rust/src/models/order.rs | 6 +++--- samples/client/petstore/rust/src/models/pet.rs | 6 +++--- samples/client/petstore/rust/src/models/tag.rs | 4 ++-- samples/client/petstore/rust/src/models/user.rs | 6 +++--- 10 files changed, 26 insertions(+), 28 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index 8b0bdbd33f3..a0e4ccdacbf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -272,7 +272,7 @@ public String toApiDocFilename(String name) { @Override public String getTypeDeclaration(Property p) { - if(p instanceof ArrayProperty) { + if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); return "Vec<" + getTypeDeclaration(inner) + ">"; @@ -280,10 +280,8 @@ public String getTypeDeclaration(Property p) { else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "[TODO]" + getTypeDeclaration(inner); + return "::std::collections::HashMap"; } - //return super.getTypeDeclaration(p); // Not using the supertype invocation, because we want to UpperCamelize // the type. @@ -292,11 +290,11 @@ else if (p instanceof MapProperty) { return typeMapping.get(swaggerType); } - if(typeMapping.containsValue(swaggerType)) { + if (typeMapping.containsValue(swaggerType)) { return swaggerType; } - if(languageSpecificPrimitives.contains(swaggerType)) { + if (languageSpecificPrimitives.contains(swaggerType)) { return swaggerType; } diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache index 649a8876258..2ccc54e9234 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -2,14 +2,14 @@ {{#models}} {{#model}} {{#description}} -// {{{classname}}} : {{{description}}} +/// {{{classname}}} : {{{description}}} {{/description}} #[derive(Debug, Serialize, Deserialize)] pub struct {{classname}} { {{#vars}} {{#description}} - // {{{description}}} + /// {{{description}}} {{/description}} #[serde(rename = "{{baseName}}")] {{name}}: {{^required}}Option<{{/required}}{{^isPrimitiveType}}{{^isContainer}}super::{{/isContainer}}{{/isPrimitiveType}}{{{datatype}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} @@ -17,7 +17,7 @@ pub struct {{classname}} { impl {{classname}} { {{#description}} - // {{{description}}} + /// {{{description}}} {{/description}} pub fn new({{#requiredVars}}{{name}}: {{{datatype}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{classname}} { {{classname}} { diff --git a/samples/client/petstore/rust/docs/StoreApi.md b/samples/client/petstore/rust/docs/StoreApi.md index 8dca9d3cb6f..221405f6cf6 100644 --- a/samples/client/petstore/rust/docs/StoreApi.md +++ b/samples/client/petstore/rust/docs/StoreApi.md @@ -38,7 +38,7 @@ No authorization required [[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) # **GetInventory** -> map[TODO]i32 GetInventory(ctx, ) +> ::std::collections::HashMap GetInventory(ctx, ) Returns pet inventories by status Returns a map of status codes to quantities @@ -48,7 +48,7 @@ This endpoint does not need any parameter. ### Return type -[**map[TODO]i32**](map.md) +[**::std::collections::HashMap**](map.md) ### Authorization diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index 05ab63d4434..f9a0cbfcfc7 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -32,7 +32,7 @@ impl StoreApiImpl { pub trait StoreApi { fn DeleteOrder(&self, order_id: String) -> Box>; - fn GetInventory(&self, ) -> Box>; + fn GetInventory(&self, ) -> Box, Error = Error>>; fn GetOrderById(&self, order_id: i64) -> Box>; fn PlaceOrder(&self, body: Order) -> Box>; } @@ -47,7 +47,7 @@ implStoreApi for StoreApiImpl { } - fn GetInventory(&self, ) -> Box> { + fn GetInventory(&self, ) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let mut req = hyper::Request::new( hyper::Method::Get, diff --git a/samples/client/petstore/rust/src/models/api_response.rs b/samples/client/petstore/rust/src/models/api_response.rs index ac8b1d6261d..47bf363daa0 100644 --- a/samples/client/petstore/rust/src/models/api_response.rs +++ b/samples/client/petstore/rust/src/models/api_response.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// ApiResponse : Describes the result of uploading an image resource +/// ApiResponse : Describes the result of uploading an image resource #[derive(Debug, Serialize, Deserialize)] pub struct ApiResponse { @@ -18,7 +18,7 @@ pub struct ApiResponse { } impl ApiResponse { - // Describes the result of uploading an image resource + /// Describes the result of uploading an image resource pub fn new() -> ApiResponse { ApiResponse { code: None, diff --git a/samples/client/petstore/rust/src/models/category.rs b/samples/client/petstore/rust/src/models/category.rs index 0dc4ed24a9b..39c4979e5f9 100644 --- a/samples/client/petstore/rust/src/models/category.rs +++ b/samples/client/petstore/rust/src/models/category.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// Category : A category for a pet +/// Category : A category for a pet #[derive(Debug, Serialize, Deserialize)] pub struct Category { @@ -17,7 +17,7 @@ pub struct Category { } impl Category { - // A category for a pet + /// A category for a pet pub fn new() -> Category { Category { id: None, diff --git a/samples/client/petstore/rust/src/models/order.rs b/samples/client/petstore/rust/src/models/order.rs index 857277fc081..c012ed37fde 100644 --- a/samples/client/petstore/rust/src/models/order.rs +++ b/samples/client/petstore/rust/src/models/order.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// Order : An order for a pets from the pet store +/// Order : An order for a pets from the pet store #[derive(Debug, Serialize, Deserialize)] pub struct Order { @@ -16,13 +16,13 @@ pub struct Order { #[serde(rename = "petId")] pet_id: Option, #[serde(rename = "quantity")] quantity: Option, #[serde(rename = "shipDate")] ship_date: Option, - // Order Status + /// Order Status #[serde(rename = "status")] status: Option, #[serde(rename = "complete")] complete: Option } impl Order { - // An order for a pets from the pet store + /// An order for a pets from the pet store pub fn new() -> Order { Order { id: None, diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index ab51ae42b49..246ecbf0845 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// Pet : A pet for sale in the pet store +/// Pet : A pet for sale in the pet store #[derive(Debug, Serialize, Deserialize)] pub struct Pet { @@ -17,12 +17,12 @@ pub struct Pet { #[serde(rename = "name")] name: String, #[serde(rename = "photoUrls")] photo_urls: Vec, #[serde(rename = "tags")] tags: Option>, - // pet status in the store + /// pet status in the store #[serde(rename = "status")] status: Option } impl Pet { - // A pet for sale in the pet store + /// A pet for sale in the pet store pub fn new(name: String, photo_urls: Vec) -> Pet { Pet { id: None, diff --git a/samples/client/petstore/rust/src/models/tag.rs b/samples/client/petstore/rust/src/models/tag.rs index f9f62346378..1ac30f30788 100644 --- a/samples/client/petstore/rust/src/models/tag.rs +++ b/samples/client/petstore/rust/src/models/tag.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// Tag : A tag for a pet +/// Tag : A tag for a pet #[derive(Debug, Serialize, Deserialize)] pub struct Tag { @@ -17,7 +17,7 @@ pub struct Tag { } impl Tag { - // A tag for a pet + /// A tag for a pet pub fn new() -> Tag { Tag { id: None, diff --git a/samples/client/petstore/rust/src/models/user.rs b/samples/client/petstore/rust/src/models/user.rs index 0f61dad805a..c6848bb0f32 100644 --- a/samples/client/petstore/rust/src/models/user.rs +++ b/samples/client/petstore/rust/src/models/user.rs @@ -8,7 +8,7 @@ * Generated by: https://github.com/swagger-api/swagger-codegen.git */ -// User : A User who is purchasing from the pet store +/// User : A User who is purchasing from the pet store #[derive(Debug, Serialize, Deserialize)] pub struct User { @@ -19,12 +19,12 @@ pub struct User { #[serde(rename = "email")] email: Option, #[serde(rename = "password")] password: Option, #[serde(rename = "phone")] phone: Option, - // User Status + /// User Status #[serde(rename = "userStatus")] user_status: Option } impl User { - // A User who is purchasing from the pet store + /// A User who is purchasing from the pet store pub fn new() -> User { User { id: None, From 9f9a1c6db159e8403c8a0a699849ce17b8690121 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 17:56:12 +0800 Subject: [PATCH 07/22] fix map parameter, update api.mustache --- .../io/swagger/codegen/DefaultCodegen.java | 5 + .../codegen/languages/RustClientCodegen.java | 39 ++++- .../src/main/resources/rust/api.mustache | 70 +++----- samples/client/petstore/rust/docs/PetApi.md | 4 +- samples/client/petstore/rust/docs/StoreApi.md | 4 +- samples/client/petstore/rust/docs/UserApi.md | 4 +- .../client/petstore/rust/src/apis/pet_api.rs | 161 ++++++++++++++---- .../petstore/rust/src/apis/store_api.rs | 78 +++++++-- .../client/petstore/rust/src/apis/user_api.rs | 137 +++++++++++---- 9 files changed, 362 insertions(+), 140 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 474a1750059..cd4dfaeb23b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2134,6 +2134,11 @@ public CodegenOperation fromOperation(String path, ArrayProperty ap = (ArrayProperty) responseProperty; CodegenProperty innerProperty = fromProperty("response", ap.getItems()); op.returnBaseType = innerProperty.baseType; + } else if (responseProperty instanceof MapProperty) { + MapProperty ap = (MapProperty) responseProperty; + CodegenProperty innerProperty = fromProperty("response", ap.getAdditionalProperties()); + op.returnBaseType = innerProperty.baseType; + LOGGER.info("innerProperty.baseType = " + innerProperty.baseType); } else { if (cm.complexType != null) { op.returnBaseType = cm.complexType; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index a0e4ccdacbf..ae80392bb72 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -74,7 +74,7 @@ public RustClientCodegen() { "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f32", "f64", - "char", "bool", "String", "Vec") + "char", "bool", "String", "Vec", "File") ); instantiationTypes.clear(); @@ -339,17 +339,50 @@ public Map postProcessOperations(Map objs) { operation.httpMethod = camelize(operation.httpMethod.toLowerCase()); // update return type to conform to rust standard if (operation.returnType != null) { - // array of model if ( operation.returnType.startsWith("Vec") && !languageSpecificPrimitives.contains(operation.returnBaseType)) { + // array of model String rt = operation.returnType; int end = rt.lastIndexOf(">"); if ( end > 0 ) { operation.vendorExtensions.put("x-returnTypeInMethod", "Vec"); - operation.returnContainer = "Vec"; + operation.returnContainer = "List"; + } + } else if (operation.returnType.startsWith("::std::collections::HashMap"); + if ( end > 0 ) { + operation.vendorExtensions.put("x-returnTypeInMethod", "::std::collections::HashMap"); + operation.returnContainer = "Map"; } } else if (!languageSpecificPrimitives.contains(operation.returnType)) { // add super:: to model, e.g. super::pet operation.vendorExtensions.put("x-returnTypeInMethod", "super::" + operation.returnType); + } else { + // primitive type or array/map of primitive type + operation.vendorExtensions.put("x-returnTypeInMethod", operation.returnType); + } + } + + for (CodegenParameter p : operation.allParams) { + if (p.isListContainer && !languageSpecificPrimitives.contains(p.dataType)) { + // array of model + String rt = p.dataType; + int end = rt.lastIndexOf(">"); + if ( end > 0 ) { + p.dataType = "Vec<" + rt.substring("Vec<".length(), end).trim() + ">"; + } + } else if (p.isMapContainer && !languageSpecificPrimitives.contains(p.dataType)) { + // map of model + String rt = p.dataType; + int end = rt.lastIndexOf(">"); + if ( end > 0 ) { + p.dataType = "::std::collections::HashMap"; + } + } else if (!languageSpecificPrimitives.contains(p.dataType)) { + // add super:: to model, e.g. super::pet + p.dataType = "super::" + p.dataType; } } } diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index b556fe652d2..ea928748ee1 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -35,67 +35,51 @@ impl{{classname}} for {{classname}}Impl { {{#operation}} fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::{{httpMethod}}, - format!("{}{{path}}", configuration.base_path{{#allParams}}, {{paramName}}={{paramName}}{{/allParams}})); + let method = hyper::Method::{{httpMethod}}; + + {{^hasQueryParams}} + let uri = format!("{}{{path}}", configuration.base_path{{#allParams}}, {{baseName}}={{paramName}}{{/allParams}})); + {{/hasQueryParams}} {{#hasQueryParams}} - {{#queryParams}} - {{#required}} - // TODO query parameter {{baseName}}({{paramName}}) - {{/required}} - {{^required}} - // TODO query parameter {{baseName}}({{paramName}}) Optional - {{/required}} - {{/queryParams}} + let query = url::form_urlencoded::Serializer::new(String::new()) + {{#queryParams}}.append_pair("{{paramName}}", {{paramName}}){{/queryParams}} // only for query params + .finish(); + let uri = format!("{}{{path}}{}", configuration.base_path, query{{#allParams}}, {{paramName}}={{paramName}}{{/allParams}})); {{/hasQueryParams}} + + let mut req = hyper::Request::new(method, uri); + {{#hasHeaderParams}} + let mut headers = req.headers_mut(); {{#headerParams}} - {{#required}} - // TODO header parameter {{baseName}}({{paramName}}) - {{/required}} - {{^required}} - // TODO header parameter {{baseName}}({{paramName}}) Optional - {{/required}} + headers.set_raw("{{paramName}}", "{{paramValue}}"); {{/headerParams}} {{/hasHeaderParams}} - {{#hasFormParams}} - {{#formParams}} - {{#isFile}} - {{^required}} - // TODO form parameter (file) {{baseName}}({{paramName}}) Optional - {{/required}} - {{/isFile}} - {{^isFile}} - {{#required}} - // TODO form parameter {{baseName}}({{paramName}}) - {{/required}} - {{^required}} - // TODO form parameter {{baseName}}({{paramName}}) Optional - {{/required}} - {{/isFile}} - {{/formParams}} - {{/hasFormParams}} + {{#hasBodyParam}} {{#bodyParams}} - // body params - {{#required}} - let serialized = serde_json::to_string({{{paramName}}}).unwrap(); + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); + {{/bodyParams}} + {{/hasBodyParam}} + // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) + {{^returnType}} .and_then(|_| futures::future::ok(())) + {{/returnType}} + {{#returnType}} + .and_then(|body| { + let parsed: Result<{{returnType}}, _> = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + {{/returnType}} ) - {{/required}} - {{^required}} - // TODO optional body parameter - {{/required}} - {{/bodyParams}} - {{/hasBodyParam}} } {{/operation}} diff --git a/samples/client/petstore/rust/docs/PetApi.md b/samples/client/petstore/rust/docs/PetApi.md index 14ad460f06f..9dfba2bb5a5 100644 --- a/samples/client/petstore/rust/docs/PetApi.md +++ b/samples/client/petstore/rust/docs/PetApi.md @@ -25,7 +25,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** | [**super::Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -174,7 +174,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** | [**super::Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type diff --git a/samples/client/petstore/rust/docs/StoreApi.md b/samples/client/petstore/rust/docs/StoreApi.md index 221405f6cf6..43542f3f1cf 100644 --- a/samples/client/petstore/rust/docs/StoreApi.md +++ b/samples/client/petstore/rust/docs/StoreApi.md @@ -48,7 +48,7 @@ This endpoint does not need any parameter. ### Return type -[**::std::collections::HashMap**](map.md) +**::std::collections::HashMap** ### Authorization @@ -98,7 +98,7 @@ Place an order for a pet Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Order**](Order.md)| order placed for purchasing the pet | + **body** | [**super::Order**](Order.md)| order placed for purchasing the pet | ### Return type diff --git a/samples/client/petstore/rust/docs/UserApi.md b/samples/client/petstore/rust/docs/UserApi.md index b5acb681de7..f0233a48e79 100644 --- a/samples/client/petstore/rust/docs/UserApi.md +++ b/samples/client/petstore/rust/docs/UserApi.md @@ -24,7 +24,7 @@ This can only be done by the logged in user. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**User**](User.md)| Created user object | + **body** | [**super::User**](User.md)| Created user object | ### Return type @@ -212,7 +212,7 @@ This can only be done by the logged in user. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| name that need to be deleted | - **body** | [**User**](User.md)| Updated user object | + **body** | [**super::User**](User.md)| Updated user object | ### Return type diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index 380598b409c..9df73d7695b 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -31,30 +31,34 @@ impl PetApiImpl { } pub trait PetApi { - fn AddPet(&self, body: Pet) -> Box>; + fn AddPet(&self, body: super::Pet) -> Box>; fn DeletePet(&self, pet_id: i64, api_key: String) -> Box>; fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>>; fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>>; fn GetPetById(&self, pet_id: i64) -> Box>; - fn UpdatePet(&self, body: Pet) -> Box>; + fn UpdatePet(&self, body: super::Pet) -> Box>; fn UpdatePetWithForm(&self, pet_id: i64, name: String, status: String) -> Box>; fn UploadFile(&self, pet_id: i64, additional_metadata: String, file: File) -> Box>; } implPetApi for PetApiImpl { - fn AddPet(&self, body: Pet) -> Box> { + fn AddPet(&self, body: super::Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Post, - format!("{}/pet", configuration.base_path, body=body)); - // body params + let method = hyper::Method::Post; + + let uri = format!("{}/pet", configuration.base_path, body=body)); + + let mut req = hyper::Request::new(method, uri); + + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); + // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) @@ -64,51 +68,113 @@ implPetApi for PetApiImpl { fn DeletePet(&self, pet_id: i64, api_key: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Delete, - format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id, api_key=api_key)); - // TODO header parameter api_key(api_key) Optional + let method = hyper::Method::Delete; + + let uri = format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id, api_key=api_key)); + + let mut req = hyper::Request::new(method, uri); + + let mut headers = req.headers_mut(); + headers.set_raw("api_key", ""); + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) } fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Get, - format!("{}/pet/findByStatus", configuration.base_path, status=status)); - // TODO query parameter status(status) + let method = hyper::Method::Get; + + let query = url::form_urlencoded::Serializer::new(String::new()) + .append_pair("status", status) // only for query params + .finish(); + let uri = format!("{}/pet/findByStatus{}", configuration.base_path, query, status=status)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|body| { + let parsed: Result = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) } fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Get, - format!("{}/pet/findByTags", configuration.base_path, tags=tags)); - // TODO query parameter tags(tags) + let method = hyper::Method::Get; + + let query = url::form_urlencoded::Serializer::new(String::new()) + .append_pair("tags", tags) // only for query params + .finish(); + let uri = format!("{}/pet/findByTags{}", configuration.base_path, query, tags=tags)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|body| { + let parsed: Result = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) } fn GetPetById(&self, pet_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Get, - format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id)); + let method = hyper::Method::Get; + + let uri = format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|body| { + let parsed: Result = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) } - fn UpdatePet(&self, body: Pet) -> Box> { + fn UpdatePet(&self, body: super::Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Put, - format!("{}/pet", configuration.base_path, body=body)); - // body params + let method = hyper::Method::Put; + + let uri = format!("{}/pet", configuration.base_path, body=body)); + + let mut req = hyper::Request::new(method, uri); + + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); + // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) @@ -118,22 +184,43 @@ implPetApi for PetApiImpl { fn UpdatePetWithForm(&self, pet_id: i64, name: &str, status: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Post, - format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id, name=name, status=status)); - // TODO form parameter name(name) Optional - // TODO form parameter status(status) Optional + let method = hyper::Method::Post; + + let uri = format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id, name=name, status=status)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) } fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Post, - format!("{}/pet/{petId}/uploadImage", configuration.base_path, pet_id=pet_id, additional_metadata=additional_metadata, file=file)); - // TODO form parameter additionalMetadata(additional_metadata) Optional - // TODO form parameter (file) file(file) Optional + let method = hyper::Method::Post; + + let uri = format!("{}/pet/{petId}/uploadImage", configuration.base_path, pet_id=pet_id, additional_metadata=additional_metadata, file=file)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|body| { + let parsed: Result = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) } } diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index f9a0cbfcfc7..2c26a21c1e6 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -34,51 +34,97 @@ pub trait StoreApi { fn DeleteOrder(&self, order_id: String) -> Box>; fn GetInventory(&self, ) -> Box, Error = Error>>; fn GetOrderById(&self, order_id: i64) -> Box>; - fn PlaceOrder(&self, body: Order) -> Box>; + fn PlaceOrder(&self, body: super::Order) -> Box>; } implStoreApi for StoreApiImpl { fn DeleteOrder(&self, order_id: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Delete, - format!("{}/store/order/{orderId}", configuration.base_path, order_id=order_id)); + let method = hyper::Method::Delete; + + let uri = format!("{}/store/order/{orderId}", configuration.base_path, order_id=order_id)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) } fn GetInventory(&self, ) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Get, - format!("{}/store/inventory", configuration.base_path)); + let method = hyper::Method::Get; + + let uri = format!("{}/store/inventory", configuration.base_path)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|body| { + let parsed: Result<::std::collections::HashMap<String, i32>, _> = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) } fn GetOrderById(&self, order_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Get, - format!("{}/store/order/{orderId}", configuration.base_path, order_id=order_id)); + let method = hyper::Method::Get; + + let uri = format!("{}/store/order/{orderId}", configuration.base_path, order_id=order_id)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|body| { + let parsed: Result = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) } - fn PlaceOrder(&self, body: Order) -> Box> { + fn PlaceOrder(&self, body: super::Order) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Post, - format!("{}/store/order", configuration.base_path, body=body)); - // body params + let method = hyper::Method::Post; + + let uri = format!("{}/store/order", configuration.base_path, body=body)); + + let mut req = hyper::Request::new(method, uri); + + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); + // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) - .and_then(|_| futures::future::ok(())) + .and_then(|body| { + let parsed: Result = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) ) } diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index 24323212484..9b14ef0b70a 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -31,30 +31,34 @@ impl UserApiImpl { } pub trait UserApi { - fn CreateUser(&self, body: User) -> Box>; + fn CreateUser(&self, body: super::User) -> Box>; fn CreateUsersWithArrayInput(&self, body: Vec) -> Box>; fn CreateUsersWithListInput(&self, body: Vec) -> Box>; fn DeleteUser(&self, username: String) -> Box>; fn GetUserByName(&self, username: String) -> Box>; fn LoginUser(&self, username: String, password: String) -> Box>; fn LogoutUser(&self, ) -> Box>; - fn UpdateUser(&self, username: String, body: User) -> Box>; + fn UpdateUser(&self, username: String, body: super::User) -> Box>; } implUserApi for UserApiImpl { - fn CreateUser(&self, body: User) -> Box> { + fn CreateUser(&self, body: super::User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Post, - format!("{}/user", configuration.base_path, body=body)); - // body params + let method = hyper::Method::Post; + + let uri = format!("{}/user", configuration.base_path, body=body)); + + let mut req = hyper::Request::new(method, uri); + + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); + // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) @@ -64,16 +68,20 @@ implUserApi for UserApiImpl { fn CreateUsersWithArrayInput(&self, body: Vec) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Post, - format!("{}/user/createWithArray", configuration.base_path, body=body)); - // body params + let method = hyper::Method::Post; + + let uri = format!("{}/user/createWithArray", configuration.base_path, body=body)); + + let mut req = hyper::Request::new(method, uri); + + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); + // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) @@ -83,16 +91,20 @@ implUserApi for UserApiImpl { fn CreateUsersWithListInput(&self, body: Vec) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Post, - format!("{}/user/createWithList", configuration.base_path, body=body)); - // body params + let method = hyper::Method::Post; + + let uri = format!("{}/user/createWithList", configuration.base_path, body=body)); + + let mut req = hyper::Request::new(method, uri); + + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); + // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) @@ -102,50 +114,105 @@ implUserApi for UserApiImpl { fn DeleteUser(&self, username: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Delete, - format!("{}/user/{username}", configuration.base_path, username=username)); + let method = hyper::Method::Delete; + + let uri = format!("{}/user/{username}", configuration.base_path, username=username)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) } fn GetUserByName(&self, username: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Get, - format!("{}/user/{username}", configuration.base_path, username=username)); + let method = hyper::Method::Get; + + let uri = format!("{}/user/{username}", configuration.base_path, username=username)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|body| { + let parsed: Result = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) } - fn LoginUser(&self, username: &str, password: &str) -> Box> { + fn LoginUser(&self, username: &str, password: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Get, - format!("{}/user/login", configuration.base_path, username=username, password=password)); - // TODO query parameter username(username) - // TODO query parameter password(password) + let method = hyper::Method::Get; + + let query = url::form_urlencoded::Serializer::new(String::new()) + .append_pair("username", username).append_pair("password", password) // only for query params + .finish(); + let uri = format!("{}/user/login{}", configuration.base_path, query, username=username, password=password)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|body| { + let parsed: Result = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) } fn LogoutUser(&self, ) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Get, - format!("{}/user/logout", configuration.base_path)); + let method = hyper::Method::Get; + + let uri = format!("{}/user/logout", configuration.base_path)); + + let mut req = hyper::Request::new(method, uri); + + + + // send request + Box::new( + configuration.client.request(req).and_then(|res| { res.body().concat2() }) + .map_err(|e| Error::from(e)) + .and_then(|_| futures::future::ok(())) + ) } - fn UpdateUser(&self, username: &str, body: User) -> Box> { + fn UpdateUser(&self, username: &str, body: super::User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); - let mut req = hyper::Request::new( - hyper::Method::Put, - format!("{}/user/{username}", configuration.base_path, username=username, body=body)); - // body params + let method = hyper::Method::Put; + + let uri = format!("{}/user/{username}", configuration.base_path, username=username, body=body)); + + let mut req = hyper::Request::new(method, uri); + + let serialized = serde_json::to_string(body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); + // send request Box::new( configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) From 952fa0f73e297b0a71b3f2f83b6bc846757e960e Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 18:03:57 +0800 Subject: [PATCH 08/22] use baseName for parameter --- .../io/swagger/codegen/DefaultCodegen.java | 1 - .../src/main/resources/rust/api.mustache | 10 +++++---- .../client/petstore/rust/src/apis/pet_api.rs | 22 +++++++++---------- .../petstore/rust/src/apis/store_api.rs | 6 ++--- .../client/petstore/rust/src/apis/user_api.rs | 17 +++++++------- 5 files changed, 29 insertions(+), 27 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index cd4dfaeb23b..b69855d8e74 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2138,7 +2138,6 @@ public CodegenOperation fromOperation(String path, MapProperty ap = (MapProperty) responseProperty; CodegenProperty innerProperty = fromProperty("response", ap.getAdditionalProperties()); op.returnBaseType = innerProperty.baseType; - LOGGER.info("innerProperty.baseType = " + innerProperty.baseType); } else { if (cm.complexType != null) { op.returnBaseType = cm.complexType; diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index ea928748ee1..0c59f7b8f53 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -39,13 +39,15 @@ impl{{classname}} for {{classname}}Impl { let method = hyper::Method::{{httpMethod}}; {{^hasQueryParams}} - let uri = format!("{}{{path}}", configuration.base_path{{#allParams}}, {{baseName}}={{paramName}}{{/allParams}})); + let uri = format!("{}{{{path}}}", configuration.base_path{{#allParams}}, "{{baseName}}"={{paramName}}{{/allParams}})); {{/hasQueryParams}} {{#hasQueryParams}} let query = url::form_urlencoded::Serializer::new(String::new()) - {{#queryParams}}.append_pair("{{paramName}}", {{paramName}}){{/queryParams}} // only for query params + {{#queryParams}} + .append_pair("{{baseName}}", {{paramName}}) + {{/queryParams}} .finish(); - let uri = format!("{}{{path}}{}", configuration.base_path, query{{#allParams}}, {{paramName}}={{paramName}}{{/allParams}})); + let uri = format!("{}{{{path}}}{}", configuration.base_path, query{{#allParams}}, "{{baseName}}"={{paramName}}{{/allParams}})); {{/hasQueryParams}} let mut req = hyper::Request::new(method, uri); @@ -53,7 +55,7 @@ impl{{classname}} for {{classname}}Impl { {{#hasHeaderParams}} let mut headers = req.headers_mut(); {{#headerParams}} - headers.set_raw("{{paramName}}", "{{paramValue}}"); + headers.set_raw("{{baseName}}", {{paramName}}); {{/headerParams}} {{/hasHeaderParams}} diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index 9df73d7695b..3b4af6898c2 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -48,7 +48,7 @@ implPetApi for PetApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/pet", configuration.base_path, body=body)); + let uri = format!("{}/pet", configuration.base_path, "body"=body)); let mut req = hyper::Request::new(method, uri); @@ -71,12 +71,12 @@ implPetApi for PetApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id, api_key=api_key)); + let uri = format!("{}/pet/{petId}", configuration.base_path, "petId"=pet_id, "api_key"=api_key)); let mut req = hyper::Request::new(method, uri); let mut headers = req.headers_mut(); - headers.set_raw("api_key", ""); + headers.set_raw("api_key", api_key); // send request @@ -93,9 +93,9 @@ implPetApi for PetApiImpl { let method = hyper::Method::Get; let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("status", status) // only for query params + .append_pair("status", status) .finish(); - let uri = format!("{}/pet/findByStatus{}", configuration.base_path, query, status=status)); + let uri = format!("{}/pet/findByStatus{}", configuration.base_path, query, "status"=status)); let mut req = hyper::Request::new(method, uri); @@ -118,9 +118,9 @@ implPetApi for PetApiImpl { let method = hyper::Method::Get; let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("tags", tags) // only for query params + .append_pair("tags", tags) .finish(); - let uri = format!("{}/pet/findByTags{}", configuration.base_path, query, tags=tags)); + let uri = format!("{}/pet/findByTags{}", configuration.base_path, query, "tags"=tags)); let mut req = hyper::Request::new(method, uri); @@ -142,7 +142,7 @@ implPetApi for PetApiImpl { let method = hyper::Method::Get; - let uri = format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id)); + let uri = format!("{}/pet/{petId}", configuration.base_path, "petId"=pet_id)); let mut req = hyper::Request::new(method, uri); @@ -164,7 +164,7 @@ implPetApi for PetApiImpl { let method = hyper::Method::Put; - let uri = format!("{}/pet", configuration.base_path, body=body)); + let uri = format!("{}/pet", configuration.base_path, "body"=body)); let mut req = hyper::Request::new(method, uri); @@ -187,7 +187,7 @@ implPetApi for PetApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/pet/{petId}", configuration.base_path, pet_id=pet_id, name=name, status=status)); + let uri = format!("{}/pet/{petId}", configuration.base_path, "petId"=pet_id, "name"=name, "status"=status)); let mut req = hyper::Request::new(method, uri); @@ -206,7 +206,7 @@ implPetApi for PetApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/pet/{petId}/uploadImage", configuration.base_path, pet_id=pet_id, additional_metadata=additional_metadata, file=file)); + let uri = format!("{}/pet/{petId}/uploadImage", configuration.base_path, "petId"=pet_id, "additionalMetadata"=additional_metadata, "file"=file)); let mut req = hyper::Request::new(method, uri); diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index 2c26a21c1e6..05a7552640f 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -44,7 +44,7 @@ implStoreApi for StoreApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/store/order/{orderId}", configuration.base_path, order_id=order_id)); + let uri = format!("{}/store/order/{orderId}", configuration.base_path, "orderId"=order_id)); let mut req = hyper::Request::new(method, uri); @@ -85,7 +85,7 @@ implStoreApi for StoreApiImpl { let method = hyper::Method::Get; - let uri = format!("{}/store/order/{orderId}", configuration.base_path, order_id=order_id)); + let uri = format!("{}/store/order/{orderId}", configuration.base_path, "orderId"=order_id)); let mut req = hyper::Request::new(method, uri); @@ -107,7 +107,7 @@ implStoreApi for StoreApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/store/order", configuration.base_path, body=body)); + let uri = format!("{}/store/order", configuration.base_path, "body"=body)); let mut req = hyper::Request::new(method, uri); diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index 9b14ef0b70a..d57352e8639 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -48,7 +48,7 @@ implUserApi for UserApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/user", configuration.base_path, body=body)); + let uri = format!("{}/user", configuration.base_path, "body"=body)); let mut req = hyper::Request::new(method, uri); @@ -71,7 +71,7 @@ implUserApi for UserApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/user/createWithArray", configuration.base_path, body=body)); + let uri = format!("{}/user/createWithArray", configuration.base_path, "body"=body)); let mut req = hyper::Request::new(method, uri); @@ -94,7 +94,7 @@ implUserApi for UserApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/user/createWithList", configuration.base_path, body=body)); + let uri = format!("{}/user/createWithList", configuration.base_path, "body"=body)); let mut req = hyper::Request::new(method, uri); @@ -117,7 +117,7 @@ implUserApi for UserApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/user/{username}", configuration.base_path, username=username)); + let uri = format!("{}/user/{username}", configuration.base_path, "username"=username)); let mut req = hyper::Request::new(method, uri); @@ -136,7 +136,7 @@ implUserApi for UserApiImpl { let method = hyper::Method::Get; - let uri = format!("{}/user/{username}", configuration.base_path, username=username)); + let uri = format!("{}/user/{username}", configuration.base_path, "username"=username)); let mut req = hyper::Request::new(method, uri); @@ -159,9 +159,10 @@ implUserApi for UserApiImpl { let method = hyper::Method::Get; let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("username", username).append_pair("password", password) // only for query params + .append_pair("username", username) + .append_pair("password", password) .finish(); - let uri = format!("{}/user/login{}", configuration.base_path, query, username=username, password=password)); + let uri = format!("{}/user/login{}", configuration.base_path, query, "username"=username, "password"=password)); let mut req = hyper::Request::new(method, uri); @@ -202,7 +203,7 @@ implUserApi for UserApiImpl { let method = hyper::Method::Put; - let uri = format!("{}/user/{username}", configuration.base_path, username=username, body=body)); + let uri = format!("{}/user/{username}", configuration.base_path, "username"=username, "body"=body)); let mut req = hyper::Request::new(method, uri); From 4a640a90275cff162fdf80fb2f985d5b4d1b8e94 Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Wed, 19 Jul 2017 12:04:34 +0100 Subject: [PATCH 09/22] Convert String to &str in trait definition --- modules/swagger-codegen/src/main/resources/rust/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 0c59f7b8f53..4dbae6d6b81 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -24,7 +24,7 @@ impl {{{classname}}}Impl { pub trait {{classname}} { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>; + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>; {{/operation}} {{/operations}} } From 469153c076037b2c5bf12164503b08492c922dc4 Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Wed, 19 Jul 2017 12:04:53 +0100 Subject: [PATCH 10/22] Only pass pathParams to uri builder --- modules/swagger-codegen/src/main/resources/rust/api.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 4dbae6d6b81..674f9d819d4 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -39,7 +39,7 @@ impl{{classname}} for {{classname}}Impl { let method = hyper::Method::{{httpMethod}}; {{^hasQueryParams}} - let uri = format!("{}{{{path}}}", configuration.base_path{{#allParams}}, "{{baseName}}"={{paramName}}{{/allParams}})); + let uri = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{baseName}}={{paramName}}{{/pathParams}}); {{/hasQueryParams}} {{#hasQueryParams}} let query = url::form_urlencoded::Serializer::new(String::new()) @@ -47,7 +47,7 @@ impl{{classname}} for {{classname}}Impl { .append_pair("{{baseName}}", {{paramName}}) {{/queryParams}} .finish(); - let uri = format!("{}{{{path}}}{}", configuration.base_path, query{{#allParams}}, "{{baseName}}"={{paramName}}{{/allParams}})); + let uri = format!("{}{{{path}}}{}", configuration.base_path, query{{#pathParams}}, {{baseName}}={{paramName}}{{/pathParams}}); {{/hasQueryParams}} let mut req = hyper::Request::new(method, uri); From f24b268c5e44de45c0941320912b35b82b0a2123 Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Wed, 19 Jul 2017 12:05:12 +0100 Subject: [PATCH 11/22] Fixed the html escaping in return type --- modules/swagger-codegen/src/main/resources/rust/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 674f9d819d4..edffba8bc0d 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -77,7 +77,7 @@ impl{{classname}} for {{classname}}Impl { {{/returnType}} {{#returnType}} .and_then(|body| { - let parsed: Result<{{returnType}}, _> = serde_json::from_slice(&body); + let parsed: Result<{{{returnType}}}, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) {{/returnType}} From 090b0fbaaf51c624ff4b88b3b9f0990bfefb932a Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Wed, 19 Jul 2017 12:05:21 +0100 Subject: [PATCH 12/22] Fixed the hashmap constructor --- modules/swagger-codegen/src/main/resources/rust/model.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache index 2ccc54e9234..3fe6089cd63 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -22,7 +22,7 @@ impl {{classname}} { pub fn new({{#requiredVars}}{{name}}: {{{datatype}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{classname}} { {{classname}} { {{#vars}} - {{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}Hash:new(){{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} + {{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}HashMap::new(){{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} } } From b70b12d65b28e69ece5c0a2292ec978d5ffce7ac Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Wed, 19 Jul 2017 12:05:42 +0100 Subject: [PATCH 13/22] Added models into API scope --- .../swagger-codegen/src/main/resources/rust/api_mod.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache index 2516931e218..67ebae27b6d 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache @@ -19,7 +19,7 @@ impl From for Error { } } -use super::models; +use super::models::*; {{#apiInfo}} {{#apis}} From 43f2a9cab74fe9302c784ed0f09bc24e45c810eb Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Wed, 19 Jul 2017 12:13:53 +0100 Subject: [PATCH 14/22] removed models subimport, reference from super --- modules/swagger-codegen/src/main/resources/rust/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index edffba8bc0d..98c1b12551f 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -7,7 +7,7 @@ use serde_json; use futures; use futures::{Future, Stream}; -use super::{Error, configuration, models}; +use super::{Error, configuration}; pub struct {{{classname}}}Impl { configuration: Rc>, From 5187e852a4ffb34a712e485d6cbdb139aa4a9554 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 19 Jul 2017 21:11:33 +0800 Subject: [PATCH 15/22] use fully-qualfiied model name --- .../codegen/languages/RustClientCodegen.java | 7 ++- .../src/main/resources/rust/api.mustache | 2 +- samples/client/petstore/rust/docs/Pet.md | 4 +- samples/client/petstore/rust/docs/PetApi.md | 20 +++---- samples/client/petstore/rust/docs/StoreApi.md | 10 ++-- samples/client/petstore/rust/docs/UserApi.md | 12 ++--- samples/client/petstore/rust/src/apis/mod.rs | 2 +- .../client/petstore/rust/src/apis/pet_api.rs | 54 +++++++++---------- .../petstore/rust/src/apis/store_api.rs | 28 +++++----- .../client/petstore/rust/src/apis/user_api.rs | 44 +++++++-------- .../client/petstore/rust/src/models/pet.rs | 12 ++--- 11 files changed, 99 insertions(+), 96 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index ae80392bb72..cb8b84e993b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -298,7 +298,9 @@ else if (p instanceof MapProperty) { return swaggerType; } - return toModelName(swaggerType); + // return fully-qualified model name + // ::models::{{classnameFile}}::{{classname}} + return "::models::" + toModelFilename(swaggerType) + "::" + toModelName(swaggerType); } @Override @@ -338,6 +340,7 @@ public Map postProcessOperations(Map objs) { // http method verb conversion (e.g. PUT => Put) operation.httpMethod = camelize(operation.httpMethod.toLowerCase()); // update return type to conform to rust standard + /* if (operation.returnType != null) { if ( operation.returnType.startsWith("Vec") && !languageSpecificPrimitives.contains(operation.returnBaseType)) { // array of model @@ -384,7 +387,7 @@ public Map postProcessOperations(Map objs) { // add super:: to model, e.g. super::pet p.dataType = "super::" + p.dataType; } - } + }*/ } return objs; diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 98c1b12551f..9aa5e11df09 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -33,7 +33,7 @@ pub trait {{classname}} { impl{{classname}} for {{classname}}Impl { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::{{httpMethod}}; diff --git a/samples/client/petstore/rust/docs/Pet.md b/samples/client/petstore/rust/docs/Pet.md index 1ed8471002b..21fd85091d5 100644 --- a/samples/client/petstore/rust/docs/Pet.md +++ b/samples/client/petstore/rust/docs/Pet.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **i64** | | [optional] [default to null] -**category** | [***Category**](Category.md) | | [optional] [default to null] +**category** | [***::models::category::Category**](Category.md) | | [optional] [default to null] **name** | **String** | | [default to null] **photo_urls** | **Vec** | | [default to null] -**tags** | [**Vec**](Tag.md) | | [optional] [default to null] +**tags** | [**Vec<::models::tag::Tag>**](Tag.md) | | [optional] [default to null] **status** | **String** | pet status in the store | [optional] [default to null] [[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/client/petstore/rust/docs/PetApi.md b/samples/client/petstore/rust/docs/PetApi.md index 9dfba2bb5a5..275f6810e17 100644 --- a/samples/client/petstore/rust/docs/PetApi.md +++ b/samples/client/petstore/rust/docs/PetApi.md @@ -25,7 +25,7 @@ Add a new pet to the store Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **body** | [**super::Pet**](Pet.md)| Pet object that needs to be added to the store | + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -80,7 +80,7 @@ Name | Type | Description | Notes [[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) # **FindPetsByStatus** -> Vec FindPetsByStatus(ctx, status) +> Vec<::models::pet::Pet> FindPetsByStatus(ctx, status) Finds Pets by status Multiple status values can be provided with comma separated strings @@ -94,7 +94,7 @@ Name | Type | Description | Notes ### Return type -[**Vec**](Pet.md) +[**Vec<::models::pet::Pet>**](Pet.md) ### Authorization @@ -108,7 +108,7 @@ Name | Type | Description | Notes [[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) # **FindPetsByTags** -> Vec FindPetsByTags(ctx, tags) +> Vec<::models::pet::Pet> FindPetsByTags(ctx, tags) Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -122,7 +122,7 @@ Name | Type | Description | Notes ### Return type -[**Vec**](Pet.md) +[**Vec<::models::pet::Pet>**](Pet.md) ### Authorization @@ -136,7 +136,7 @@ Name | Type | Description | Notes [[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) # **GetPetById** -> Pet GetPetById(ctx, pet_id) +> ::models::pet::Pet GetPetById(ctx, pet_id) Find pet by ID Returns a single pet @@ -150,7 +150,7 @@ Name | Type | Description | Notes ### Return type -[**Pet**](Pet.md) +[**::models::pet::Pet**](Pet.md) ### Authorization @@ -174,7 +174,7 @@ Update an existing pet Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **ctx** | **context.Context** | context containing the authentication | nil if no authentication - **body** | [**super::Pet**](Pet.md)| Pet object that needs to be added to the store | + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -230,7 +230,7 @@ Name | Type | Description | Notes [[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) # **UploadFile** -> ApiResponse UploadFile(ctx, pet_id, optional) +> ::models::api_response::ApiResponse UploadFile(ctx, pet_id, optional) uploads an image @@ -254,7 +254,7 @@ Name | Type | Description | Notes ### Return type -[**ApiResponse**](ApiResponse.md) +[**::models::api_response::ApiResponse**](ApiResponse.md) ### Authorization diff --git a/samples/client/petstore/rust/docs/StoreApi.md b/samples/client/petstore/rust/docs/StoreApi.md index 43542f3f1cf..7d38e21f421 100644 --- a/samples/client/petstore/rust/docs/StoreApi.md +++ b/samples/client/petstore/rust/docs/StoreApi.md @@ -62,7 +62,7 @@ This endpoint does not need any parameter. [[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) # **GetOrderById** -> Order GetOrderById(order_id) +> ::models::order::Order GetOrderById(order_id) Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -75,7 +75,7 @@ Name | Type | Description | Notes ### Return type -[**Order**](Order.md) +[**::models::order::Order**](Order.md) ### Authorization @@ -89,7 +89,7 @@ No authorization required [[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) # **PlaceOrder** -> Order PlaceOrder(body) +> ::models::order::Order PlaceOrder(body) Place an order for a pet @@ -98,11 +98,11 @@ Place an order for a pet Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**super::Order**](Order.md)| order placed for purchasing the pet | + **body** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type -[**Order**](Order.md) +[**::models::order::Order**](Order.md) ### Authorization diff --git a/samples/client/petstore/rust/docs/UserApi.md b/samples/client/petstore/rust/docs/UserApi.md index f0233a48e79..4a1d691760c 100644 --- a/samples/client/petstore/rust/docs/UserApi.md +++ b/samples/client/petstore/rust/docs/UserApi.md @@ -24,7 +24,7 @@ This can only be done by the logged in user. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**super::User**](User.md)| Created user object | + **body** | [**User**](User.md)| Created user object | ### Return type @@ -51,7 +51,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Vec<User>**](User.md)| List of user object | + **body** | [**Vec<::models::user::User>**](User.md)| List of user object | ### Return type @@ -78,7 +78,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Vec<User>**](User.md)| List of user object | + **body** | [**Vec<::models::user::User>**](User.md)| List of user object | ### Return type @@ -123,7 +123,7 @@ No authorization required [[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) # **GetUserByName** -> User GetUserByName(username) +> ::models::user::User GetUserByName(username) Get user by user name @@ -136,7 +136,7 @@ Name | Type | Description | Notes ### Return type -[**User**](User.md) +[**::models::user::User**](User.md) ### Authorization @@ -212,7 +212,7 @@ This can only be done by the logged in user. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| name that need to be deleted | - **body** | [**super::User**](User.md)| Updated user object | + **body** | [**User**](User.md)| Updated user object | ### Return type diff --git a/samples/client/petstore/rust/src/apis/mod.rs b/samples/client/petstore/rust/src/apis/mod.rs index 21bcdf30082..4dd5322506b 100644 --- a/samples/client/petstore/rust/src/apis/mod.rs +++ b/samples/client/petstore/rust/src/apis/mod.rs @@ -19,7 +19,7 @@ impl From for Error { } } -use super::models; +use super::models::*; mod pet_api; diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index 3b4af6898c2..306787088b3 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -16,7 +16,7 @@ use serde_json; use futures; use futures::{Future, Stream}; -use super::{Error, configuration, models}; +use super::{Error, configuration}; pub struct PetApiImpl { configuration: Rc>, @@ -31,24 +31,24 @@ impl PetApiImpl { } pub trait PetApi { - fn AddPet(&self, body: super::Pet) -> Box>; - fn DeletePet(&self, pet_id: i64, api_key: String) -> Box>; - fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>>; - fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>>; - fn GetPetById(&self, pet_id: i64) -> Box>; - fn UpdatePet(&self, body: super::Pet) -> Box>; - fn UpdatePetWithForm(&self, pet_id: i64, name: String, status: String) -> Box>; - fn UploadFile(&self, pet_id: i64, additional_metadata: String, file: File) -> Box>; + fn AddPet(&self, body: Pet) -> Box>; + fn DeletePet(&self, pet_id: i64, api_key: &str) -> Box>; + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>>; + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>>; + fn GetPetById(&self, pet_id: i64) -> Box>; + fn UpdatePet(&self, body: Pet) -> Box>; + fn UpdatePetWithForm(&self, pet_id: i64, name: &str, status: &str) -> Box>; + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box>; } implPetApi for PetApiImpl { - fn AddPet(&self, body: super::Pet) -> Box> { + fn AddPet(&self, body: Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/pet", configuration.base_path, "body"=body)); + let uri = format!("{}/pet", configuration.base_path); let mut req = hyper::Request::new(method, uri); @@ -71,7 +71,7 @@ implPetApi for PetApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/pet/{petId}", configuration.base_path, "petId"=pet_id, "api_key"=api_key)); + let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); let mut req = hyper::Request::new(method, uri); @@ -87,7 +87,7 @@ implPetApi for PetApiImpl { ) } - fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; @@ -95,7 +95,7 @@ implPetApi for PetApiImpl { let query = url::form_urlencoded::Serializer::new(String::new()) .append_pair("status", status) .finish(); - let uri = format!("{}/pet/findByStatus{}", configuration.base_path, query, "status"=status)); + let uri = format!("{}/pet/findByStatus{}", configuration.base_path, query); let mut req = hyper::Request::new(method, uri); @@ -106,13 +106,13 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result = serde_json::from_slice(&body); + let parsed: Result, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; @@ -120,7 +120,7 @@ implPetApi for PetApiImpl { let query = url::form_urlencoded::Serializer::new(String::new()) .append_pair("tags", tags) .finish(); - let uri = format!("{}/pet/findByTags{}", configuration.base_path, query, "tags"=tags)); + let uri = format!("{}/pet/findByTags{}", configuration.base_path, query); let mut req = hyper::Request::new(method, uri); @@ -131,18 +131,18 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result = serde_json::from_slice(&body); + let parsed: Result, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn GetPetById(&self, pet_id: i64) -> Box> { + fn GetPetById(&self, pet_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/pet/{petId}", configuration.base_path, "petId"=pet_id)); + let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); let mut req = hyper::Request::new(method, uri); @@ -153,18 +153,18 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result = serde_json::from_slice(&body); + let parsed: Result<::models::pet::Pet, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn UpdatePet(&self, body: super::Pet) -> Box> { + fn UpdatePet(&self, body: Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Put; - let uri = format!("{}/pet", configuration.base_path, "body"=body)); + let uri = format!("{}/pet", configuration.base_path); let mut req = hyper::Request::new(method, uri); @@ -187,7 +187,7 @@ implPetApi for PetApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/pet/{petId}", configuration.base_path, "petId"=pet_id, "name"=name, "status"=status)); + let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); let mut req = hyper::Request::new(method, uri); @@ -201,12 +201,12 @@ implPetApi for PetApiImpl { ) } - fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box> { + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/pet/{petId}/uploadImage", configuration.base_path, "petId"=pet_id, "additionalMetadata"=additional_metadata, "file"=file)); + let uri = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); let mut req = hyper::Request::new(method, uri); @@ -217,7 +217,7 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result = serde_json::from_slice(&body); + let parsed: Result<::models::api_response::ApiResponse, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index 05a7552640f..192c5feae59 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -16,7 +16,7 @@ use serde_json; use futures; use futures::{Future, Stream}; -use super::{Error, configuration, models}; +use super::{Error, configuration}; pub struct StoreApiImpl { configuration: Rc>, @@ -31,10 +31,10 @@ impl StoreApiImpl { } pub trait StoreApi { - fn DeleteOrder(&self, order_id: String) -> Box>; + fn DeleteOrder(&self, order_id: &str) -> Box>; fn GetInventory(&self, ) -> Box, Error = Error>>; - fn GetOrderById(&self, order_id: i64) -> Box>; - fn PlaceOrder(&self, body: super::Order) -> Box>; + fn GetOrderById(&self, order_id: i64) -> Box>; + fn PlaceOrder(&self, body: Order) -> Box>; } @@ -44,7 +44,7 @@ implStoreApi for StoreApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/store/order/{orderId}", configuration.base_path, "orderId"=order_id)); + let uri = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); let mut req = hyper::Request::new(method, uri); @@ -58,12 +58,12 @@ implStoreApi for StoreApiImpl { ) } - fn GetInventory(&self, ) -> Box, Error = Error>> { + fn GetInventory(&self, ) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/store/inventory", configuration.base_path)); + let uri = format!("{}/store/inventory", configuration.base_path); let mut req = hyper::Request::new(method, uri); @@ -74,18 +74,18 @@ implStoreApi for StoreApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::std::collections::HashMap<String, i32>, _> = serde_json::from_slice(&body); + let parsed: Result<::std::collections::HashMap, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn GetOrderById(&self, order_id: i64) -> Box> { + fn GetOrderById(&self, order_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/store/order/{orderId}", configuration.base_path, "orderId"=order_id)); + let uri = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); let mut req = hyper::Request::new(method, uri); @@ -96,18 +96,18 @@ implStoreApi for StoreApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result = serde_json::from_slice(&body); + let parsed: Result<::models::order::Order, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn PlaceOrder(&self, body: super::Order) -> Box> { + fn PlaceOrder(&self, body: Order) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/store/order", configuration.base_path, "body"=body)); + let uri = format!("{}/store/order", configuration.base_path); let mut req = hyper::Request::new(method, uri); @@ -122,7 +122,7 @@ implStoreApi for StoreApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result = serde_json::from_slice(&body); + let parsed: Result<::models::order::Order, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index d57352e8639..e306db6cb1e 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -16,7 +16,7 @@ use serde_json; use futures; use futures::{Future, Stream}; -use super::{Error, configuration, models}; +use super::{Error, configuration}; pub struct UserApiImpl { configuration: Rc>, @@ -31,24 +31,24 @@ impl UserApiImpl { } pub trait UserApi { - fn CreateUser(&self, body: super::User) -> Box>; - fn CreateUsersWithArrayInput(&self, body: Vec) -> Box>; - fn CreateUsersWithListInput(&self, body: Vec) -> Box>; - fn DeleteUser(&self, username: String) -> Box>; - fn GetUserByName(&self, username: String) -> Box>; - fn LoginUser(&self, username: String, password: String) -> Box>; + fn CreateUser(&self, body: User) -> Box>; + fn CreateUsersWithArrayInput(&self, body: Vec<::models::user::User>) -> Box>; + fn CreateUsersWithListInput(&self, body: Vec<::models::user::User>) -> Box>; + fn DeleteUser(&self, username: &str) -> Box>; + fn GetUserByName(&self, username: &str) -> Box>; + fn LoginUser(&self, username: &str, password: &str) -> Box>; fn LogoutUser(&self, ) -> Box>; - fn UpdateUser(&self, username: String, body: super::User) -> Box>; + fn UpdateUser(&self, username: &str, body: User) -> Box>; } implUserApi for UserApiImpl { - fn CreateUser(&self, body: super::User) -> Box> { + fn CreateUser(&self, body: User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user", configuration.base_path, "body"=body)); + let uri = format!("{}/user", configuration.base_path); let mut req = hyper::Request::new(method, uri); @@ -66,12 +66,12 @@ implUserApi for UserApiImpl { ) } - fn CreateUsersWithArrayInput(&self, body: Vec) -> Box> { + fn CreateUsersWithArrayInput(&self, body: Vec<::models::user::User>) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user/createWithArray", configuration.base_path, "body"=body)); + let uri = format!("{}/user/createWithArray", configuration.base_path); let mut req = hyper::Request::new(method, uri); @@ -89,12 +89,12 @@ implUserApi for UserApiImpl { ) } - fn CreateUsersWithListInput(&self, body: Vec) -> Box> { + fn CreateUsersWithListInput(&self, body: Vec<::models::user::User>) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user/createWithList", configuration.base_path, "body"=body)); + let uri = format!("{}/user/createWithList", configuration.base_path); let mut req = hyper::Request::new(method, uri); @@ -117,7 +117,7 @@ implUserApi for UserApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/user/{username}", configuration.base_path, "username"=username)); + let uri = format!("{}/user/{username}", configuration.base_path, username=username); let mut req = hyper::Request::new(method, uri); @@ -131,12 +131,12 @@ implUserApi for UserApiImpl { ) } - fn GetUserByName(&self, username: &str) -> Box> { + fn GetUserByName(&self, username: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/user/{username}", configuration.base_path, "username"=username)); + let uri = format!("{}/user/{username}", configuration.base_path, username=username); let mut req = hyper::Request::new(method, uri); @@ -147,7 +147,7 @@ implUserApi for UserApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result = serde_json::from_slice(&body); + let parsed: Result<::models::user::User, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) @@ -162,7 +162,7 @@ implUserApi for UserApiImpl { .append_pair("username", username) .append_pair("password", password) .finish(); - let uri = format!("{}/user/login{}", configuration.base_path, query, "username"=username, "password"=password)); + let uri = format!("{}/user/login{}", configuration.base_path, query); let mut req = hyper::Request::new(method, uri); @@ -184,7 +184,7 @@ implUserApi for UserApiImpl { let method = hyper::Method::Get; - let uri = format!("{}/user/logout", configuration.base_path)); + let uri = format!("{}/user/logout", configuration.base_path); let mut req = hyper::Request::new(method, uri); @@ -198,12 +198,12 @@ implUserApi for UserApiImpl { ) } - fn UpdateUser(&self, username: &str, body: super::User) -> Box> { + fn UpdateUser(&self, username: &str, body: User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Put; - let uri = format!("{}/user/{username}", configuration.base_path, "username"=username, "body"=body)); + let uri = format!("{}/user/{username}", configuration.base_path, username=username); let mut req = hyper::Request::new(method, uri); diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index 246ecbf0845..95ec4c8cae9 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -13,10 +13,10 @@ #[derive(Debug, Serialize, Deserialize)] pub struct Pet { #[serde(rename = "id")] id: Option, - #[serde(rename = "category")] category: Option, + #[serde(rename = "category")] category: Option, #[serde(rename = "name")] name: String, #[serde(rename = "photoUrls")] photo_urls: Vec, - #[serde(rename = "tags")] tags: Option>, + #[serde(rename = "tags")] tags: Option>, /// pet status in the store #[serde(rename = "status")] status: Option } @@ -43,11 +43,11 @@ impl Pet { self } - pub fn set_category(&mut self, category: Category) { + pub fn set_category(&mut self, category: ::models::category::Category) { self.category = Some(category); } - pub fn with_category(mut self, category: Category) -> Pet { + pub fn with_category(mut self, category: ::models::category::Category) -> Pet { self.category = Some(category); self } @@ -70,11 +70,11 @@ impl Pet { self } - pub fn set_tags(&mut self, tags: Vec) { + pub fn set_tags(&mut self, tags: Vec<::models::tag::Tag>) { self.tags = Some(tags); } - pub fn with_tags(mut self, tags: Vec) -> Pet { + pub fn with_tags(mut self, tags: Vec<::models::tag::Tag>) -> Pet { self.tags = Some(tags); self } From 503c9792e08050d0425c6525e3c547e44dac8937 Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Wed, 19 Jul 2017 16:02:44 +0100 Subject: [PATCH 16/22] Fixed the remaining templates inconsistencies --- .../codegen/languages/RustClientCodegen.java | 4 +-- .../src/main/resources/rust/api.mustache | 31 ++++++++++++------- .../src/main/resources/rust/api_mod.mustache | 3 +- .../src/main/resources/rust/client.mustache | 7 ++--- .../src/main/resources/rust/model.mustache | 2 +- .../main/resources/rust/model_mod.mustache | 3 ++ 6 files changed, 29 insertions(+), 21 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index cb8b84e993b..9b9ae585b30 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -93,7 +93,7 @@ public RustClientCodegen() { typeMapping.put("date", "string"); typeMapping.put("DateTime", "String"); typeMapping.put("password", "String"); - // TODO what should 'file' mapped to + // TODO(farcaller): map file typeMapping.put("file", "File"); typeMapping.put("binary", "Vec"); typeMapping.put("ByteArray", "String"); @@ -300,7 +300,7 @@ else if (p instanceof MapProperty) { // return fully-qualified model name // ::models::{{classnameFile}}::{{classname}} - return "::models::" + toModelFilename(swaggerType) + "::" + toModelName(swaggerType); + return "::models::" + toModelName(swaggerType); } @Override diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 9aa5e11df09..acfd363027f 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -24,7 +24,7 @@ impl {{{classname}}}Impl { pub trait {{classname}} { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>; + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>; {{/operation}} {{/operations}} } @@ -33,35 +33,42 @@ pub trait {{classname}} { impl{{classname}} for {{classname}}Impl { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::{{httpMethod}}; {{^hasQueryParams}} - let uri = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{baseName}}={{paramName}}{{/pathParams}}); + let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}}); {{/hasQueryParams}} {{#hasQueryParams}} - let query = url::form_urlencoded::Serializer::new(String::new()) + let query = ::url::form_urlencoded::Serializer::new(String::new()) {{#queryParams}} - .append_pair("{{baseName}}", {{paramName}}) + .append_pair("{{baseName}}", {{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}) {{/queryParams}} .finish(); - let uri = format!("{}{{{path}}}{}", configuration.base_path, query{{#pathParams}}, {{baseName}}={{paramName}}{{/pathParams}}); + let uri_str = format!("{}{{{path}}}{}", configuration.base_path, query{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}}); {{/hasQueryParams}} - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); {{#hasHeaderParams}} - let mut headers = req.headers_mut(); - {{#headerParams}} - headers.set_raw("{{baseName}}", {{paramName}}); - {{/headerParams}} + { + let mut headers = req.headers_mut(); + {{#headerParams}} + headers.set_raw("{{baseName}}", {{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}); + {{/headerParams}} + } {{/hasHeaderParams}} {{#hasBodyParam}} {{#bodyParams}} - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); diff --git a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache index 67ebae27b6d..e9f0ac2ce01 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache @@ -27,9 +27,8 @@ mod {{classFilename}}; {{#operations}} {{#operation}} {{#-last}} - pub use self::{{classFilename}}::{{classname}}; - +pub use self::{{classFilename}}::{{classname}}Impl; {{/-last}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/rust/client.mustache b/modules/swagger-codegen/src/main/resources/rust/client.mustache index d840b8a1684..82294ec771a 100644 --- a/modules/swagger-codegen/src/main/resources/rust/client.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/client.mustache @@ -2,7 +2,6 @@ use std::rc::Rc; use hyper; use super::configuration::Configuration; -use super::pet_api; pub struct APIClient { configuration: Rc>, @@ -11,7 +10,7 @@ pub struct APIClient { {{#operations}} {{#operation}} {{#-last}} - {{classFilename}}: Box<{{classFilename}}::{{classname}}>, + {{classFilename}}: Box<::apis::{{classname}}>, {{/-last}} {{/operation}} {{/operations}} @@ -30,7 +29,7 @@ impl APIClient { {{#operations}} {{#operation}} {{#-last}} - {{classFilename}}: Box::new({{classFilename}}::{{classname}}Impl::new(rc.clone())), + {{classFilename}}: Box::new(::apis::{{classname}}Impl::new(rc.clone())), {{/-last}} {{/operation}} {{/operations}} @@ -44,7 +43,7 @@ impl APIClient { {{#operations}} {{#operation}} {{#-last}} - pub fn {{classFilename}}(&self) -> &{{classFilename}}::{{classname}}{ + pub fn {{classFilename}}(&self) -> &::apis::{{classname}}{ self.{{classFilename}}.as_ref() } diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache index 3fe6089cd63..cb91ca5fa05 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -11,7 +11,7 @@ pub struct {{classname}} { {{#description}} /// {{{description}}} {{/description}} - #[serde(rename = "{{baseName}}")] {{name}}: {{^required}}Option<{{/required}}{{^isPrimitiveType}}{{^isContainer}}super::{{/isContainer}}{{/isPrimitiveType}}{{{datatype}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} + #[serde(rename = "{{baseName}}")] {{name}}: {{^required}}Option<{{/required}}{{{datatype}}}{{^required}}>{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} } diff --git a/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache index daddc889b81..d2b7578f324 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache @@ -4,3 +4,6 @@ mod {{{classFilename}}}; pub use self::{{{classFilename}}}::{{{classname}}}; {{/model}} {{/models}} + +// TODO(farcaller): sort out files +pub struct File; From 20fe88283bea1cc0b12662e6e5501ab0e4d612f1 Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Wed, 19 Jul 2017 16:15:47 +0100 Subject: [PATCH 17/22] Fixed issues that floated up in kubernetes swagger file --- modules/swagger-codegen/src/main/resources/rust/api.mustache | 2 +- modules/swagger-codegen/src/main/resources/rust/model.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index acfd363027f..9941dc92277 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -44,7 +44,7 @@ impl{{classname}} for {{classname}}Impl { {{#hasQueryParams}} let query = ::url::form_urlencoded::Serializer::new(String::new()) {{#queryParams}} - .append_pair("{{baseName}}", {{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}) + .append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()) {{/queryParams}} .finish(); let uri_str = format!("{}{{{path}}}{}", configuration.base_path, query{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}}); diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache index cb91ca5fa05..f893e744239 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -22,7 +22,7 @@ impl {{classname}} { pub fn new({{#requiredVars}}{{name}}: {{{datatype}}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{classname}} { {{classname}} { {{#vars}} - {{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}HashMap::new(){{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} + {{name}}: {{#required}}{{name}}{{/required}}{{^required}}{{#isListContainer}}None{{/isListContainer}}{{#isMapContainer}}None{{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} {{/vars}} } } From 615492934a801f1093654ec807768816354d733f Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 22 Jul 2017 18:18:35 +0800 Subject: [PATCH 18/22] add rust tests --- .../codegen/languages/RustClientCodegen.java | 2 ++ .../options/RustClientOptionsProvider.java | 33 +++++++++++++++++ .../codegen/rust/RustClientOptionsTest.java | 35 +++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/rust/RustClientOptionsTest.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index 9b9ae585b30..a921ffa6a42 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -16,6 +16,8 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { static Logger LOGGER = LoggerFactory.getLogger(RustClientCodegen.class); + public static final String PACKAGE_NAME = "pacakgeName"; + public static final String PACKAGE_VERSION = "packageVersion"; protected String packageName = "swagger"; protected String packageVersion = "1.0.0"; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java new file mode 100644 index 00000000000..0a761a0a87e --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java @@ -0,0 +1,33 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.RustClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class RustClientOptionsProvider implements OptionsProvider { + public static final String PACKAGE_NAME_VALUE = "swagger_client_rust"; + public static final String PACKAGE_VERSION_VALUE = "2.1.2"; + + + @Override + public String getLanguage() { + return "rust"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(RustClientCodegen.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(RustClientCodegen.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/rust/RustClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/rust/RustClientOptionsTest.java new file mode 100644 index 00000000000..22df0dfcf86 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/rust/RustClientOptionsTest.java @@ -0,0 +1,35 @@ +package io.swagger.codegen.rust; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.RustClientCodegen; +import io.swagger.codegen.options.RustClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class RustClientOptionsTest extends AbstractOptionsTest { + + @Tested + private RustClientCodegen clientCodegen; + + public RustClientOptionsTest() { + super(new RustClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(RustClientOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(RustClientOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + }}; + } +} From 7f90a3a1cd3b9961b94629ee814112dd12b12fa4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 23 Jul 2017 00:17:10 +0800 Subject: [PATCH 19/22] fix test cases --- .../java/io/swagger/codegen/languages/RustClientCodegen.java | 2 +- .../io/swagger/codegen/options/RustClientOptionsProvider.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index a921ffa6a42..5b593b58a77 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -16,7 +16,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { static Logger LOGGER = LoggerFactory.getLogger(RustClientCodegen.class); - public static final String PACKAGE_NAME = "pacakgeName"; + public static final String PACKAGE_NAME = "packageName"; public static final String PACKAGE_VERSION = "packageVersion"; protected String packageName = "swagger"; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java index 0a761a0a87e..4ec12ea2b8f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RustClientOptionsProvider.java @@ -8,7 +8,7 @@ import java.util.Map; public class RustClientOptionsProvider implements OptionsProvider { - public static final String PACKAGE_NAME_VALUE = "swagger_client_rust"; + public static final String PACKAGE_NAME_VALUE = "swagger_test"; public static final String PACKAGE_VERSION_VALUE = "2.1.2"; From d912e34ea12bbe4d8d4cbbbec8d44ed4add7bb5b Mon Sep 17 00:00:00 2001 From: Brandon W Maister Date: Sun, 6 Aug 2017 02:33:30 -0500 Subject: [PATCH 20/22] Rust gen slightly more idiomatic (#6247) * Go -> Rust in README * Remove leftover go file in rust sample * rust: Regenerate sample * rust: Rename *Impl -> *Client * rust: one-line use line More in line with common style * rust: Replace tabs (in java) with 4 spaces --- .../codegen/languages/RustClientCodegen.java | 32 +- .../src/main/resources/rust/README.mustache | 2 +- .../src/main/resources/rust/api.mustache | 10 +- .../src/main/resources/rust/api_mod.mustache | 3 +- .../src/main/resources/rust/client.mustache | 4 +- samples/client/petstore/rust/README.md | 2 +- samples/client/petstore/rust/docs/Pet.md | 4 +- samples/client/petstore/rust/docs/PetApi.md | 16 +- samples/client/petstore/rust/docs/StoreApi.md | 8 +- samples/client/petstore/rust/docs/UserApi.md | 8 +- .../petstore/rust/src/apis/api_client.rs | 423 ------------------ .../client/petstore/rust/src/apis/client.rs | 21 +- samples/client/petstore/rust/src/apis/mod.rs | 12 +- .../client/petstore/rust/src/apis/pet_api.rs | 132 ++++-- .../petstore/rust/src/apis/store_api.rs | 60 ++- .../client/petstore/rust/src/apis/user_api.rs | 118 +++-- .../client/petstore/rust/src/models/mod.rs | 3 + .../client/petstore/rust/src/models/pet.rs | 12 +- 18 files changed, 272 insertions(+), 598 deletions(-) delete mode 100644 samples/client/petstore/rust/src/apis/api_client.rs diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java index 5b593b58a77..15caa76a245 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -51,17 +51,17 @@ public RustClientCodegen() { setReservedWordsLowerCase( Arrays.asList( - "abstract", "alignof", "as", "become", "box", - "break", "const", "continue", "crate", "do", - "else", "enum", "extern", "false", "final", - "fn", "for", "if", "impl", "in", - "let", "loop", "macro", "match", "mod", - "move", "mut", "offsetof", "override", "priv", - "proc", "pub", "pure", "ref", "return", - "Self", "self", "sizeof", "static", "struct", - "super", "trait", "true", "type", "typeof", - "unsafe", "unsized", "use", "virtual", "where", - "while", "yield" + "abstract", "alignof", "as", "become", "box", + "break", "const", "continue", "crate", "do", + "else", "enum", "extern", "false", "final", + "fn", "for", "if", "impl", "in", + "let", "loop", "macro", "match", "mod", + "move", "mut", "offsetof", "override", "priv", + "proc", "pub", "pure", "ref", "return", + "Self", "self", "sizeof", "static", "struct", + "super", "trait", "true", "type", "typeof", + "unsafe", "unsized", "use", "virtual", "where", + "while", "yield" ) ); @@ -73,10 +73,10 @@ public RustClientCodegen() { languageSpecificPrimitives = new HashSet( Arrays.asList( - "i8", "i16", "i32", "i64", - "u8", "u16", "u32", "u64", - "f32", "f64", - "char", "bool", "String", "Vec", "File") + "i8", "i16", "i32", "i64", + "u8", "u16", "u32", "u64", + "f32", "f64", + "char", "bool", "String", "Vec", "File") ); instantiationTypes.clear(); @@ -386,7 +386,7 @@ public Map postProcessOperations(Map objs) { p.dataType = "::std::collections::HashMap"; } } else if (!languageSpecificPrimitives.contains(p.dataType)) { - // add super:: to model, e.g. super::pet + // add super:: to model, e.g. super::pet p.dataType = "super::" + p.dataType; } }*/ diff --git a/modules/swagger-codegen/src/main/resources/rust/README.mustache b/modules/swagger-codegen/src/main/resources/rust/README.mustache index 0e89ca61846..67cc0280e2c 100644 --- a/modules/swagger-codegen/src/main/resources/rust/README.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/README.mustache @@ -1,4 +1,4 @@ -# Go API client for {{packageName}} +# Rust API client for {{packageName}} {{#appDescription}} {{{appDescription}}} diff --git a/modules/swagger-codegen/src/main/resources/rust/api.mustache b/modules/swagger-codegen/src/main/resources/rust/api.mustache index 9941dc92277..811f8870448 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -9,13 +9,13 @@ use futures::{Future, Stream}; use super::{Error, configuration}; -pub struct {{{classname}}}Impl { +pub struct {{{classname}}}Client { configuration: Rc>, } -impl {{{classname}}}Impl { - pub fn new(configuration: Rc>) -> {{{classname}}}Impl { - {{{classname}}}Impl { +impl {{{classname}}}Client { + pub fn new(configuration: Rc>) -> {{{classname}}}Client { + {{{classname}}}Client { configuration: configuration, } } @@ -30,7 +30,7 @@ pub trait {{classname}} { } -impl{{classname}} for {{classname}}Impl { +impl{{classname}} for {{classname}}Client { {{#operations}} {{#operation}} fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box> { diff --git a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache index e9f0ac2ce01..5b62b897cdd 100644 --- a/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache @@ -27,8 +27,7 @@ mod {{classFilename}}; {{#operations}} {{#operation}} {{#-last}} -pub use self::{{classFilename}}::{{classname}}; -pub use self::{{classFilename}}::{{classname}}Impl; +pub use self::{{classFilename}}::{ {{classname}}, {{classname}}Client }; {{/-last}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/rust/client.mustache b/modules/swagger-codegen/src/main/resources/rust/client.mustache index 82294ec771a..faaea0dbd2f 100644 --- a/modules/swagger-codegen/src/main/resources/rust/client.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/client.mustache @@ -21,7 +21,7 @@ pub struct APIClient { impl APIClient { pub fn new(configuration: Configuration) -> APIClient { let rc = Rc::new(configuration); - + APIClient { configuration: rc.clone(), {{#apiInfo}} @@ -29,7 +29,7 @@ impl APIClient { {{#operations}} {{#operation}} {{#-last}} - {{classFilename}}: Box::new(::apis::{{classname}}Impl::new(rc.clone())), + {{classFilename}}: Box::new(::apis::{{classname}}Client::new(rc.clone())), {{/-last}} {{/operation}} {{/operations}} diff --git a/samples/client/petstore/rust/README.md b/samples/client/petstore/rust/README.md index 32ad5365bdf..ee5f2426813 100644 --- a/samples/client/petstore/rust/README.md +++ b/samples/client/petstore/rust/README.md @@ -1,4 +1,4 @@ -# Go API client for swagger +# Rust API client for swagger This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. diff --git a/samples/client/petstore/rust/docs/Pet.md b/samples/client/petstore/rust/docs/Pet.md index 21fd85091d5..ab2bef92432 100644 --- a/samples/client/petstore/rust/docs/Pet.md +++ b/samples/client/petstore/rust/docs/Pet.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **i64** | | [optional] [default to null] -**category** | [***::models::category::Category**](Category.md) | | [optional] [default to null] +**category** | [***::models::Category**](Category.md) | | [optional] [default to null] **name** | **String** | | [default to null] **photo_urls** | **Vec** | | [default to null] -**tags** | [**Vec<::models::tag::Tag>**](Tag.md) | | [optional] [default to null] +**tags** | [**Vec<::models::Tag>**](Tag.md) | | [optional] [default to null] **status** | **String** | pet status in the store | [optional] [default to null] [[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/client/petstore/rust/docs/PetApi.md b/samples/client/petstore/rust/docs/PetApi.md index 275f6810e17..82e8a231c37 100644 --- a/samples/client/petstore/rust/docs/PetApi.md +++ b/samples/client/petstore/rust/docs/PetApi.md @@ -80,7 +80,7 @@ Name | Type | Description | Notes [[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) # **FindPetsByStatus** -> Vec<::models::pet::Pet> FindPetsByStatus(ctx, status) +> Vec<::models::Pet> FindPetsByStatus(ctx, status) Finds Pets by status Multiple status values can be provided with comma separated strings @@ -94,7 +94,7 @@ Name | Type | Description | Notes ### Return type -[**Vec<::models::pet::Pet>**](Pet.md) +[**Vec<::models::Pet>**](Pet.md) ### Authorization @@ -108,7 +108,7 @@ Name | Type | Description | Notes [[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) # **FindPetsByTags** -> Vec<::models::pet::Pet> FindPetsByTags(ctx, tags) +> Vec<::models::Pet> FindPetsByTags(ctx, tags) Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -122,7 +122,7 @@ Name | Type | Description | Notes ### Return type -[**Vec<::models::pet::Pet>**](Pet.md) +[**Vec<::models::Pet>**](Pet.md) ### Authorization @@ -136,7 +136,7 @@ Name | Type | Description | Notes [[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) # **GetPetById** -> ::models::pet::Pet GetPetById(ctx, pet_id) +> ::models::Pet GetPetById(ctx, pet_id) Find pet by ID Returns a single pet @@ -150,7 +150,7 @@ Name | Type | Description | Notes ### Return type -[**::models::pet::Pet**](Pet.md) +[**::models::Pet**](Pet.md) ### Authorization @@ -230,7 +230,7 @@ Name | Type | Description | Notes [[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) # **UploadFile** -> ::models::api_response::ApiResponse UploadFile(ctx, pet_id, optional) +> ::models::ApiResponse UploadFile(ctx, pet_id, optional) uploads an image @@ -254,7 +254,7 @@ Name | Type | Description | Notes ### Return type -[**::models::api_response::ApiResponse**](ApiResponse.md) +[**::models::ApiResponse**](ApiResponse.md) ### Authorization diff --git a/samples/client/petstore/rust/docs/StoreApi.md b/samples/client/petstore/rust/docs/StoreApi.md index 7d38e21f421..f2c523db474 100644 --- a/samples/client/petstore/rust/docs/StoreApi.md +++ b/samples/client/petstore/rust/docs/StoreApi.md @@ -62,7 +62,7 @@ This endpoint does not need any parameter. [[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) # **GetOrderById** -> ::models::order::Order GetOrderById(order_id) +> ::models::Order GetOrderById(order_id) Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -75,7 +75,7 @@ Name | Type | Description | Notes ### Return type -[**::models::order::Order**](Order.md) +[**::models::Order**](Order.md) ### Authorization @@ -89,7 +89,7 @@ No authorization required [[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) # **PlaceOrder** -> ::models::order::Order PlaceOrder(body) +> ::models::Order PlaceOrder(body) Place an order for a pet @@ -102,7 +102,7 @@ Name | Type | Description | Notes ### Return type -[**::models::order::Order**](Order.md) +[**::models::Order**](Order.md) ### Authorization diff --git a/samples/client/petstore/rust/docs/UserApi.md b/samples/client/petstore/rust/docs/UserApi.md index 4a1d691760c..1ae4ba43937 100644 --- a/samples/client/petstore/rust/docs/UserApi.md +++ b/samples/client/petstore/rust/docs/UserApi.md @@ -51,7 +51,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Vec<::models::user::User>**](User.md)| List of user object | + **body** | [**Vec<::models::User>**](User.md)| List of user object | ### Return type @@ -78,7 +78,7 @@ Creates list of users with given input array Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**Vec<::models::user::User>**](User.md)| List of user object | + **body** | [**Vec<::models::User>**](User.md)| List of user object | ### Return type @@ -123,7 +123,7 @@ No authorization required [[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) # **GetUserByName** -> ::models::user::User GetUserByName(username) +> ::models::User GetUserByName(username) Get user by user name @@ -136,7 +136,7 @@ Name | Type | Description | Notes ### Return type -[**::models::user::User**](User.md) +[**::models::User**](User.md) ### Authorization diff --git a/samples/client/petstore/rust/src/apis/api_client.rs b/samples/client/petstore/rust/src/apis/api_client.rs deleted file mode 100644 index f629d8b8910..00000000000 --- a/samples/client/petstore/rust/src/apis/api_client.rs +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Swagger Petstore - * - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package swagger - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "errors" - "io" - "mime/multipart" - "golang.org/x/oauth2" - "golang.org/x/net/context" - "net/http" - "net/url" - "time" - "os" - "path/filepath" - "reflect" - "regexp" - "strings" - "unicode/utf8" - "strconv" -) - -var ( - jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") - xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") -) - -/// APIClient manages communication with the Swagger Petstore API v1.0.0 -/// In most cases there should be only one, shared, APIClient. -type APIClient struct { - cfg *Configuration - common service /// Reuse a single struct instead of allocating one for each service on the heap. - - /// API Services - PetApi *PetApiService - StoreApi *StoreApiService - UserApi *UserApiService -} - -type service struct { - client *APIClient -} - -/// NewAPIClient creates a new API client. Requires a userAgent string describing your application. -/// optionally a custom http.Client to allow for advanced features such as caching. -func NewAPIClient(cfg *Configuration) *APIClient { - if cfg.HTTPClient == nil { - cfg.HTTPClient = http.DefaultClient - } - - c := &APIClient{} - c.cfg = cfg - c.common.client = c - - /// API Services - c.PetApi = (*PetApiService)(&c.common) - c.StoreApi = (*StoreApiService)(&c.common) - c.UserApi = (*UserApiService)(&c.common) - - return c -} - -func atoi(in string) (int, error) { - return strconv.Atoi(in) -} - - -/// selectHeaderContentType select a content type from the available list. -func selectHeaderContentType(contentTypes []string) string { - if len(contentTypes) == 0 { - return "" - } - if contains(contentTypes, "application/json") { - return "application/json" - } - return contentTypes[0] /// use the first content type specified in 'consumes' -} - -/// selectHeaderAccept join all accept types and return -func selectHeaderAccept(accepts []string) string { - if len(accepts) == 0 { - return "" - } - - if contains(accepts, "application/json") { - return "application/json" - } - - return strings.Join(accepts, ",") -} - -/// contains is a case insenstive match, finding needle in a haystack -func contains(haystack []string, needle string) bool { - for _, a := range haystack { - if strings.ToLower(a) == strings.ToLower(needle) { - return true - } - } - return false -} - -/// Verify optional parameters are of the correct type. -func typeCheckParameter(obj interface{}, expected string, name string) error { - /// Make sure there is an object. - if obj == nil { - return nil - } - - /// Check the type is as expected. - if reflect.TypeOf(obj).String() != expected { - return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) - } - return nil -} - -/// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. -func parameterToString(obj interface{}, collectionFormat string) string { - var delimiter string - - switch collectionFormat { - case "pipes": - delimiter = "|" - case "ssv": - delimiter = " " - case "tsv": - delimiter = "\t" - case "csv": - delimiter = "," - } - - if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") - } - - return fmt.Sprintf("%v", obj) -} - -/// callAPI do the request. -func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { - return c.cfg.HTTPClient.Do(request) -} - -/// Change base path to allow switching to mocks -func (c *APIClient) ChangeBasePath (path string) { - c.cfg.BasePath = path -} - -/// prepareRequest build the request -func (c *APIClient) prepareRequest ( - ctx context.Context, - path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams url.Values, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { - - var body *bytes.Buffer - - /// Detect postBody type and post. - if postBody != nil { - contentType := headerParams["Content-Type"] - if contentType == "" { - contentType = detectContentType(postBody) - headerParams["Content-Type"] = contentType - } - - body, err = setBody(postBody, contentType) - if err != nil { - return nil, err - } - } - - /// add form paramters and file if available. - if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { - if body != nil { - return nil, errors.New("Cannot specify postBody and multipart form at the same time.") - } - body = &bytes.Buffer{} - w := multipart.NewWriter(body) - - for k, v := range formParams { - for _, iv := range v { - if strings.HasPrefix(k, "@") { /// file - err = addFile(w, k[1:], iv) - if err != nil { - return nil, err - } - } else { /// form value - w.WriteField(k, iv) - } - } - } - if len(fileBytes) > 0 && fileName != "" { - w.Boundary() - ///_, fileNm := filepath.Split(fileName) - part, err := w.CreateFormFile("file", filepath.Base(fileName)) - if err != nil { - return nil, err - } - _, err = part.Write(fileBytes) - if err != nil { - return nil, err - } - /// Set the Boundary in the Content-Type - headerParams["Content-Type"] = w.FormDataContentType() - } - - /// Set Content-Length - headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) - w.Close() - } - - /// Setup path and query paramters - url, err := url.Parse(path) - if err != nil { - return nil, err - } - - /// Adding Query Param - query := url.Query() - for k, v := range queryParams { - for _, iv := range v { - query.Add(k, iv) - } - } - - /// Encode the parameters. - url.RawQuery = query.Encode() - - /// Generate a new request - if body != nil { - localVarRequest, err = http.NewRequest(method, url.String(), body) - } else { - localVarRequest, err = http.NewRequest(method, url.String(), nil) - } - if err != nil { - return nil, err - } - - /// add header parameters, if any - if len(headerParams) > 0 { - headers := http.Header{} - for h, v := range headerParams { - headers.Set(h, v) - } - localVarRequest.Header = headers - } - - /// Add the user agent to the request. - localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) - - /// Walk through any authentication. - if ctx != nil { - /// OAuth2 authentication - if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { - /// We were able to grab an oauth2 token from the context - var latestToken *oauth2.Token - if latestToken, err = tok.Token(); err != nil { - return nil, err - } - - latestToken.SetAuthHeader(localVarRequest) - } - - /// Basic HTTP Authentication - if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { - localVarRequest.SetBasicAuth(auth.UserName, auth.Password) - } - - /// AccessToken Authentication - if auth, ok := ctx.Value(ContextAccessToken).(string); ok { - localVarRequest.Header.Add("Authorization", "Bearer " + auth) - } - } - - for header, value := range c.cfg.DefaultHeader { - localVarRequest.Header.Add(header, value) - } - - return localVarRequest, nil -} - - -/// Add a file to the multipart request -func addFile(w *multipart.Writer, fieldName, path string) error { - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - - part, err := w.CreateFormFile(fieldName, filepath.Base(path)) - if err != nil { - return err - } - _, err = io.Copy(part, file) - - return err -} - -/// Prevent trying to import "fmt" -func reportError(format string, a ...interface{}) (error) { - return fmt.Errorf(format, a...) -} - -/// Set request body from an interface{} -func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { - if bodyBuf == nil { - bodyBuf = &bytes.Buffer{} - } - - if reader, ok := body.(io.Reader); ok { - _, err = bodyBuf.ReadFrom(reader) - } else if b, ok := body.([]byte); ok { - _, err = bodyBuf.Write(b) - } else if s, ok := body.(string); ok { - _, err = bodyBuf.WriteString(s) - } else if jsonCheck.MatchString(contentType) { - err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { - xml.NewEncoder(bodyBuf).Encode(body) - } - - if err != nil { - return nil, err - } - - if bodyBuf.Len() == 0 { - err = fmt.Errorf("Invalid body type %s\n", contentType) - return nil, err - } - return bodyBuf, nil -} - -/// detectContentType method is used to figure out `Request.Body` content type for request header -func detectContentType(body interface{}) string { - contentType := "text/plain; charset=utf-8" - kind := reflect.TypeOf(body).Kind() - - switch kind { - case reflect.Struct, reflect.Map, reflect.Ptr: - contentType = "application/json; charset=utf-8" - case reflect.String: - contentType = "text/plain; charset=utf-8" - default: - if b, ok := body.([]byte); ok { - contentType = http.DetectContentType(b) - } else if kind == reflect.Slice { - contentType = "application/json; charset=utf-8" - } - } - - return contentType -} - - -/// Ripped from https:///github.com/gregjones/httpcache/blob/master/httpcache.go -type cacheControl map[string]string - -func parseCacheControl(headers http.Header) cacheControl { - cc := cacheControl{} - ccHeader := headers.Get("Cache-Control") - for _, part := range strings.Split(ccHeader, ",") { - part = strings.Trim(part, " ") - if part == "" { - continue - } - if strings.ContainsRune(part, '=') { - keyval := strings.Split(part, "=") - cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") - } else { - cc[part] = "" - } - } - return cc -} - -/// CacheExpires helper function to determine remaining time before repeating a request. -func CacheExpires(r *http.Response) (time.Time) { - /// Figure out when the cache expires. - var expires time.Time - now, err := time.Parse(time.RFC1123, r.Header.Get("date")) - if err != nil { - return time.Now() - } - respCacheControl := parseCacheControl(r.Header) - - if maxAge, ok := respCacheControl["max-age"]; ok { - lifetime, err := time.ParseDuration(maxAge + "s") - if err != nil { - expires = now - } - expires = now.Add(lifetime) - } else { - expiresHeader := r.Header.Get("Expires") - if expiresHeader != "" { - expires, err = time.Parse(time.RFC1123, expiresHeader) - if err != nil { - expires = now - } - } - } - return expires -} - -func strlen(s string) (int) { - return utf8.RuneCountInString(s) -} - diff --git a/samples/client/petstore/rust/src/apis/client.rs b/samples/client/petstore/rust/src/apis/client.rs index c239fc77a76..de8387bfe59 100644 --- a/samples/client/petstore/rust/src/apis/client.rs +++ b/samples/client/petstore/rust/src/apis/client.rs @@ -2,36 +2,35 @@ use std::rc::Rc; use hyper; use super::configuration::Configuration; -use super::pet_api; pub struct APIClient { configuration: Rc>, - pet_api: Box, - store_api: Box, - user_api: Box, + pet_api: Box<::apis::PetApi>, + store_api: Box<::apis::StoreApi>, + user_api: Box<::apis::UserApi>, } impl APIClient { pub fn new(configuration: Configuration) -> APIClient { let rc = Rc::new(configuration); - + APIClient { configuration: rc.clone(), - pet_api: Box::new(pet_api::PetApiImpl::new(rc.clone())), - store_api: Box::new(store_api::StoreApiImpl::new(rc.clone())), - user_api: Box::new(user_api::UserApiImpl::new(rc.clone())), + pet_api: Box::new(::apis::PetApiClient::new(rc.clone())), + store_api: Box::new(::apis::StoreApiClient::new(rc.clone())), + user_api: Box::new(::apis::UserApiClient::new(rc.clone())), } } - pub fn pet_api(&self) -> &pet_api::PetApi{ + pub fn pet_api(&self) -> &::apis::PetApi{ self.pet_api.as_ref() } - pub fn store_api(&self) -> &store_api::StoreApi{ + pub fn store_api(&self) -> &::apis::StoreApi{ self.store_api.as_ref() } - pub fn user_api(&self) -> &user_api::UserApi{ + pub fn user_api(&self) -> &::apis::UserApi{ self.user_api.as_ref() } diff --git a/samples/client/petstore/rust/src/apis/mod.rs b/samples/client/petstore/rust/src/apis/mod.rs index 4dd5322506b..ebd01fe651a 100644 --- a/samples/client/petstore/rust/src/apis/mod.rs +++ b/samples/client/petstore/rust/src/apis/mod.rs @@ -22,17 +22,11 @@ impl From for Error { use super::models::*; mod pet_api; - -pub use self::pet_api::PetApi; - +pub use self::pet_api::{ PetApi, PetApiClient }; mod store_api; - -pub use self::store_api::StoreApi; - +pub use self::store_api::{ StoreApi, StoreApiClient }; mod user_api; - -pub use self::user_api::UserApi; - +pub use self::user_api::{ UserApi, UserApiClient }; pub mod configuration; pub mod client; diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs index 306787088b3..7c8249585cf 100644 --- a/samples/client/petstore/rust/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/src/apis/pet_api.rs @@ -18,42 +18,47 @@ use futures::{Future, Stream}; use super::{Error, configuration}; -pub struct PetApiImpl { +pub struct PetApiClient { configuration: Rc>, } -impl PetApiImpl { - pub fn new(configuration: Rc>) -> PetApiImpl { - PetApiImpl { +impl PetApiClient { + pub fn new(configuration: Rc>) -> PetApiClient { + PetApiClient { configuration: configuration, } } } pub trait PetApi { - fn AddPet(&self, body: Pet) -> Box>; + fn AddPet(&self, body: ::models::Pet) -> Box>; fn DeletePet(&self, pet_id: i64, api_key: &str) -> Box>; - fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>>; - fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>>; - fn GetPetById(&self, pet_id: i64) -> Box>; - fn UpdatePet(&self, body: Pet) -> Box>; + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>>; + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>>; + fn GetPetById(&self, pet_id: i64) -> Box>; + fn UpdatePet(&self, body: ::models::Pet) -> Box>; fn UpdatePetWithForm(&self, pet_id: i64, name: &str, status: &str) -> Box>; - fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box>; + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box>; } -implPetApi for PetApiImpl { - fn AddPet(&self, body: Pet) -> Box> { +implPetApi for PetApiClient { + fn AddPet(&self, body: ::models::Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/pet", configuration.base_path); + let uri_str = format!("{}/pet", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -71,12 +76,19 @@ implPetApi for PetApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let mut headers = req.headers_mut(); - headers.set_raw("api_key", api_key); + { + let mut headers = req.headers_mut(); + headers.set_raw("api_key", api_key); + } // send request @@ -87,17 +99,22 @@ implPetApi for PetApiImpl { ) } - fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { + fn FindPetsByStatus(&self, status: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("status", status) + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("status", &status.join(",").to_string()) .finish(); - let uri = format!("{}/pet/findByStatus{}", configuration.base_path, query); + let uri_str = format!("{}/pet/findByStatus{}", configuration.base_path, query); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -106,23 +123,28 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result, _> = serde_json::from_slice(&body); + let parsed: Result, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { + fn FindPetsByTags(&self, tags: Vec) -> Box, Error = Error>> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("tags", tags) + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("tags", &tags.join(",").to_string()) .finish(); - let uri = format!("{}/pet/findByTags{}", configuration.base_path, query); + let uri_str = format!("{}/pet/findByTags{}", configuration.base_path, query); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -131,20 +153,25 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result, _> = serde_json::from_slice(&body); + let parsed: Result, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn GetPetById(&self, pet_id: i64) -> Box> { + fn GetPetById(&self, pet_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -153,23 +180,28 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::pet::Pet, _> = serde_json::from_slice(&body); + let parsed: Result<::models::Pet, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn UpdatePet(&self, body: Pet) -> Box> { + fn UpdatePet(&self, body: ::models::Pet) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Put; - let uri = format!("{}/pet", configuration.base_path); + let uri_str = format!("{}/pet", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -187,9 +219,14 @@ implPetApi for PetApiImpl { let method = hyper::Method::Post; - let uri = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -201,14 +238,19 @@ implPetApi for PetApiImpl { ) } - fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: File) -> Box> { + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); + let uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -217,7 +259,7 @@ implPetApi for PetApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::api_response::ApiResponse, _> = serde_json::from_slice(&body); + let parsed: Result<::models::ApiResponse, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs index 192c5feae59..f6165a22d45 100644 --- a/samples/client/petstore/rust/src/apis/store_api.rs +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -18,13 +18,13 @@ use futures::{Future, Stream}; use super::{Error, configuration}; -pub struct StoreApiImpl { +pub struct StoreApiClient { configuration: Rc>, } -impl StoreApiImpl { - pub fn new(configuration: Rc>) -> StoreApiImpl { - StoreApiImpl { +impl StoreApiClient { + pub fn new(configuration: Rc>) -> StoreApiClient { + StoreApiClient { configuration: configuration, } } @@ -33,20 +33,25 @@ impl StoreApiImpl { pub trait StoreApi { fn DeleteOrder(&self, order_id: &str) -> Box>; fn GetInventory(&self, ) -> Box, Error = Error>>; - fn GetOrderById(&self, order_id: i64) -> Box>; - fn PlaceOrder(&self, body: Order) -> Box>; + fn GetOrderById(&self, order_id: i64) -> Box>; + fn PlaceOrder(&self, body: ::models::Order) -> Box>; } -implStoreApi for StoreApiImpl { +implStoreApi for StoreApiClient { fn DeleteOrder(&self, order_id: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Delete; - let uri = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -63,9 +68,14 @@ implStoreApi for StoreApiImpl { let method = hyper::Method::Get; - let uri = format!("{}/store/inventory", configuration.base_path); + let uri_str = format!("{}/store/inventory", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -80,14 +90,19 @@ implStoreApi for StoreApiImpl { ) } - fn GetOrderById(&self, order_id: i64) -> Box> { + fn GetOrderById(&self, order_id: i64) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -96,23 +111,28 @@ implStoreApi for StoreApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::order::Order, _> = serde_json::from_slice(&body); + let parsed: Result<::models::Order, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) } - fn PlaceOrder(&self, body: Order) -> Box> { + fn PlaceOrder(&self, body: ::models::Order) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/store/order", configuration.base_path); + let uri_str = format!("{}/store/order", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -122,7 +142,7 @@ implStoreApi for StoreApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::order::Order, _> = serde_json::from_slice(&body); + let parsed: Result<::models::Order, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs index e306db6cb1e..49925d7b336 100644 --- a/samples/client/petstore/rust/src/apis/user_api.rs +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -18,42 +18,47 @@ use futures::{Future, Stream}; use super::{Error, configuration}; -pub struct UserApiImpl { +pub struct UserApiClient { configuration: Rc>, } -impl UserApiImpl { - pub fn new(configuration: Rc>) -> UserApiImpl { - UserApiImpl { +impl UserApiClient { + pub fn new(configuration: Rc>) -> UserApiClient { + UserApiClient { configuration: configuration, } } } pub trait UserApi { - fn CreateUser(&self, body: User) -> Box>; - fn CreateUsersWithArrayInput(&self, body: Vec<::models::user::User>) -> Box>; - fn CreateUsersWithListInput(&self, body: Vec<::models::user::User>) -> Box>; + fn CreateUser(&self, body: ::models::User) -> Box>; + fn CreateUsersWithArrayInput(&self, body: Vec<::models::User>) -> Box>; + fn CreateUsersWithListInput(&self, body: Vec<::models::User>) -> Box>; fn DeleteUser(&self, username: &str) -> Box>; - fn GetUserByName(&self, username: &str) -> Box>; + fn GetUserByName(&self, username: &str) -> Box>; fn LoginUser(&self, username: &str, password: &str) -> Box>; fn LogoutUser(&self, ) -> Box>; - fn UpdateUser(&self, username: &str, body: User) -> Box>; + fn UpdateUser(&self, username: &str, body: ::models::User) -> Box>; } -implUserApi for UserApiImpl { - fn CreateUser(&self, body: User) -> Box> { +implUserApi for UserApiClient { + fn CreateUser(&self, body: ::models::User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user", configuration.base_path); + let uri_str = format!("{}/user", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -66,17 +71,22 @@ implUserApi for UserApiImpl { ) } - fn CreateUsersWithArrayInput(&self, body: Vec<::models::user::User>) -> Box> { + fn CreateUsersWithArrayInput(&self, body: Vec<::models::User>) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user/createWithArray", configuration.base_path); + let uri_str = format!("{}/user/createWithArray", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -89,17 +99,22 @@ implUserApi for UserApiImpl { ) } - fn CreateUsersWithListInput(&self, body: Vec<::models::user::User>) -> Box> { + fn CreateUsersWithListInput(&self, body: Vec<::models::User>) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Post; - let uri = format!("{}/user/createWithList", configuration.base_path); + let uri_str = format!("{}/user/createWithList", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); @@ -117,9 +132,14 @@ implUserApi for UserApiImpl { let method = hyper::Method::Delete; - let uri = format!("{}/user/{username}", configuration.base_path, username=username); + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -131,14 +151,19 @@ implUserApi for UserApiImpl { ) } - fn GetUserByName(&self, username: &str) -> Box> { + fn GetUserByName(&self, username: &str) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Get; - let uri = format!("{}/user/{username}", configuration.base_path, username=username); + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -147,7 +172,7 @@ implUserApi for UserApiImpl { configuration.client.request(req).and_then(|res| { res.body().concat2() }) .map_err(|e| Error::from(e)) .and_then(|body| { - let parsed: Result<::models::user::User, _> = serde_json::from_slice(&body); + let parsed: Result<::models::User, _> = serde_json::from_slice(&body); parsed.map_err(|e| Error::from(e)) }).map_err(|e| Error::from(e)) ) @@ -158,13 +183,18 @@ implUserApi for UserApiImpl { let method = hyper::Method::Get; - let query = url::form_urlencoded::Serializer::new(String::new()) - .append_pair("username", username) - .append_pair("password", password) + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("username", &username.to_string()) + .append_pair("password", &password.to_string()) .finish(); - let uri = format!("{}/user/login{}", configuration.base_path, query); + let uri_str = format!("{}/user/login{}", configuration.base_path, query); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -184,9 +214,14 @@ implUserApi for UserApiImpl { let method = hyper::Method::Get; - let uri = format!("{}/user/logout", configuration.base_path); + let uri_str = format!("{}/user/logout", configuration.base_path); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); @@ -198,17 +233,22 @@ implUserApi for UserApiImpl { ) } - fn UpdateUser(&self, username: &str, body: User) -> Box> { + fn UpdateUser(&self, username: &str, body: ::models::User) -> Box> { let configuration: &configuration::Configuration = self.configuration.borrow(); let method = hyper::Method::Put; - let uri = format!("{}/user/{username}", configuration.base_path, username=username); + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); - let mut req = hyper::Request::new(method, uri); + let uri = uri_str.parse(); + // TODO(farcaller): handle error + // if let Err(e) = uri { + // return Box::new(futures::future::err(e)); + // } + let mut req = hyper::Request::new(method, uri.unwrap()); - let serialized = serde_json::to_string(body).unwrap(); + let serialized = serde_json::to_string(&body).unwrap(); req.headers_mut().set(hyper::header::ContentType::json()); req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64)); req.set_body(serialized); diff --git a/samples/client/petstore/rust/src/models/mod.rs b/samples/client/petstore/rust/src/models/mod.rs index b4495b6a5fc..b24024670b2 100644 --- a/samples/client/petstore/rust/src/models/mod.rs +++ b/samples/client/petstore/rust/src/models/mod.rs @@ -10,3 +10,6 @@ mod tag; pub use self::tag::Tag; mod user; pub use self::user::User; + +// TODO(farcaller): sort out files +pub struct File; diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index 95ec4c8cae9..213f5fd1851 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -13,10 +13,10 @@ #[derive(Debug, Serialize, Deserialize)] pub struct Pet { #[serde(rename = "id")] id: Option, - #[serde(rename = "category")] category: Option, + #[serde(rename = "category")] category: Option<::models::Category>, #[serde(rename = "name")] name: String, #[serde(rename = "photoUrls")] photo_urls: Vec, - #[serde(rename = "tags")] tags: Option>, + #[serde(rename = "tags")] tags: Option>, /// pet status in the store #[serde(rename = "status")] status: Option } @@ -43,11 +43,11 @@ impl Pet { self } - pub fn set_category(&mut self, category: ::models::category::Category) { + pub fn set_category(&mut self, category: ::models::Category) { self.category = Some(category); } - pub fn with_category(mut self, category: ::models::category::Category) -> Pet { + pub fn with_category(mut self, category: ::models::Category) -> Pet { self.category = Some(category); self } @@ -70,11 +70,11 @@ impl Pet { self } - pub fn set_tags(&mut self, tags: Vec<::models::tag::Tag>) { + pub fn set_tags(&mut self, tags: Vec<::models::Tag>) { self.tags = Some(tags); } - pub fn with_tags(mut self, tags: Vec<::models::tag::Tag>) -> Pet { + pub fn with_tags(mut self, tags: Vec<::models::Tag>) -> Pet { self.tags = Some(tags); self } From 74a1660c4c6c2f9e28055940f3c0e33732175a6a Mon Sep 17 00:00:00 2001 From: Vladimir Pouzanov Date: Sun, 6 Aug 2017 09:05:55 +0100 Subject: [PATCH 21/22] Added trivial getter implementation (#6249) --- .../swagger-codegen/src/main/resources/rust/model.mustache | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/rust/model.mustache b/modules/swagger-codegen/src/main/resources/rust/model.mustache index f893e744239..d841f482c01 100644 --- a/modules/swagger-codegen/src/main/resources/rust/model.mustache +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -37,6 +37,10 @@ impl {{classname}} { self } + pub fn {{name}}(&self) -> &{{datatype}} { + &self.{{name}} + } + {{/vars}} } From 15f89e295e0ce6773e748534b6ffabb5614065f4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 6 Aug 2017 16:09:09 +0800 Subject: [PATCH 22/22] update rust petstore samples --- .../petstore/rust/src/models/api_response.rs | 12 +++++++ .../petstore/rust/src/models/category.rs | 8 +++++ .../client/petstore/rust/src/models/order.rs | 24 ++++++++++++++ .../client/petstore/rust/src/models/pet.rs | 24 ++++++++++++++ .../client/petstore/rust/src/models/tag.rs | 8 +++++ .../client/petstore/rust/src/models/user.rs | 32 +++++++++++++++++++ 6 files changed, 108 insertions(+) diff --git a/samples/client/petstore/rust/src/models/api_response.rs b/samples/client/petstore/rust/src/models/api_response.rs index 47bf363daa0..8597a1a4df5 100644 --- a/samples/client/petstore/rust/src/models/api_response.rs +++ b/samples/client/petstore/rust/src/models/api_response.rs @@ -36,6 +36,10 @@ impl ApiResponse { self } + pub fn code(&self) -> &i32 { + &self.code + } + pub fn set__type(&mut self, _type: String) { self._type = Some(_type); } @@ -45,6 +49,10 @@ impl ApiResponse { self } + pub fn _type(&self) -> &String { + &self._type + } + pub fn set_message(&mut self, message: String) { self.message = Some(message); } @@ -54,6 +62,10 @@ impl ApiResponse { self } + pub fn message(&self) -> &String { + &self.message + } + } diff --git a/samples/client/petstore/rust/src/models/category.rs b/samples/client/petstore/rust/src/models/category.rs index 39c4979e5f9..109d67aec79 100644 --- a/samples/client/petstore/rust/src/models/category.rs +++ b/samples/client/petstore/rust/src/models/category.rs @@ -34,6 +34,10 @@ impl Category { self } + pub fn id(&self) -> &i64 { + &self.id + } + pub fn set_name(&mut self, name: String) { self.name = Some(name); } @@ -43,6 +47,10 @@ impl Category { self } + pub fn name(&self) -> &String { + &self.name + } + } diff --git a/samples/client/petstore/rust/src/models/order.rs b/samples/client/petstore/rust/src/models/order.rs index c012ed37fde..5b6a40bea88 100644 --- a/samples/client/petstore/rust/src/models/order.rs +++ b/samples/client/petstore/rust/src/models/order.rs @@ -43,6 +43,10 @@ impl Order { self } + pub fn id(&self) -> &i64 { + &self.id + } + pub fn set_pet_id(&mut self, pet_id: i64) { self.pet_id = Some(pet_id); } @@ -52,6 +56,10 @@ impl Order { self } + pub fn pet_id(&self) -> &i64 { + &self.pet_id + } + pub fn set_quantity(&mut self, quantity: i32) { self.quantity = Some(quantity); } @@ -61,6 +69,10 @@ impl Order { self } + pub fn quantity(&self) -> &i32 { + &self.quantity + } + pub fn set_ship_date(&mut self, ship_date: String) { self.ship_date = Some(ship_date); } @@ -70,6 +82,10 @@ impl Order { self } + pub fn ship_date(&self) -> &String { + &self.ship_date + } + pub fn set_status(&mut self, status: String) { self.status = Some(status); } @@ -79,6 +95,10 @@ impl Order { self } + pub fn status(&self) -> &String { + &self.status + } + pub fn set_complete(&mut self, complete: bool) { self.complete = Some(complete); } @@ -88,6 +108,10 @@ impl Order { self } + pub fn complete(&self) -> &bool { + &self.complete + } + } diff --git a/samples/client/petstore/rust/src/models/pet.rs b/samples/client/petstore/rust/src/models/pet.rs index 213f5fd1851..e1d04e749fd 100644 --- a/samples/client/petstore/rust/src/models/pet.rs +++ b/samples/client/petstore/rust/src/models/pet.rs @@ -43,6 +43,10 @@ impl Pet { self } + pub fn id(&self) -> &i64 { + &self.id + } + pub fn set_category(&mut self, category: ::models::Category) { self.category = Some(category); } @@ -52,6 +56,10 @@ impl Pet { self } + pub fn category(&self) -> &::models::Category { + &self.category + } + pub fn set_name(&mut self, name: String) { self.name = name; } @@ -61,6 +69,10 @@ impl Pet { self } + pub fn name(&self) -> &String { + &self.name + } + pub fn set_photo_urls(&mut self, photo_urls: Vec) { self.photo_urls = photo_urls; } @@ -70,6 +82,10 @@ impl Pet { self } + pub fn photo_urls(&self) -> &Vec<String> { + &self.photo_urls + } + pub fn set_tags(&mut self, tags: Vec<::models::Tag>) { self.tags = Some(tags); } @@ -79,6 +95,10 @@ impl Pet { self } + pub fn tags(&self) -> &Vec<::models::Tag> { + &self.tags + } + pub fn set_status(&mut self, status: String) { self.status = Some(status); } @@ -88,6 +108,10 @@ impl Pet { self } + pub fn status(&self) -> &String { + &self.status + } + } diff --git a/samples/client/petstore/rust/src/models/tag.rs b/samples/client/petstore/rust/src/models/tag.rs index 1ac30f30788..59dcd8c1cce 100644 --- a/samples/client/petstore/rust/src/models/tag.rs +++ b/samples/client/petstore/rust/src/models/tag.rs @@ -34,6 +34,10 @@ impl Tag { self } + pub fn id(&self) -> &i64 { + &self.id + } + pub fn set_name(&mut self, name: String) { self.name = Some(name); } @@ -43,6 +47,10 @@ impl Tag { self } + pub fn name(&self) -> &String { + &self.name + } + } diff --git a/samples/client/petstore/rust/src/models/user.rs b/samples/client/petstore/rust/src/models/user.rs index c6848bb0f32..fb5d417eeb4 100644 --- a/samples/client/petstore/rust/src/models/user.rs +++ b/samples/client/petstore/rust/src/models/user.rs @@ -47,6 +47,10 @@ impl User { self } + pub fn id(&self) -> &i64 { + &self.id + } + pub fn set_username(&mut self, username: String) { self.username = Some(username); } @@ -56,6 +60,10 @@ impl User { self } + pub fn username(&self) -> &String { + &self.username + } + pub fn set_first_name(&mut self, first_name: String) { self.first_name = Some(first_name); } @@ -65,6 +73,10 @@ impl User { self } + pub fn first_name(&self) -> &String { + &self.first_name + } + pub fn set_last_name(&mut self, last_name: String) { self.last_name = Some(last_name); } @@ -74,6 +86,10 @@ impl User { self } + pub fn last_name(&self) -> &String { + &self.last_name + } + pub fn set_email(&mut self, email: String) { self.email = Some(email); } @@ -83,6 +99,10 @@ impl User { self } + pub fn email(&self) -> &String { + &self.email + } + pub fn set_password(&mut self, password: String) { self.password = Some(password); } @@ -92,6 +112,10 @@ impl User { self } + pub fn password(&self) -> &String { + &self.password + } + pub fn set_phone(&mut self, phone: String) { self.phone = Some(phone); } @@ -101,6 +125,10 @@ impl User { self } + pub fn phone(&self) -> &String { + &self.phone + } + pub fn set_user_status(&mut self, user_status: i32) { self.user_status = Some(user_status); } @@ -110,6 +138,10 @@ impl User { self } + pub fn user_status(&self) -> &i32 { + &self.user_status + } + }