From 4cb7f1d6135aa3a42ff38cf89771105c40e7e5a9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 6 Aug 2017 16:59:08 +0800 Subject: [PATCH] [Rust] add new Rust client generator (#6105) * add rust generator (1st release) * update based on feedback * fix reserved keyword * fix string parameter * Convert String to &str in trait definition * Only pass pathParams to uri builder * Fixed the html escaping in return type * Fixed the hashmap constructor * Added models into API scope * removed models subimport, reference from super * update returntype in method signature * Fixed the remaining templates inconsistencies * Fixed issues that floated up in kubernetes swagger file * add hash support, fix docstring * fix map parameter, update api.mustache * use baseName for parameter * use fully-qualfiied model name * add rust tests * fix test cases * 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 * Added trivial getter implementation (#6249) * update rust petstore samples --- bin/rust-petstore.sh | 31 ++ bin/windows/rust-petstore.bat | 10 + .../codegen/languages/RustClientCodegen.java | 483 ++++++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../src/main/resources/rust/.travis.yml | 1 + .../src/main/resources/rust/Cargo.mustache | 17 + .../src/main/resources/rust/README.mustache | 96 ++++ .../src/main/resources/rust/api.mustache | 96 ++++ .../src/main/resources/rust/api_doc.mustache | 50 ++ .../src/main/resources/rust/api_mod.mustache | 38 ++ .../src/main/resources/rust/client.mustache | 56 ++ .../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 | 61 +++ .../main/resources/rust/model_doc.mustache | 11 + .../main/resources/rust/model_mod.mustache | 9 + .../resources/rust/partial_header.mustache | 13 + .../options/RustClientOptionsProvider.java | 33 ++ .../codegen/rust/RustClientOptionsTest.java | 35 ++ .../petstore/rust/.swagger-codegen-ignore | 23 + .../petstore/rust/.swagger-codegen/VERSION | 1 + samples/client/petstore/rust/.travis.yml | 1 + 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 ++++ .../client/petstore/rust/src/apis/client.rs | 24 +- .../petstore/rust/src/apis/configuration.rs | 12 +- samples/client/petstore/rust/src/apis/mod.rs | 19 +- .../client/petstore/rust/src/apis/pet_api.rs | 254 ++++++++- .../petstore/rust/src/apis/store_api.rs | 151 ++++++ .../client/petstore/rust/src/apis/user_api.rs | 264 ++++++++++ .../petstore/rust/src/models/api_response.rs | 72 +++ .../petstore/rust/src/models/category.rs | 59 ++- .../client/petstore/rust/src/models/mod.rs | 15 +- .../client/petstore/rust/src/models/order.rs | 118 +++++ .../client/petstore/rust/src/models/pet.rs | 106 +++- .../client/petstore/rust/src/models/tag.rs | 59 ++- .../client/petstore/rust/src/models/user.rs | 148 ++++++ 50 files changed, 3334 insertions(+), 62 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_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/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 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 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/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/languages/RustClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java new file mode 100644 index 00000000000..15caa76a245 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RustClientCodegen.java @@ -0,0 +1,483 @@ +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); + public static final String PACKAGE_NAME = "packageName"; + public static final String PACKAGE_VERSION = "packageVersion"; + + 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", "String", "Vec", "File") + ); + + 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"); + // TODO(farcaller): map file + typeMapping.put("file", "File"); + typeMapping.put("binary", "Vec"); + typeMapping.put("ByteArray", "String"); + // TODO what should 'object' mapped to + typeMapping.put("object", "Object"); + + // no need for rust + //importMapping = new HashMap(); + + 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(".travis.yml", "", ".travis.yml")); + + supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.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")); + } + + @Override + public String escapeReservedWord(String name) + { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return '_' + 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 "Vec<" + getTypeDeclaration(inner) + ">"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return "::std::collections::HashMap"; + } + + // 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 fully-qualified model name + // ::models::{{classnameFile}}::{{classname}} + return "::models::" + 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()); + // update return type to conform to rust standard + /* + if (operation.returnType != null) { + 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 = "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; + } + }*/ + } + + return objs; + } + + @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 f614d296153..27d63c44097 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..22761ba7ee1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/.travis.yml @@ -0,0 +1 @@ +language: rust 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..614745d5088 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/Cargo.mustache @@ -0,0 +1,17 @@ +[package] +name = "{{{packageName}}}" +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..67cc0280e2c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/README.mustache @@ -0,0 +1,96 @@ +# Rust 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..811f8870448 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/api.mustache @@ -0,0 +1,96 @@ +{{>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}; + +pub struct {{{classname}}}Client { + configuration: Rc>, +} + +impl {{{classname}}}Client { + pub fn new(configuration: Rc>) -> {{{classname}}}Client { + {{{classname}}}Client { + configuration: configuration, + } + } +} + +pub trait {{classname}} { +{{#operations}} +{{#operation}} + fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{^isString}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>; +{{/operation}} +{{/operations}} +} + + +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> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::{{httpMethod}}; + + {{^hasQueryParams}} + 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()) + {{#queryParams}} + .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}}); + {{/hasQueryParams}} + + 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}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}); + {{/headerParams}} + } + {{/hasHeaderParams}} + + {{#hasBodyParam}} + {{#bodyParams}} + 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}} + ) + } + +{{/operation}} +{{/operations}} +} 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..5b62b897cdd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/api_mod.mustache @@ -0,0 +1,38 @@ +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}} +mod {{classFilename}}; +{{#operations}} +{{#operation}} +{{#-last}} +pub use self::{{classFilename}}::{ {{classname}}, {{classname}}Client }; +{{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +pub mod configuration; +pub mod client; 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..faaea0dbd2f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/client.mustache @@ -0,0 +1,56 @@ +use std::rc::Rc; + +use hyper; +use super::configuration::Configuration; + +pub struct APIClient { + configuration: Rc>, +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{#-last}} + {{classFilename}}: Box<::apis::{{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(::apis::{{classname}}Client::new(rc.clone())), + {{/-last}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + } + } + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#-last}} + pub fn {{classFilename}}(&self) -> &::apis::{{classname}}{ + self.{{classFilename}}.as_ref() + } + +{{/-last}} +{{/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..d841f482c01 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/model.mustache @@ -0,0 +1,61 @@ +{{>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}}None{{/isListContainer}}{{#isMapContainer}}None{{/isMapContainer}}{{^isContainer}}None{{/isContainer}}{{/required}}{{#hasMore}},{{/hasMore}} + {{/vars}} + } + } + + {{#vars}} + pub fn set_{{name}}(&mut self, {{name}}: {{{datatype}}}) { + self.{{name}} = {{^required}}Some({{name}}){{/required}}{{#required}}{{name}}{{/required}}; + } + + pub fn with_{{name}}(mut self, {{name}}: {{{datatype}}}) -> {{classname}} { + self.{{name}} = {{^required}}Some({{name}}){{/required}}{{#required}}{{name}}{{/required}}; + self + } + + pub fn {{name}}(&self) -> &{{datatype}} { + &self.{{name}} + } + + {{/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..d2b7578f324 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rust/model_mod.mustache @@ -0,0 +1,9 @@ +{{#models}} +{{#model}} +mod {{{classFilename}}}; +pub use self::{{{classFilename}}}::{{{classname}}}; +{{/model}} +{{/models}} + +// TODO(farcaller): sort out files +pub struct File; 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/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..4ec12ea2b8f --- /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_test"; + 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; + }}; + } +} 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..22761ba7ee1 --- /dev/null +++ b/samples/client/petstore/rust/.travis.yml @@ -0,0 +1 @@ +language: rust diff --git a/samples/client/petstore/rust/Cargo.toml b/samples/client/petstore/rust/Cargo.toml index 8c2c024a747..ad18ef78781 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 = "swagger" +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..ee5f2426813 --- /dev/null +++ b/samples/client/petstore/rust/README.md @@ -0,0 +1,97 @@ +# 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. + +## 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..a34664707bd --- /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** | | [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 new file mode 100644 index 00000000000..6481bb566cd --- /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** | | [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..8a91ed5952a --- /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** | | [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 new file mode 100644 index 00000000000..ab2bef92432 --- /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** | [***::models::Category**](Category.md) | | [optional] [default to null] +**name** | **String** | | [default to null] +**photo_urls** | **Vec** | | [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 new file mode 100644 index 00000000000..82e8a231c37 --- /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** +> Vec<::models::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** | [**Vec<String>**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**Vec<::models::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** +> 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. + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context containing the authentication | nil if no authentication + **tags** | [**Vec<String>**](String.md)| Tags to filter by | + +### Return type + +[**Vec<::models::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** +> ::models::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 + +[**::models::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** +> ::models::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 + +[**::models::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..f2c523db474 --- /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** +> ::std::collections::HashMap 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 + +**::std::collections::HashMap** + +### 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** +> ::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 + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order_id** | **i64**| ID of pet that needs to be fetched | + +### Return type + +[**::models::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** +> ::models::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 + +[**::models::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..9c69cde1e03 --- /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** | | [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..d9b1f2a95b8 --- /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** | | [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 new file mode 100644 index 00000000000..1ae4ba43937 --- /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** | [**Vec<::models::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** | [**Vec<::models::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** +> ::models::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 + +[**::models::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** + +### 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/client.rs b/samples/client/petstore/rust/src/apis/client.rs index 606f0eba578..de8387bfe59 100644 --- a/samples/client/petstore/rust/src/apis/client.rs +++ b/samples/client/petstore/rust/src/apis/client.rs @@ -2,25 +2,37 @@ use std::rc::Rc; use hyper; use super::configuration::Configuration; -use super::pet_api; pub struct APIClient { configuration: Rc>, - - pet_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())), + 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) -> &::apis::StoreApi{ + self.store_api.as_ref() + } + + pub fn user_api(&self) -> &::apis::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/mod.rs b/samples/client/petstore/rust/src/apis/mod.rs index b1cba2957ef..ebd01fe651a 100644 --- a/samples/client/petstore/rust/src/apis/mod.rs +++ b/samples/client/petstore/rust/src/apis/mod.rs @@ -19,19 +19,14 @@ impl From for Error { } } -use super::models; +use super::models::*; -mod get_pet_by_id_api; -pub use self::get_pet_by_id_api::get_pet_by_id; - -mod update_pet_with_form_api; -pub use self::update_pet_with_form_api::update_pet_with_form; - -mod add_pet_api; -pub use self::add_pet_api::add_pet; +mod pet_api; +pub use self::pet_api::{ PetApi, PetApiClient }; +mod store_api; +pub use self::store_api::{ StoreApi, StoreApiClient }; +mod user_api; +pub use self::user_api::{ UserApi, UserApiClient }; 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 d413b95664b..7c8249585cf 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; @@ -6,39 +16,253 @@ use serde_json; use futures; use futures::{Future, Stream}; -use super::{Error, configuration, models}; +use super::{Error, configuration}; -pub trait PetAPI { - fn add_pet(&self, pet: &models::Pet) -> Box>; -} - -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, } } } -implPetAPI for PetAPIImpl { - fn add_pet(&self, pet: &models::Pet) -> Box> { +pub trait PetApi { + 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: ::models::Pet) -> Box>; + fn UpdatePetWithForm(&self, pet_id: i64, name: &str, status: &str) -> Box>; + fn UploadFile(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box>; +} + + +implPetApi for PetApiClient { + fn AddPet(&self, body: ::models::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()); - let serialized = serde_json::to_string(pet).unwrap(); + + let method = hyper::Method::Post; + + let uri_str = format!("{}/pet", configuration.base_path); + + 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(); 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(())) ) } + + fn DeletePet(&self, pet_id: i64, api_key: &str) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Delete; + + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + + 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); + } + + + // 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 method = hyper::Method::Get; + + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("status", &status.join(",").to_string()) + .finish(); + let uri_str = format!("{}/pet/findByStatus{}", configuration.base_path, query); + + 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()); + + + + // 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 method = hyper::Method::Get; + + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("tags", &tags.join(",").to_string()) + .finish(); + let uri_str = format!("{}/pet/findByTags{}", configuration.base_path, query); + + 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()); + + + + // 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 method = hyper::Method::Get; + + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + + 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()); + + + + // 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<::models::Pet, _> = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) + } + + fn UpdatePet(&self, body: ::models::Pet) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Put; + + let uri_str = format!("{}/pet", configuration.base_path); + + 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(); + 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(())) + ) + } + + fn UpdatePetWithForm(&self, pet_id: i64, name: &str, status: &str) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Post; + + let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + + 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()); + + + + // 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: ::models::File) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Post; + + let uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); + + 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()); + + + + // 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<::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 new file mode 100644 index 00000000000..f6165a22d45 --- /dev/null +++ b/samples/client/petstore/rust/src/apis/store_api.rs @@ -0,0 +1,151 @@ +/* + * 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}; + +pub struct StoreApiClient { + configuration: Rc>, +} + +impl StoreApiClient { + pub fn new(configuration: Rc>) -> StoreApiClient { + StoreApiClient { + configuration: configuration, + } + } +} + +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: ::models::Order) -> Box>; +} + + +implStoreApi for StoreApiClient { + fn DeleteOrder(&self, order_id: &str) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Delete; + + let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + + 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()); + + + + // 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 method = hyper::Method::Get; + + let uri_str = format!("{}/store/inventory", configuration.base_path); + + 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()); + + + + // 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, _> = 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 method = hyper::Method::Get; + + let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + + 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()); + + + + // 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<::models::Order, _> = serde_json::from_slice(&body); + parsed.map_err(|e| Error::from(e)) + }).map_err(|e| Error::from(e)) + ) + } + + fn PlaceOrder(&self, body: ::models::Order) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Post; + + let uri_str = format!("{}/store/order", configuration.base_path); + + 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(); + 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(|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 new file mode 100644 index 00000000000..49925d7b336 --- /dev/null +++ b/samples/client/petstore/rust/src/apis/user_api.rs @@ -0,0 +1,264 @@ +/* + * 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}; + +pub struct UserApiClient { + configuration: Rc>, +} + +impl UserApiClient { + pub fn new(configuration: Rc>) -> UserApiClient { + UserApiClient { + configuration: configuration, + } + } +} + +pub trait UserApi { + 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 LoginUser(&self, username: &str, password: &str) -> Box>; + fn LogoutUser(&self, ) -> Box>; + fn UpdateUser(&self, username: &str, body: ::models::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_str = format!("{}/user", configuration.base_path); + + 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(); + 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(())) + ) + } + + fn CreateUsersWithArrayInput(&self, body: Vec<::models::User>) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Post; + + let uri_str = format!("{}/user/createWithArray", configuration.base_path); + + 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(); + 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(())) + ) + } + + fn CreateUsersWithListInput(&self, body: Vec<::models::User>) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Post; + + let uri_str = format!("{}/user/createWithList", configuration.base_path); + + 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(); + 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(())) + ) + } + + fn DeleteUser(&self, username: &str) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Delete; + + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); + + 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()); + + + + // 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 method = hyper::Method::Get; + + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); + + 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()); + + + + // 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<::models::User, _> = 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> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Get; + + let query = ::url::form_urlencoded::Serializer::new(String::new()) + .append_pair("username", &username.to_string()) + .append_pair("password", &password.to_string()) + .finish(); + let uri_str = format!("{}/user/login{}", configuration.base_path, query); + + 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()); + + + + // 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 method = hyper::Method::Get; + + let uri_str = format!("{}/user/logout", configuration.base_path); + + 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()); + + + + // 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: ::models::User) -> Box> { + let configuration: &configuration::Configuration = self.configuration.borrow(); + + let method = hyper::Method::Put; + + let uri_str = format!("{}/user/{username}", configuration.base_path, username=username); + + 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(); + 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(())) + ) + } + +} 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..8597a1a4df5 --- /dev/null +++ b/samples/client/petstore/rust/src/models/api_response.rs @@ -0,0 +1,72 @@ +/* + * 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 code(&self) -> &i32 { + &self.code + } + + 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 _type(&self) -> &String { + &self._type + } + + 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 + } + + 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 c69e9d147bb..109d67aec79 100644 --- a/samples/client/petstore/rust/src/models/category.rs +++ b/samples/client/petstore/rust/src/models/category.rs @@ -1,8 +1,57 @@ -/// 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 id(&self) -> &i64 { + &self.id + } + + 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 + } + + pub fn name(&self) -> &String { + &self.name + } + +} + + + diff --git a/samples/client/petstore/rust/src/models/mod.rs b/samples/client/petstore/rust/src/models/mod.rs index 4b8e81e42d6..b24024670b2 100644 --- a/samples/client/petstore/rust/src/models/mod.rs +++ b/samples/client/petstore/rust/src/models/mod.rs @@ -1,8 +1,15 @@ -mod pet; -pub use self::pet::Pet; - +mod api_response; +pub use self::api_response::ApiResponse; mod category; pub use self::category::Category; - +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; + +// TODO(farcaller): sort out files +pub struct File; 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..5b6a40bea88 --- /dev/null +++ b/samples/client/petstore/rust/src/models/order.rs @@ -0,0 +1,118 @@ +/* + * 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 id(&self) -> &i64 { + &self.id + } + + 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 pet_id(&self) -> &i64 { + &self.pet_id + } + + 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 quantity(&self) -> &i32 { + &self.quantity + } + + 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 ship_date(&self) -> &String { + &self.ship_date + } + + 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 status(&self) -> &String { + &self.status + } + + 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 + } + + 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 c812a0dbccb..e1d04e749fd 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<::models::Category>, + #[serde(rename = "name")] name: String, + #[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: Vec) -> Pet { Pet { id: None, category: None, name: name, photo_urls: photo_urls, - tags: Vec::new(), - status: None, + tags: None, + status: None } } @@ -31,4 +42,77 @@ impl Pet { self.id = Some(id); self } + + pub fn id(&self) -> &i64 { + &self.id + } + + pub fn set_category(&mut self, category: ::models::Category) { + self.category = Some(category); + } + + pub fn with_category(mut self, category: ::models::Category) -> Pet { + self.category = Some(category); + self + } + + pub fn category(&self) -> &::models::Category { + &self.category + } + + pub fn set_name(&mut self, name: String) { + self.name = name; + } + + pub fn with_name(mut self, name: String) -> Pet { + self.name = name; + self + } + + pub fn name(&self) -> &String { + &self.name + } + + pub fn set_photo_urls(&mut self, photo_urls: Vec) { + self.photo_urls = photo_urls; + } + + pub fn with_photo_urls(mut self, photo_urls: Vec) -> Pet { + self.photo_urls = photo_urls; + 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); + } + + pub fn with_tags(mut self, tags: Vec<::models::Tag>) -> Pet { + self.tags = Some(tags); + self + } + + pub fn tags(&self) -> &Vec<::models::Tag> { + &self.tags + } + + 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 + } + + 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 2ebb742c8f7..59dcd8c1cce 100644 --- a/samples/client/petstore/rust/src/models/tag.rs +++ b/samples/client/petstore/rust/src/models/tag.rs @@ -1,8 +1,57 @@ -/// 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 id(&self) -> &i64 { + &self.id + } + + 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 + } + + 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 new file mode 100644 index 00000000000..fb5d417eeb4 --- /dev/null +++ b/samples/client/petstore/rust/src/models/user.rs @@ -0,0 +1,148 @@ +/* + * 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 id(&self) -> &i64 { + &self.id + } + + 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 username(&self) -> &String { + &self.username + } + + 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 first_name(&self) -> &String { + &self.first_name + } + + 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 last_name(&self) -> &String { + &self.last_name + } + + 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 email(&self) -> &String { + &self.email + } + + 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 password(&self) -> &String { + &self.password + } + + 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 phone(&self) -> &String { + &self.phone + } + + 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 + } + + pub fn user_status(&self) -> &i32 { + &self.user_status + } + +} + + +