diff --git a/.gitignore b/.gitignore index 2e1d1355309..ddb31ac6c90 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ samples/server-generator/scalatra/target samples/server-generator/scalatra/output/.history # nodejs +**/node_modules/ samples/server-generator/node/output/node_modules samples/server/petstore/nodejs/node_modules samples/server/petstore/nodejs-server/node_modules @@ -116,13 +117,6 @@ samples/client/petstore/python/.venv/ # ts samples/client/petstore/typescript-node/npm/node_modules -samples/client/petstore/typescript-fetch/with-package-metadata/node_modules -samples/client/petstore/typescript-fetch/with-package-metadata/dist -samples/client/petstore/typescript-fetch/with-package-metadata/typings -samples/client/petstore/typescript-fetch/default/node_modules -samples/client/petstore/typescript-fetch/default/dist -samples/client/petstore/typescript-fetch/default/typings -samples/client/petstore/typescript-fetch/default-es6/node_modules -samples/client/petstore/typescript-fetch/default-es6/dist -samples/client/petstore/typescript-fetch/default-es6/typings +samples/client/petstore/typescript-fetch/**/dist/ +samples/client/petstore/typescript-fetch/**/typings diff --git a/README.md b/README.md index bce750740c7..52c8b8c4749 100644 --- a/README.md +++ b/README.md @@ -608,7 +608,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ - -l silex \ + -l silex-PHP \ -o samples/server/petstore/silex ``` @@ -894,6 +894,7 @@ Here is a list of template creators: * JAX-RS CXF: @hiveship * PHP Lumen: @abcsum * PHP Slim: @jfastnacht + * Ruby on Rails 5: @zlx ## How to join the core team diff --git a/bin/android-petstore-httpclient.sh b/bin/android-petstore-httpclient.sh new file mode 100755 index 00000000000..097484e0410 --- /dev/null +++ b/bin/android-petstore-httpclient.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/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -Dlibrary=httpclient -o samples/client/petstore/android/httpclient" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/android-petstore.sh b/bin/android-petstore.sh index 72b12f92e55..67256debeb0 100755 --- a/bin/android-petstore.sh +++ b/bin/android-petstore.sh @@ -26,6 +26,6 @@ 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/android -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android/default" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android/volley" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/rails5-petstore-server.sh b/bin/rails5-petstore-server.sh new file mode 100755 index 00000000000..28b3ca3069b --- /dev/null +++ b/bin/rails5-petstore-server.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/rails5 -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l rails5 -o samples/server/petstore/rails5" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-all.sh b/bin/typescript-fetch-petstore-all.sh index d39c16d8803..6365b9032a6 100755 --- a/bin/typescript-fetch-petstore-all.sh +++ b/bin/typescript-fetch-petstore-all.sh @@ -1,5 +1,5 @@ #!/bin/sh ./bin/typescript-fetch-petstore-target-es6.sh -./bin/typescript-fetch-petstore-target-with-package-metadata.sh +./bin/typescript-fetch-petstore-with-npm-version.sh ./bin/typescript-fetch-petstore.sh diff --git a/bin/typescript-fetch-petstore-target-es6.sh b/bin/typescript-fetch-petstore-target-es6.sh index 3734e7e3449..84a6562eeb6 100755 --- a/bin/typescript-fetch-petstore-target-es6.sh +++ b/bin/typescript-fetch-petstore-target-es6.sh @@ -26,6 +26,6 @@ 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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/default-es6" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/builds/es6-target" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.json b/bin/typescript-fetch-petstore-with-npm-version.json similarity index 100% rename from bin/typescript-fetch-petstore-target-with-package-metadata.json rename to bin/typescript-fetch-petstore-with-npm-version.json diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.sh b/bin/typescript-fetch-petstore-with-npm-version.sh similarity index 88% rename from bin/typescript-fetch-petstore-target-with-package-metadata.sh rename to bin/typescript-fetch-petstore-with-npm-version.sh index 3c4978c8a80..fd9225f0e72 100755 --- a/bin/typescript-fetch-petstore-target-with-package-metadata.sh +++ b/bin/typescript-fetch-petstore-with-npm-version.sh @@ -26,6 +26,6 @@ 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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-with-package-metadata.json -o samples/client/petstore/typescript-fetch/with-package-metadata" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-with-npm-version.json -o samples/client/petstore/typescript-fetch/builds/with-npm-version" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore.sh b/bin/typescript-fetch-petstore.sh index 6283285c736..50d56f34609 100755 --- a/bin/typescript-fetch-petstore.sh +++ b/bin/typescript-fetch-petstore.sh @@ -26,6 +26,6 @@ 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 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/default" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/builds/default" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/rails-petstore-server.bat b/bin/windows/rails-petstore-server.bat new file mode 100644 index 00000000000..55677b55197 --- /dev/null +++ b/bin/windows/rails-petstore-server.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +set JAVA_OPTS=%JAVA_OPTS% -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -t modules\swagger-codegen\src\main\resources\rails5 -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l aspnet5 -o samples\server\petstore\rails5\ + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index 41ca44f7bac..34c4124320f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -33,7 +33,7 @@ public class CodegenModel { public Set allMandatory; public Set imports = new TreeSet(); - public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum; + public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired; public ExternalDocs externalDocs; public Map vendorExtensions; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 48858a0d504..9dfe0d45c88 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -7,13 +7,16 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.Arrays; public class CodegenOperation { public final List responseHeaders = new ArrayList(); public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, isListContainer, isMultipart, hasMore = Boolean.TRUE, - isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE; + isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE, + isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, + isRestful; public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator; public List> consumes, produces; @@ -88,6 +91,81 @@ public class CodegenOperation { return nonempty(formParams); } + /** + * Check if act as Restful index method + * + * @return true if act as Restful index method, false otherwise + */ + public boolean isRestfulIndex() { + return "GET".equals(httpMethod) && "".equals(pathWithoutBaseName()); + } + + /** + * Check if act as Restful show method + * + * @return true if act as Restful show method, false otherwise + */ + public boolean isRestfulShow() { + return "GET".equals(httpMethod) && isMemberPath(); + } + + /** + * Check if act as Restful create method + * + * @return true if act as Restful create method, false otherwise + */ + public boolean isRestfulCreate() { + return "POST".equals(httpMethod) && "".equals(pathWithoutBaseName()); + } + + /** + * Check if act as Restful update method + * + * @return true if act as Restful update method, false otherwise + */ + public boolean isRestfulUpdate() { + return Arrays.asList("PUT", "PATCH").contains(httpMethod) && isMemberPath(); + } + + /** + * Check if act as Restful destroy method + * + * @return true if act as Restful destroy method, false otherwise + */ + public boolean isRestfulDestroy() { + return "DELETE".equals(httpMethod) && isMemberPath(); + } + + /** + * Check if Restful-style + * + * @return true if Restful-style, false otherwise + */ + public boolean isRestful() { + return isRestfulIndex() || isRestfulShow() || isRestfulCreate() || isRestfulUpdate() || isRestfulDestroy(); + } + + /** + * Get the substring except baseName from path + * + * @return the substring + */ + private String pathWithoutBaseName() { + return baseName != null ? path.replace("/" + baseName.toLowerCase(), "") : path; + } + + /** + * Check if the path match format /xxx/:id + * + * @return true if path act as member + */ + private boolean isMemberPath() { + if (pathParams.size() != 1) return false; + + String id = pathParams.get(0).baseName; + return ("/{" + id + "}").equals(pathWithoutBaseName()); + } + @Override public String toString() { return String.format("%s(%s)", baseName, path); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 231f1ef0210..cb7164cc1f9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1901,6 +1901,14 @@ public class DefaultCodegen { } op.externalDocs = operation.getExternalDocs(); + // set Restful Flag + op.isRestfulShow = op.isRestfulShow(); + op.isRestfulIndex = op.isRestfulIndex(); + op.isRestfulCreate = op.isRestfulCreate(); + op.isRestfulUpdate = op.isRestfulUpdate(); + op.isRestfulDestroy = op.isRestfulDestroy(); + op.isRestful = op.isRestful(); + return op; } @@ -2519,6 +2527,7 @@ public class DefaultCodegen { private void addVars(CodegenModel m, Map properties, List required, Map allProperties, List allRequired) { + m.hasRequired = false; if (properties != null && !properties.isEmpty()) { m.hasVars = true; m.hasEnums = false; @@ -2557,6 +2566,7 @@ public class DefaultCodegen { } else { final CodegenProperty cp = fromProperty(key, prop); cp.required = mandatory.contains(key) ? true : null; + m.hasRequired = Boolean.TRUE.equals(m.hasRequired) || Boolean.TRUE.equals(cp.required); if (cp.isEnum) { // FIXME: if supporting inheritance, when called a second time for allProperties it is possible for // m.hasEnums to be set incorrectly if allProperties has enumerations but properties does not. diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 282c4d88647..58b59f71364 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -89,8 +89,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.") .defaultValue(Boolean.TRUE.toString())); - supportedLibraries.put("", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1"); - supportedLibraries.put("volley", "HTTP client: Volley 1.0.19"); + supportedLibraries.put("volley", "HTTP client: Volley 1.0.19 (default)"); + supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release."); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setEnum(supportedLibraries); cliOptions.add(library); @@ -382,23 +382,26 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi additionalProperties.put( "modelDocPath", modelDocPath ); if (StringUtils.isEmpty(getLibrary())) { - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); - //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - addSupportingFilesForDefault(); - } else if ("volley".equals(getLibrary())) { - modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); - apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); - //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); - addSupportingFilesForVolley(); + setLibrary("volley"); // set volley as the default library } + + // determine which file (mustache) to add based on library + if ("volley".equals(getLibrary())) { + addSupportingFilesForVolley(); + } else if ("httpclient".equals(getLibrary())) { + addSupportingFilesForHttpClient(); + } else { + throw new IllegalArgumentException("Invalid 'library' option specified: '" + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)"); + } + } - private void addSupportingFilesForDefault() { + private void addSupportingFilesForHttpClient() { + // documentation files + modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); + apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); @@ -418,6 +421,13 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi } private void addSupportingFilesForVolley() { + // documentation files + modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); + apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + 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("pom.mustache", "", "pom.xml")); // supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 2fc8738f067..d9f9ff3a477 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -218,6 +218,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { binRelativePath += "vendor"; additionalProperties.put("binRelativePath", binRelativePath); + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", + clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index bc839f07d18..30c4941c57d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -107,12 +107,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated")); - supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); - supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1"); - supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); - supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); - supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); - supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.1). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.2)"); + supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0"); + supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2"); + supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); + supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)"); CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); library.setDefault(DEFAULT_LIBRARY); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 46b6083e2e4..d7532d86ee3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -42,6 +42,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected String[] specialWords = {"new", "copy"}; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected String modelFilesPath = "Model/"; + protected String coreFilesPath = "Core/"; + protected String apiFilesPath = "Api/"; protected Set advancedMapingTypes = new HashSet(); @@ -223,35 +226,38 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); - String swaggerFolder = podName; + additionalProperties.put("modelFilesPath", modelFilesPath); + additionalProperties.put("coreFilesPath", coreFilesPath); + additionalProperties.put("apiFilesPath", apiFilesPath); - modelPackage = swaggerFolder; - apiPackage = swaggerFolder; + modelPackage = podName; + apiPackage = podName; - supportingFiles.add(new SupportingFile("Object-header.mustache", swaggerFolder, classPrefix + "Object.h")); - supportingFiles.add(new SupportingFile("Object-body.mustache", swaggerFolder, classPrefix + "Object.m")); - supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", swaggerFolder, classPrefix + "QueryParamCollection.h")); - supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", swaggerFolder, classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", swaggerFolder, classPrefix + "ApiClient.h")); - supportingFiles.add(new SupportingFile("ApiClient-body.mustache", swaggerFolder, classPrefix + "ApiClient.m")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.h")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m")); - supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.m")); - supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.h")); - supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", swaggerFolder, classPrefix + "Sanitizer.m")); - supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", swaggerFolder, classPrefix + "Sanitizer.h")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-body.mustache", swaggerFolder, classPrefix + "Configuration.m")); - supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); + supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); + supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h")); + supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m")); + supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h")); + supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m")); + supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); + supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); 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")); - } @Override @@ -454,12 +460,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + File.separatorChar + apiPackage(); + return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator); } @Override public String modelFileFolder() { - return outputFolder + File.separatorChar + modelPackage(); + return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator); + } + + public String coreFileFolder() { + return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 738ffd4e0d5..7bb9714bc0a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -3,6 +3,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; @@ -13,6 +14,7 @@ import io.swagger.models.properties.*; import java.io.File; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.HashSet; import java.util.regex.Matcher; @@ -35,7 +37,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String composerVendorName = "swagger"; protected String composerProjectName = "swagger-client"; protected String packagePath = "SwaggerClient-php"; - protected String artifactVersion = "1.0.0"; + protected String artifactVersion = null; protected String srcBasePath = "lib"; protected String testBasePath = "test"; protected String docsBasePath = "docs"; @@ -626,4 +628,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // process enum in models return postProcessModelsEnum(objs); } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.vendorExtensions.put("x-testOperationId", camelize(op.operationId)); + } + return objs; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java new file mode 100644 index 00000000000..cbf77338ab3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -0,0 +1,323 @@ +package io.swagger.codegen.languages; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.Swagger; +import io.swagger.util.Yaml; + +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig { + + private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class); + + protected String gemName; + protected String moduleName; + protected String gemVersion = "1.0.0"; + protected String appFolder = "app"; + protected String channelsFolder = appFolder + File.separator + "channels"; + protected String applicationCableFolder = channelsFolder + File.separator + "application_cable"; + protected String controllersFolder = appFolder + File.separator + "controllers"; + protected String jobsFolder = appFolder + File.separator + "jobs"; + protected String mailersFolder = appFolder + File.separator + "mailers"; + protected String modelsFolder = appFolder + File.separator + "models"; + protected String viewsFolder = appFolder + File.separator + "views"; + protected String layoutsFolder = viewsFolder + File.separator + "layouts"; + protected String binFolder = "bin"; + protected String configFolder = "config"; + protected String environmentsFolder = configFolder + File.separator + "config"; + protected String initializersFolder = configFolder + File.separator + "initializers"; + protected String localesFolder = configFolder + File.separator + "locales"; + protected String dbFolder = "db"; + protected String migrateFolder = dbFolder + File.separator + "migrate"; + protected String libFolder = "lib"; + protected String tasksFolder = libFolder + File.separator + "tasks"; + protected String logFolder = "log"; + protected String publicFolder = "public"; + protected String testFolder = "test"; + protected String tmpFolder = "tmp"; + protected String cacheFolder = tmpFolder + File.separator + "cache"; + protected String pidFolder = tmpFolder + File.separator + "pids"; + protected String socketsFolder = tmpFolder + File.separator + "sockets"; + protected String vendorFolder = "vendor"; + + public Rails5ServerCodegen() { + super(); + apiPackage = "app/controllers"; + outputFolder = "generated-code" + File.separator + "rails5"; + + // no model + modelTemplateFiles.clear(); + apiTemplateFiles.put("controller.mustache", ".rb"); + embeddedTemplateDir = templateDir = "rails5"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + setReservedWordsLowerCase( + Arrays.asList( + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", + "if", "not", "return", "undef", "yield") + ); + + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("array"); + languageSpecificPrimitives.add("map"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("DateTime"); + + typeMapping.put("long", "int"); + typeMapping.put("integer", "int"); + typeMapping.put("Array", "array"); + typeMapping.put("String", "string"); + typeMapping.put("List", "array"); + typeMapping.put("map", "map"); + //TODO binary should be mapped to byte array + // mapped to String as a workaround + typeMapping.put("binary", "string"); + + // remove modelPackage and apiPackage added by default + cliOptions.clear(); + } + + @Override + public void processOpts() { + super.processOpts(); + + // use constant model/api package (folder path) + //setModelPackage("models"); + setApiPackage("app/controllers"); + + supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile")); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("Rakefile", "", "Rakefile")); + supportingFiles.add(new SupportingFile("config.ru", "", "config.ru")); + supportingFiles.add(new SupportingFile("channel.rb", applicationCableFolder, "channel.rb")); + supportingFiles.add(new SupportingFile("connection.rb", applicationCableFolder, "connection.rb")); + supportingFiles.add(new SupportingFile("application_controller.rb", controllersFolder, "application_controller.rb")); + supportingFiles.add(new SupportingFile("application_job.rb", jobsFolder, "application_job.rb")); + supportingFiles.add(new SupportingFile("application_mailer.rb", mailersFolder, "application_mailer.rb")); + supportingFiles.add(new SupportingFile("application_record.rb", modelsFolder, "application_record.rb")); + supportingFiles.add(new SupportingFile("mailer.html.erb", layoutsFolder, "mailer.html.erb")); + supportingFiles.add(new SupportingFile("mailer.text.erb", layoutsFolder, "mailer.text.erb")); + supportingFiles.add(new SupportingFile("bundle", binFolder, "bundle")); + supportingFiles.add(new SupportingFile("rails", binFolder, "rails")); + supportingFiles.add(new SupportingFile("rake", binFolder, "rake")); + supportingFiles.add(new SupportingFile("setup", binFolder, "setup")); + supportingFiles.add(new SupportingFile("update", binFolder, "update")); + supportingFiles.add(new SupportingFile("development.rb", environmentsFolder, "development.rb")); + supportingFiles.add(new SupportingFile("production.rb", environmentsFolder, "production.rb")); + supportingFiles.add(new SupportingFile("active_record_belongs_to_required_by_default.rb", initializersFolder, "active_record_belongs_to_required_by_default.rb")); + supportingFiles.add(new SupportingFile("application_controller_renderer.rb", initializersFolder, "application_controller_renderer.rb")); + supportingFiles.add(new SupportingFile("backtrace_silencers.rb", initializersFolder, "backtrace_silencers.rb")); + supportingFiles.add(new SupportingFile("callback_terminator.rb", initializersFolder, "callback_terminator.rb")); + supportingFiles.add(new SupportingFile("cors.rb", initializersFolder, "cors.rb")); + supportingFiles.add(new SupportingFile("filter_parameter_logging.rb", initializersFolder, "filter_parameter_logging.rb")); + supportingFiles.add(new SupportingFile("inflections.rb", initializersFolder, "inflections.rb")); + supportingFiles.add(new SupportingFile("mime_types.rb", initializersFolder, "mime_types.rb")); + supportingFiles.add(new SupportingFile("ssl_options.rb", initializersFolder, "ssl_options.rb")); + supportingFiles.add(new SupportingFile("to_time_preserves_timezone.rb", initializersFolder, "to_time_preserves_timezone.rb")); + supportingFiles.add(new SupportingFile("en.yml", localesFolder, "en.yml")); + supportingFiles.add(new SupportingFile("application.rb", configFolder, "application.rb")); + supportingFiles.add(new SupportingFile("boot.rb", configFolder, "boot.rb")); + supportingFiles.add(new SupportingFile("cable.yml", configFolder, "cable.yml")); + supportingFiles.add(new SupportingFile("database.yml", configFolder, "database.yml")); + supportingFiles.add(new SupportingFile("environment.rb", configFolder, "environment.rb")); + supportingFiles.add(new SupportingFile("puma.rb", configFolder, "puma.rb")); + supportingFiles.add(new SupportingFile("routes.mustache", configFolder, "routes.rb")); + supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml")); + supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb")); + supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep")); + supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb")); + supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb")); + supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", logFolder, ".keep")); + supportingFiles.add(new SupportingFile("404.html", publicFolder, "404.html")); + supportingFiles.add(new SupportingFile("422.html", publicFolder, "422.html")); + supportingFiles.add(new SupportingFile("500.html", publicFolder, "500.html")); + supportingFiles.add(new SupportingFile("apple-touch-icon-precomposed.png", publicFolder, "apple-touch-icon-precomposed.png")); + supportingFiles.add(new SupportingFile("apple-touch-icon.png", publicFolder, "apple-touch-icon.png")); + supportingFiles.add(new SupportingFile("favicon.ico", publicFolder, "favicon.ico")); + supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt")); + supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt")); + supportingFiles.add(new SupportingFile("test_helper.rb", testFolder, "test_helper.rb")); + supportingFiles.add(new SupportingFile(".keep", cacheFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", pidFolder, ".keep")); + supportingFiles.add(new SupportingFile(".keep", socketsFolder, ".keep")); + supportingFiles.add(new SupportingFile("restart.txt", tmpFolder, "restart.txt")); + supportingFiles.add(new SupportingFile(".keep", vendorFolder, ".keep")); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "rails5"; + } + + @Override + public String getHelp() { + return "Generates a Rails5 server library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage.replace("/", File.separator); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @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; + } + if (type == null) { + return null; + } + return type; + } + + @Override + public String toDefaultValue(Property p) { + return "null"; + } + + @Override + public String toVarName(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'. + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // camelize (lower first character) the variable name + // petId => pet_id + name = underscore(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // underscore the model file name + // PhoneNumber.rb => phone_number.rb + 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. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_controllers"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "ApiController"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Controller"; + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return underscore(operationId); + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + LOGGER.error(e.getMessage(), e); + } + } + return super.postProcessSupportingFileData(objs); + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index ba846857cb9..9d6d891df70 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -355,8 +355,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { return value; } - char[] separators = {'-', '_', ' '}; - return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ ]", ""); + char[] separators = {'-', '_', ' ', ':'}; + return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :]", ""); } @@ -502,6 +502,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + // TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value)); // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { String varName = new String(name); @@ -525,8 +526,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumName(CodegenProperty property) { - String enumName = underscore(toModelName(property.name)).toUpperCase(); + String enumName = toModelName(property.name); + // TODO: toModelName already does something for names starting with number, so this code is probably never called if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java index c817162401e..90f778eae8e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -26,7 +26,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege super.processOpts(); supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("assign.ts", "", "assign.ts")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json")); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache index 74ff86ebd1b..1df88d403a2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache @@ -23,14 +23,17 @@ import feign.Request.Options; import feign.RequestInterceptor; import feign.RequestTemplate; import feign.Response; +import feign.RetryableException; import feign.Util; import {{invokerPackage}}.StringUtil; public class OAuth implements RequestInterceptor { + static final int MILLIS_PER_SECOND = 1000; + public interface AccessTokenListener { - public void notify(BasicOAuthToken token); + void notify(BasicOAuthToken token); } private volatile String accessToken; @@ -41,21 +44,13 @@ public class OAuth implements RequestInterceptor { private AccessTokenListener accessTokenListener; public OAuth(Client client, TokenRequestBuilder requestBuilder) { - setOauthClient(client); + this.oauthClient = new OAuthClient(new OAuthFeignClient(client)); this.tokenRequestBuilder = requestBuilder; } public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); - setFlow(flow); - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); - } - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); - } - - public void setFlow(OAuthFlow flow) { switch(flow) { case accessCode: case implicit: @@ -70,6 +65,11 @@ public class OAuth implements RequestInterceptor { default: break; } + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); } @Override @@ -80,34 +80,29 @@ public class OAuth implements RequestInterceptor { } // If first time, get the token if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { - try { - updateAccessToken(); - } catch (OAuthSystemException e) { - e.printStackTrace(); - return; - } catch (OAuthProblemException e) { - e.printStackTrace(); - return; - } + updateAccessToken(); } if (getAccessToken() != null) { template.header("Authorization", "Bearer " + getAccessToken()); } } - public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { - if (getAccessToken() == null) { - OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); - if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { - setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); - } + public synchronized void updateAccessToken() { + OAuthJSONAccessTokenResponse accessTokenResponse; + try { + accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + } catch (Exception e) { + throw new RetryableException(e.getMessage(), e,null); + } + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); } } } - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) { this.accessTokenListener = accessTokenListener; } @@ -117,7 +112,7 @@ public class OAuth implements RequestInterceptor { public synchronized void setAccessToken(String accessToken, Long expiresIn) { this.accessToken = accessToken; - this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND; } public TokenRequestBuilder getTokenRequestBuilder() { @@ -148,7 +143,7 @@ public class OAuth implements RequestInterceptor { this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); } - public class OAuthFeignClient implements HttpClient { + public static class OAuthFeignClient implements HttpClient { private Client client; @@ -198,6 +193,5 @@ public class OAuth implements RequestInterceptor { public void shutdown() { // Nothing to do here } - } } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache index 257a4611db5..95c86d4bc0b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom-j8-async.mustache @@ -163,10 +163,9 @@ 9.2.9.v20150224 1.13 1.6.3 - 1.6.1 4.8.1 2.5 - 2.0.4-SNAPSHOT - 4.0.9.RELEASE + 2.4.0 + 4.2.5.RELEASE \ No newline at end of file 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 c84abac129c..f0d0fde5e57 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 @@ -27,6 +27,7 @@ io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen io.swagger.codegen.languages.SilexServerCodegen io.swagger.codegen.languages.SinatraServerCodegen +io.swagger.codegen.languages.Rails5ServerCodegen io.swagger.codegen.languages.SlimFrameworkServerCodegen io.swagger.codegen.languages.SpringBootServerCodegen io.swagger.codegen.languages.SpringMVCServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md index 8ec43e76497..db2dfccec36 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/README.md @@ -1,44 +1,54 @@ # TypeScript-Fetch -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: -* Node.JS +Environment +* Node.js * Webpack * Browserify -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) ### Installation ### -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: ``` import * as localName from 'npmName'; import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` import * as localName from './symlinkDir'; import {operationId} from './symlinkDir'; ``` -With CommonJS, the following syntaxes are supported: +The CommonJS syntax is as follows: ``` -import localName = require('npmName'); - import localName = require('./symlinkDir')'; -``` \ No newline at end of file +``` diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 67d61999aa0..20c303e40eb 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -1,7 +1,30 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; +import * as querystring from "querystring"; +import * as url from "url"; +import * as isomorphicFetch from "isomorphic-fetch"; +{{^supportsES6}} +import * as assign from "core-js/library/fn/object/assign"; +{{/supportsES6}} + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "{{basePath}}"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} {{#models}} {{#model}} @@ -13,24 +36,20 @@ import {assign} from './assign'; export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{#vars}} {{#description}} - /** * {{{description}}} */ {{/description}} - "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } {{#hasEnums}} -export namespace {{classname}} { {{#vars}} {{#isEnum}} - -export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; +export type {{classname}}{{datatypeWithEnum}} = {{#allowableValues}}{{#values}}"{{.}}"{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; {{/isEnum}} {{/vars}} -} {{/hasEnums}} {{/model}} {{/models}} @@ -38,96 +57,111 @@ export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-las {{#apiInfo}} {{#apis}} {{#operations}} -//export namespace {{package}} { - 'use strict'; - -{{#description}} - /** - * {{&description}} - */ -{{/description}} - export class {{classname}} { - protected basePath = '{{basePath}}'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } +/** + * {{classname}} - fetch parameter creator{{#description}} + * {{&description}}{{/description}} + */ +export const {{classname}}FetchParamCreactor = { {{#operation}} - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{paramName}} {{description}} - {{/allParams}}*/ - public {{nickname}} (params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { - const localVarPath = this.basePath + '{{path}}'{{#pathParams}} - .replace('{' + '{{baseName}}' + '}', String(params.{{paramName}})){{/pathParams}}; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); -{{#hasFormParams}} - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - -{{/hasFormParams}} -{{#hasBodyParam}} - headerParams['Content-Type'] = 'application/json'; - -{{/hasBodyParam}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}): FetchArgs { {{#allParams}} {{#required}} - // verify required parameter '{{paramName}}' is set - if (params.{{paramName}} == null) { - throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); - } + // verify required parameter "{{paramName}}" is set + if (params["{{paramName}}"] == null) { + throw new Error("Missing required parameter {{paramName}} when calling {{nickname}}"); + } {{/required}} {{/allParams}} -{{#queryParams}} - if (params.{{paramName}} !== undefined) { - queryParameters['{{baseName}}'] = params.{{paramName}}; - } + const baseUrl = `{{path}}`{{#pathParams}} + .replace(`{${"{{baseName}}"}}`, `${ params.{{paramName}} }`){{/pathParams}}; + let urlObj = url.parse(baseUrl, true); +{{#hasQueryParams}} + urlObj.query = {{#supportsES6}}Object.{{/supportsES6}}assign({}, urlObj.query, { {{#queryParams}} + "{{baseName}}": params.{{paramName}},{{/queryParams}} + }); +{{/hasQueryParams}} + let fetchOptions: RequestInit = { method: "{{httpMethod}}" }; -{{/queryParams}} -{{#headerParams}} - headerParams['{{baseName}}'] = params.{{paramName}}; + let contentTypeHeader: Dictionary; +{{#hasFormParams}} + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ {{#formParams}} + "{{baseName}}": params.{{paramName}},{{/formParams}} + }); +{{/hasFormParams}} +{{#hasBodyParam}} + contentTypeHeader = { "Content-Type": "application/json" };{{#bodyParam}} + if (params["{{paramName}}"]) { + fetchOptions.body = JSON.stringify(params["{{paramName}}"] || {}); + }{{/bodyParam}} +{{/hasBodyParam}} +{{#hasHeaderParam}} + fetchOptions.headers = {{#supportsES6}}Object.{{/supportsES6}}assign({ {{#headerParams}} + "{{baseName}}": params.{{paramName}},{{/headerParams}} + }, contentTypeHeader); +{{/hasHeaderParam}} +{{^hasHeaderParam}} + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } +{{/hasHeaderParam}} + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +{{/operation}} +} -{{/headerParams}} -{{#formParams}} - formParams['{{baseName}}'] = params.{{paramName}}; - -{{/formParams}} - let fetchParams = { - method: '{{httpMethod}}', - headers: headerParams, - {{#bodyParam}}body: JSON.stringify(params.{{paramName}}), - {{/bodyParam}} - {{#hasFormParams}}body: querystring.stringify(formParams), - {{/hasFormParams}} - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { +/** + * {{classname}} - functional programming interface{{#description}} + * {{&description}}{{/description}} + */ +export const {{classname}}Fp = { +{{#operation}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}; {{/allParams}} }{{/hasParams}}): (fetch: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { + const fetchArgs = {{classname}}FetchParamCreactor.{{nickname}}({{#hasParams}}params{{/hasParams}}); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { - return response.json(); + return response{{#returnType}}.json(){{/returnType}}; } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; + throw response; } }); - } + }; + }, {{/operation}} +}; + +/** + * {{classname}} - object-oriented interface{{#description}} + * {{&description}}{{/description}} + */ +export class {{classname}} extends BaseAPI { +{{#operation}} + /** {{#summary}} + * {{summary}}{{/summary}}{{#notes}} + * {{notes}}{{/notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + */ + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}) { + return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(this.fetch, this.basePath); } -//} +{{/operation}} +} + {{/operations}} {{/apis}} {{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache index e6379434b80..62a598d536b 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache @@ -1,15 +1,15 @@ { "name": "{{#npmName}}{{{npmName}}}{{/npmName}}{{^npmName}}typescript-fetch-api{{/npmName}}", "version": "{{#npmVersion}}{{{npmVersion}}}{{/npmVersion}}{{^npmVersion}}0.0.0{{/npmVersion}}", - "private": true, "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { - "isomorphic-fetch": "^2.2.1" + {{^supportsES6}}"core-js": "^2.4.0", + {{/supportsES6}}"isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache index 06a057d7a49..25f414e9840 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache @@ -4,7 +4,8 @@ "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache index 38baf589fb9..3aca69ff648 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache @@ -1,9 +1,9 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { -{{^supportsES6}} "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", -{{/supportsES6}} "node": "registry:dt/node#4.0.0+20160423143914", + "ambientDependencies": { {{^supportsES6}} + "core-js": "registry:dt/core-js#0.0.0+20160317120654",{{/supportsES6}} + "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache new file mode 100644 index 00000000000..079d91582ef --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/git_push.sh.mustache @@ -0,0 +1,51 @@ +#!/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' \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache new file mode 100644 index 00000000000..a7b72d554da --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/gitignore.mustache @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +# Keystore files +*.jks \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache index 4036bb32afb..80ba5feacab 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache @@ -37,11 +37,24 @@ ${android-platform-version} + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.6 + 1.6 + + + + - 1.5.0 + 1.5.8 4.4.4 4.5.2 - 2.3.1 + 2.6.2 1.0.19 4.1.1.4 diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 2c0f8f681e3..f9b9f766299 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -20,6 +20,11 @@ namespace {{packageName}}.Client /// public class ApiClient { + private JsonSerializerSettings serializerSettings = new JsonSerializerSettings + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }; + /// /// Initializes a new instance of the class /// with default configuration and base path ({{basePath}}). @@ -305,7 +310,7 @@ namespace {{packageName}}.Client // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content, type); + return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); } catch (Exception e) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache new file mode 100644 index 00000000000..eecd5284493 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using RestSharp; + +namespace {{packageName}}.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + Configuration Configuration {get; set;} + + /// + /// Gets the base path of the API client. + /// + /// The base path + String GetBasePath(); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 2b3f224cfc5..a96f4ced1ef 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -13,7 +13,7 @@ namespace {{packageName}}.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public interface I{{classname}} + public interface I{{classname}} : IApiAccessor { #region Synchronous Operations {{#operation}} @@ -72,7 +72,7 @@ namespace {{packageName}}.Api /// /// Represents a collection of functions to interact with the API endpoints /// - public class {{classname}} : I{{classname}} + public partial class {{classname}} : I{{classname}} { /// /// Initializes a new instance of the class. @@ -122,7 +122,7 @@ namespace {{packageName}}.Api /// Sets the base path of the API client. /// /// The base path - [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] + [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 4d4061a29fd..7535af0a3d8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -24,6 +24,13 @@ public {{{datatypeWithEnum}}}{{#isEnum}}?{{/isEnum}} {{name}} { get; set; } {{/isEnum}} {{/vars}} + {{#hasRequired}} + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected {{classname}}() { } + {{/hasRequired}} /// /// Initializes a new instance of the class. /// diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 5afc917e228..37bdfd8f4a7 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -2,7 +2,7 @@ NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; -static long requestId = 0; +static NSUInteger requestId = 0; static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; @@ -36,7 +36,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) @interface {{classPrefix}}ApiClient () -@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; +@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; @end @@ -88,49 +88,6 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; } -#pragma mark - Log Methods - -+ (void)debugLog:(NSString *)method - message:(NSString *)format, ... { - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - if (!config.debug) { - return; - } - - NSMutableString *message = [NSMutableString stringWithCapacity:1]; - - if (method) { - [message appendString:[NSString stringWithFormat:@"%@: ", method]]; - } - - va_list args; - va_start(args, format); - - [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; - - // If set logging file handler, log into file, - // otherwise log into console. - if (config.loggingFileHanlder) { - [config.loggingFileHanlder seekToEndOfFile]; - [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; - } - else { - NSLog(@"%@", message); - } - - va_end(args); -} - -- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { - - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - responseObject]; - - {{classPrefix}}DebugLog(message); -} - #pragma mark - Cache Methods +(void)clearCache { @@ -151,70 +108,6 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [NSURLCache setSharedURLCache:cache]; } -#pragma mark - Utility Methods - -/* - * Detect `Accept` from accepts - */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { - return @""; - } - - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - // use rangeOfString instead of containsString for iOS 7 support - if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { - return @"application/json"; - } - [lowerAccepts addObject:lowerAccept]; - } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - - return [lowerAccepts componentsJoinedByString:@", "]; -} - -/* - * Detect `Content-Type` from contentTypes - */ -+ (NSString *) selectHeaderContentType:(NSArray *)contentTypes -{ - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; - } - - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; - } -} - -+ (NSString*)escape:(id)unescaped { - if ([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - #pragma mark - Request Methods +(unsigned long)requestQueueSize { @@ -223,14 +116,12 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) +(NSNumber*) nextRequestId { @synchronized(self) { - long nextId = ++requestId; - {{classPrefix}}DebugLog(@"got id %ld", nextId); - return [NSNumber numberWithLong:nextId]; + return @(++requestId); } } +(NSNumber*) queueRequest { - NSNumber* requestId = [{{classPrefix}}ApiClient nextRequestId]; + NSNumber* requestId = [[self class] nextRequestId]; {{classPrefix}}DebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; @@ -294,7 +185,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) if (![strongSelf executeRequestWithId:requestId]) { return; } - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); @@ -321,7 +212,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return; } strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + {{classPrefix}}DebugLogResponse(response, responseObject,request,error); if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -370,14 +261,13 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { - NSAssert(false, @"unsupport request type %@", requestContentType); + NSAssert(NO, @"Unsupported request type %@", requestContentType); } // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } - else { + } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } @@ -393,8 +283,9 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSMutableString *resourcePath = [NSMutableString stringWithString:path]; [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] - withString:[{{classPrefix}}ApiClient escape:obj]]; + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = {{classPrefix}}PercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; NSMutableURLRequest * request = nil; @@ -438,10 +329,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } // request cache - BOOL hasHeaderParams = false; - if (headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } + BOOL hasHeaderParams = [headerParams count] > 0; if (offlineState) { {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; @@ -462,9 +350,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + [self postProcessRequest:request]; NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { @@ -485,59 +371,66 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return requestId; } +//Added for easier override to modify request +-(void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + #pragma mark - - (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } NSString * separator = nil; - int counter = 0; + NSUInteger counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if (queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) separator = @"?"; - else separator = @"&"; - id queryParam = [queryParams valueForKey:key]; - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [{{classPrefix}}ApiClient escape:[queryParams valueForKey:key]]]]; - } - else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ - {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - if ([format isEqualToString:@"csv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; - - } - else if ([format isEqualToString:@"tsv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; - - } - else if ([format isEqualToString:@"pipes"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; - - } - else if ([format isEqualToString:@"multi"]) { - for(id obj in values) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; - counter += 1; - } - - } - } - else { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; - } - - counter += 1; + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = {{classPrefix}}PercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, {{classPrefix}}PercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = {{classPrefix}}PercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; } return requestUrl; } @@ -558,15 +451,17 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; for (NSString *auth in authSettings) { - NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - - if (authSetting) { // auth setting is set only if the key is non-empty - if ([authSetting[@"in"] isEqualToString:@"header"] && [authSetting[@"key"] length] != 0) { - [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - else if ([authSetting[@"in"] isEqualToString:@"query"] && [authSetting[@"key"] length] != 0) { - [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } + NSDictionary *authSetting = [config authSettings][auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; } } diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index b08112ba445..28d5b92f628 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -7,6 +7,7 @@ #import "{{classPrefix}}Configuration.h" #import "{{classPrefix}}ResponseDeserializer.h" #import "{{classPrefix}}Sanitizer.h" +#import "{{classPrefix}}Logger.h" /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -26,13 +27,6 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; -/** - * Log debug message macro - */ -#ifndef {{classPrefix}}DebugLog - #define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -#endif - @interface {{classPrefix}}ApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @@ -113,15 +107,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(void) cancelRequest:(NSNumber*)requestId; -/** - * Gets URL encoded NSString - * - * @param unescaped The string which will be escaped. - * - * @return The escaped string. - */ -+(NSString*) escape:(id)unescaped; - /** * Customizes the behavior when the reachability changed * @@ -134,24 +119,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (void)configureCacheReachibility; -/** - * Detects Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ -+(NSString *) selectHeaderAccept:(NSArray *)accepts; - -/** - * Detects Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header - * - * @return The Content-Type header - */ -+(NSString *) selectHeaderContentType:(NSArray *)contentTypes; - /** * Sets header for request * @@ -172,19 +139,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; -/** - * Logs request and response - * - * @param response NSURLResponse for the HTTP request. - * @param responseObject response object of the HTTP request. - * @param request The HTTP request. - * @param error The error of the HTTP request. - */ -- (void)logResponse:(NSURLResponse *)response - responseObject:(id)responseObject - request:(NSURLRequest *)request - error:(NSError *)error; - /** * Performs request * @@ -222,9 +176,5 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (AFSecurityPolicy *) customSecurityPolicy; -/** - * Log debug message - */ -+(void)debugLog:(NSString *)method message:(NSString *)format, ...; @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 527e16c2b91..99708408d4e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -30,12 +30,10 @@ self.username = @""; self.password = @""; self.accessToken= @""; - self.tempFolderPath = nil; - self.debug = NO; self.verifySSL = YES; - self.loggingFile = nil; self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + self.logger = [{{classPrefix}}Logger sharedLogger]; } return self; } @@ -43,11 +41,13 @@ #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; } - else if ([self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; } else { // return empty string if nothing is set return @""; @@ -70,8 +70,7 @@ - (NSString *) getAccessToken { if (self.accessToken.length == 0) { // token not set, return empty string return @""; - } - else { + } else { return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; } } @@ -94,20 +93,6 @@ [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } -- (void) setLoggingFile:(NSString *)loggingFile { - // close old file handler - if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { - [self.loggingFileHanlder closeFile]; - } - - _loggingFile = loggingFile; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (_loggingFileHanlder == nil) { - [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - } -} - #pragma mark - Getter Methods - (NSDictionary *) apiKey { @@ -154,4 +139,12 @@ }; } +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index b77ddfe5dee..c00c7175d2a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -1,5 +1,6 @@ #import #import "{{classPrefix}}ApiClient.h" +#import "{{classPrefix}}Logger.h" /** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. * @@ -12,6 +13,11 @@ @interface {{classPrefix}}Configuration : NSObject +/** + * Default api logger + */ +@property (nonatomic, strong) {{classPrefix}}Logger * logger; + /** * Default api client */ @@ -37,7 +43,7 @@ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename for HTTP Basic Authentication + * Username for HTTP Basic Authentication */ @property (nonatomic) NSString *username; @@ -56,25 +62,11 @@ */ @property (nonatomic) NSString *tempFolderPath; -/** - * Logging Settings - */ - /** * Debug switch, default false */ @property (nonatomic) BOOL debug; -/** - * Debug file location, default log in console - */ -@property (nonatomic) NSString *loggingFile; - -/** - * Log file handler, this property is used by sdk internally. - */ -@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; - /** * Gets configuration singleton instance */ @@ -143,7 +135,7 @@ - (NSString *) getAccessToken; /** - * Gets Authentication Setings + * Gets Authentication Settings */ - (NSDictionary *) authSettings; diff --git a/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache new file mode 100644 index 00000000000..9a8f7de2418 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache @@ -0,0 +1,74 @@ +#import "{{classPrefix}}Logger.h" + +@interface {{classPrefix}}Logger () + +@end + +@implementation {{classPrefix}}Logger + ++ (instancetype) sharedLogger { + static {{classPrefix}}Logger *shardLogger = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardLogger = [[self alloc] init]; + }); + return shardLogger; +} + +#pragma mark - Log Methods + +- (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + if (!self.isEnabled) { + return; + } + + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendFormat:@"%@: ", method]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. + if (self.loggingFileHandler) { + [self.loggingFileHandler seekToEndOfFile]; + [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } else { + NSLog(@"%@", message); + } + + va_end(args); +} + +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + responseObject]; + + {{classPrefix}}DebugLog(message); +} + +- (void) setLoggingFile:(NSString *)loggingFile { + if(_loggingFile == loggingFile) { + return; + } + // close old file handler + if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHandler closeFile]; + } + _loggingFile = loggingFile; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHandler == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache new file mode 100644 index 00000000000..2070f95ae9f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Logger-header.mustache @@ -0,0 +1,54 @@ +#import + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#ifndef {{classPrefix}}DebugLogResponse +#define {{classPrefix}}DebugLogResponse(response, responseObject,request, error) [[{{classPrefix}}Logger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; +#endif + +/** + * Log debug message macro + */ +#ifndef {{classPrefix}}DebugLog +#define {{classPrefix}}DebugLog(format, ...) [[{{classPrefix}}Logger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif + +@interface {{classPrefix}}Logger : NSObject + ++(instancetype)sharedLogger; + +/** + * Enabled switch, default NO - default set by {{classPrefix}}Configuration debug property + */ +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +/** + * Debug file location, default log in console + */ +@property (nonatomic, strong) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; + +/** + * Log debug message + */ +-(void)debugLog:(NSString *)method message:(NSString *)format, ...; + +/** + * Logs request and response + * + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache index 74b166d75e9..a111aad9cef 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache @@ -3,11 +3,57 @@ #import "{{classPrefix}}QueryParamCollection.h" #import -@interface {{classPrefix}}Sanitizer () +NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { + static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@"; + static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[k{{classPrefix}}CharactersGeneralDelimitersToEncode stringByAppendingString:k{{classPrefix}}CharactersSubDelimitersToEncode]]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +@interface SWGSanitizer () + +@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; @end -@implementation {{classPrefix}}Sanitizer +@implementation SWGSanitizer + +static NSString * kApplicationJSONType = @"application/json"; + +-(instancetype)init { + self = [super init]; + if ( !self ) { + return nil; + } + _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; + return self; +} + - (id) sanitizeForSerialization:(id) object { if (object == nil) { @@ -17,7 +63,7 @@ return object; } else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; + return [self dateParameterToString:object]; } else if ([object isKindOfClass:[NSArray class]]) { NSArray *objectArray = object; @@ -61,7 +107,7 @@ return [param stringValue]; } else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; + return [self dateParameterToString:param]; } else if ([param isKindOfClass:[NSArray class]]) { NSMutableArray *mutableParam = [NSMutableArray array]; @@ -79,4 +125,44 @@ } } +- (NSString *)dateParameterToString:(id)param { + return [param ISO8601String]; +} + +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ +- (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts.count == 0) { + return @""; + } + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { + return kApplicationJSONType; + } + [lowerAccepts addObject:[string lowercaseString]]; + } + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ +- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { + if (contentTypes.count == 0) { + return kApplicationJSONType; + } + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + for (NSString *string in contentTypes) { + if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ + return kApplicationJSONType; + } + [lowerContentTypes addObject:[string lowercaseString]]; + } + return [lowerContentTypes firstObject]; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache index 706a94c1d0e..cd946661615 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache @@ -6,6 +6,8 @@ * Do not edit the class manually. */ +extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string); + @protocol {{classPrefix}}Sanitizer /** @@ -20,6 +22,24 @@ */ - (NSString *) parameterToString: (id) param; +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ +-(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ +-(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + @end @interface {{classPrefix}}Sanitizer : NSObject <{{classPrefix}}Sanitizer> diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 2a7880d8367..807acc8ed76 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -15,7 +15,7 @@ static {{classname}}* singletonAPI = nil; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; @@ -28,7 +28,7 @@ static {{classname}}* singletonAPI = nil; return self; } -- (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { +- (instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { self = [super init]; if (self) { self.apiClient = apiClient; @@ -92,9 +92,7 @@ static {{classname}}* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; {{#pathParams}} @@ -121,22 +119,16 @@ static {{classname}}* singletonAPI = nil; {{/headerParams}} // HTTP header `Accept` - headerParams[@"Accept"] = [{{classPrefix}}ApiClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [{{classPrefix}}ApiClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; // Authentication setting NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 7c5a9d335cf..e7491a14ece 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -22,13 +22,12 @@ +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +({{classname}}*) sharedAPI; {{#operation}} -/// -/// /// {{{summary}}} /// {{#notes}}{{{notes}}}{{/notes}} /// /// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -/// {{/allParams}} +/// {{/allParams}}{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// /// @return {{{returnType}}} -(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} diff --git a/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/objc/git_push.sh.mustache old mode 100755 new mode 100644 diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index 338ded84e89..c308a399c0a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -13,7 +13,7 @@ Pod::Spec.new do |s| {{#apiInfo}}{{#apis}}{{^hasMore}} s.summary = "{{appName}}" s.description = <<-DESC - {{appDescription}} + {{{appDescription}}} DESC {{/hasMore}}{{/apis}}{{/apiInfo}} s.platform = :ios, '7.0' @@ -29,8 +29,8 @@ Pod::Spec.new do |s| s.source_files = '{{podName}}/**/*' s.public_header_files = '{{podName}}/**/*.h' - s.dependency 'AFNetworking', '~> 2.3' - s.dependency 'JSONModel', '~> 1.1' - s.dependency 'ISO8601', '~> 0.3' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' end diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 5b8b9b21632..bfd811b89f0 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -55,18 +55,21 @@ class ApiClient /** * Configuration + * * @var Configuration */ protected $config; /** * Object Serializer + * * @var ObjectSerializer */ protected $serializer; /** * Constructor of the class + * * @param Configuration $config config for this ApiClient */ public function __construct(\{{invokerPackage}}\Configuration $config = null) @@ -81,6 +84,7 @@ class ApiClient /** * Get the config + * * @return Configuration */ public function getConfig() @@ -90,6 +94,7 @@ class ApiClient /** * Get the serializer + * * @return ObjectSerializer */ public function getSerializer() @@ -99,7 +104,9 @@ class ApiClient /** * Get API key (with prefix if set) + * * @param string $apiKeyIdentifier name of apikey + * * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKeyIdentifier) @@ -122,12 +129,14 @@ class ApiClient /** * Make the HTTP call (Sync) + * * @param string $resourcePath path to method endpoint * @param string $method method to call * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header * @param string $responseType expected response type of the endpoint + * * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ @@ -160,7 +169,7 @@ class ApiClient if ($this->config->getCurlTimeout() != 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } - // return the result on success, rather than just true + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -171,7 +180,7 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } - if (! empty($queryParams)) { + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } @@ -216,7 +225,7 @@ class ApiClient // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = $this->http_parse_headers(substr($response, 0, $http_header_size)); + $http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size)); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); @@ -228,7 +237,7 @@ class ApiClient // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { return array($http_body, $response_info['http_code'], $http_header); @@ -246,7 +255,9 @@ class ApiClient throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $data + $response_info['http_code'], + $http_header, + $data ); } return array($data, $response_info['http_code'], $http_header); @@ -295,40 +306,35 @@ class ApiClient * * @return string[] Array of HTTP response heaers */ - protected function http_parse_headers($raw_headers) + protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); $key = ''; - - foreach(explode("\n", $raw_headers) as $h) - { + + foreach (explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); - - if (isset($h[1])) - { - if (!isset($headers[$h[0]])) + + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); - elseif (is_array($headers[$h[0]])) - { + } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); - } - else - { + } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } - + $key = $h[0]; - } - else - { - if (substr($h[0], 0, 1) == "\t") - $headers[$key] .= "\r\n\t".trim($h[0]); - elseif (!$key) - $headers[0] = trim($h[0]);trim($h[0]); + } else { + if (substr($h[0], 0, 1) == "\t") { + $headers[$key] .= "\r\n\t".trim($h[0]); + } elseif (!$key) { + $headers[0] = trim($h[0]); + } + trim($h[0]); } } - + return $headers; } } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index eee688001ed..031e8cd995e 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -48,30 +48,34 @@ class ApiException extends Exception /** * The HTTP body of the server response either as Json or string. + * * @var mixed */ protected $responseBody; /** * The HTTP header of the server response. + * * @var string[] */ protected $responseHeaders; /** * The deserialized response object + * * @var $responseObject; */ protected $responseObject; /** * Constructor + * * @param string $message Error message * @param int $code HTTP status code * @param string $responseHeaders HTTP response header * @param mixed $responseBody HTTP body of the server response either as Json or string */ - public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) + public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null) { parent::__construct($message, $code); $this->responseHeaders = $responseHeaders; @@ -100,7 +104,9 @@ class ApiException extends Exception /** * Sets the deseralized response object (during deserialization) + * * @param mixed $obj Deserialized response object + * * @return void */ public function setResponseObject($obj) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 34d79b0ae39..7de8d9d085e 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -1,6 +1,6 @@ getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - return $deserialized; + if (Configuration::getDefaultConfiguration()->getDebug()) { + error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + } + + return $deserialized; } else { // If a discriminator is defined and points to a valid subclass, use it. if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { @@ -282,11 +286,11 @@ class ObjectSerializer $instance = new $class(); foreach ($instance::swaggerTypes() as $property => $type) { $propertySetter = $instance::setters()[$property]; - + if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { continue; } - + $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index 3049d013ca5..1bc31869371 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -46,7 +46,7 @@ Download the files and include `autoload.php`: require_once('/path/to/{{packagePath}}/autoload.php'); ``` -## Tests +## Tests To run the unit tests: @@ -108,7 +108,7 @@ Class | Method | HTTP request | Description {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} {{#authMethods}}## {{{name}}} -{{#isApiKey}}- **Type**: API key +{{#isApiKey}}- **Type**: API key - **API key parameter name**: {{{keyParamName}}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index cc74dfd3a2a..7a9b2afa993 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +52,41 @@ use \{{invokerPackage}}\ObjectSerializer; /** * API Client + * * @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use */ - function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) + public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('{{basePath}}'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \{{invokerPackage}}\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \{{invokerPackage}}\ApiClient $apiClient set the API client + * * @return {{classname}} */ public function setApiClient(\{{invokerPackage}}\ApiClient $apiClient) @@ -89,31 +94,33 @@ use \{{invokerPackage}}\ObjectSerializer; $this->apiClient = $apiClient; return $this; } - + {{#operation}} /** - * {{{operationId}}} + * Operation {{{operationId}}} * - * {{{summary}}} + * {{{summary}}}. * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} - {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{/allParams}} * + * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} * @throws \{{invokerPackage}}\ApiException on non-2xx response */ public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - list($response) = $this->{{operationId}}WithHttpInfo ({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - return $response; + list($response) = $this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + return $response; } /** - * {{{operationId}}}WithHttpInfo + * Operation {{{operationId}}}WithHttpInfo * - * {{{summary}}} + * {{{summary}}}. * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} - {{/allParams}} * @return Array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) + {{/allParams}} * + * @return Array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) * @throws \{{invokerPackage}}\ApiException on non-2xx response */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) @@ -153,7 +160,7 @@ use \{{invokerPackage}}\ObjectSerializer; {{/hasValidation}} {{/allParams}} - + // parse inputs $resourcePath = "{{path}}"; $httpBody = ''; @@ -165,7 +172,7 @@ use \{{invokerPackage}}\ObjectSerializer; $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); - + {{#queryParams}}// query params {{#collectionFormat}} if (is_array(${{paramName}})) { @@ -208,7 +215,7 @@ use \{{invokerPackage}}\ObjectSerializer; if (function_exists('curl_file_create')) { $formParams['{{baseName}}'] = curl_file_create($this->apiClient->getSerializer()->toFormValue(${{paramName}})); } else { - $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); } {{/isFile}} {{^isFile}} @@ -220,7 +227,7 @@ use \{{invokerPackage}}\ObjectSerializer; if (isset(${{paramName}})) { $_tempBody = ${{paramName}}; }{{/bodyParams}} - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -244,9 +251,12 @@ use \{{invokerPackage}}\ObjectSerializer; // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, '{{httpMethod}}', - $queryParams, $httpBody, - $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} + $resourcePath, + '{{httpMethod}}', + $queryParams, + $httpBody, + $headerParams{{#returnType}}, + '{{returnType}}'{{/returnType}} ); {{#returnType}} if (!$response) { @@ -254,17 +264,22 @@ use \{{invokerPackage}}\ObjectSerializer; } return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader); - {{/returnType}}{{^returnType}} + {{/returnType}} + {{^returnType}} return array(null, $statusCode, $httpHeader); {{/returnType}} } catch (ApiException $e) { - switch ($e->getCode()) { {{#responses}}{{#dataType}} - {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); - $e->setResponseObject($data); - break;{{/dataType}}{{/responses}} + switch ($e->getCode()) { + {{#responses}} + {{#dataType}} + {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + {{/dataType}} + {{/responses}} } - + throw $e; } } diff --git a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache index 4cf01aa510b..fa6033b084a 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache @@ -17,7 +17,7 @@ Method | HTTP request | Description {{{notes}}}{{/notes}} -### Example +### Example ```php {{{operationId}}}({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} print_r($result);{{/returnType}} } catch (Exception $e) { diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index fc07d338301..6a525223584 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,14 +53,16 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } @@ -68,10 +70,11 @@ use \{{invokerPackage}}\ObjectSerializer; /** * Test case for {{{operationId}}} * - * {{{summary}}} + * {{{summary}}}. * */ - public function test_{{operationId}}() { + public function test{{vendorExtensions.x-testOperationId}}() + { } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache index 04be6e11992..0942715ce8d 100644 --- a/modules/swagger-codegen/src/main/resources/php/autoload.mustache +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -1,14 +1,15 @@ '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes{{#parentSchema}} + parent::swaggerTypes(){{/parentSchema}}; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function attributeMap() { + public static function attributeMap() + { return {{#parentSchema}}parent::attributeMap() + {{/parentSchema}}self::$attributeMap; } @@ -85,12 +89,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - static function setters() { + public static function setters() + { return {{#parentSchema}}parent::setters() + {{/parentSchema}}self::$setters; } @@ -98,12 +103,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function getters() { + + public static function getters() + { return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters; } @@ -115,7 +121,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} @@ -152,48 +159,48 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); {{#vars}} {{#required}} if ($this->container['{{name}}'] === null) { - $invalid_properties[] = "'${{name}}' can't be null"; + $invalid_properties[] = "'{{name}}' can't be null"; } {{/required}} {{#isEnum}} $allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); if (!in_array($this->container['{{name}}'], $allowed_values)) { - $invalid_properties[] = "invalid value for '${{name}}', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for '{{name}}', must be one of #{allowed_values}."; } {{/isEnum}} {{#hasValidation}} {{#maxLength}} if (strlen($this->container['{{name}}']) > {{maxLength}}) { - $invalid_properties[] = "invalid value for '${{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; + $invalid_properties[] = "invalid value for '{{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; } {{/maxLength}} {{#minLength}} if (strlen($this->container['{{name}}']) < {{minLength}}) { - $invalid_properties[] = "invalid value for '${{name}}', the character length must be bigger than or equal to {{{minLength}}}."; + $invalid_properties[] = "invalid value for '{{name}}', the character length must be bigger than or equal to {{{minLength}}}."; } {{/minLength}} {{#maximum}} if ($this->container['{{name}}'] > {{maximum}}) { - $invalid_properties[] = "invalid value for '${{name}}', must be smaller than or equal to {{maximum}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be smaller than or equal to {{maximum}}."; } {{/maximum}} {{#minimum}} if ($this->container['{{name}}'] < {{minimum}}) { - $invalid_properties[] = "invalid value for '${{name}}', must be bigger than or equal to {{minimum}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be bigger than or equal to {{minimum}}."; } {{/minimum}} {{#pattern}} if (!preg_match("{{pattern}}", $this->container['{{name}}'])) { - $invalid_properties[] = "invalid value for '${{name}}', must be conform to the pattern {{pattern}}."; + $invalid_properties[] = "invalid value for '{{name}}', must be conform to the pattern {{pattern}}."; } {{/pattern}} {{/hasValidation}} @@ -204,8 +211,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -265,7 +272,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * Sets {{name}} - * @param {{datatype}} ${{name}} {{#description}}{{{description}}}{{/description}} + * @param {{datatype}} ${{name}}{{#description}} {{{description}}}{{/description}} * @return $this */ public function {{setter}}(${{name}}) @@ -309,7 +316,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{/vars}} /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -319,17 +326,17 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -341,17 +348,17 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/modules/swagger-codegen/src/main/resources/php/model_enum.mustache b/modules/swagger-codegen/src/main/resources/php/model_enum.mustache index 4598f9fdff9..ffb268c6cb9 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_enum.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_enum.mustache @@ -7,7 +7,8 @@ class {{classname}} { * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 006cd09c62a..22f97456e04 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -1,19 +1,20 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayAccess { /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ static $swaggerTypes = array( {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function swaggerTypes() { + + static function swaggerTypes() + { return self::$swaggerTypes{{#parent}} + parent::swaggerTypes(){{/parent}}; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ @@ -21,8 +22,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function attributeMap() { + + static function attributeMap() + { return {{#parent}}parent::attributeMap() + {{/parent}}self::$attributeMap; } @@ -34,8 +36,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function setters() { + + static function setters() + { return {{#parent}}parent::setters() + {{/parent}}self::$setters; } @@ -47,8 +50,9 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - - static function getters() { + + static function getters() + { return {{#parent}}parent::getters() + {{/parent}}self::$getters; } @@ -60,7 +64,8 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA * Gets allowable values of the enum * @return string[] */ - public function {{getter}}AllowableValues() { + public function {{getter}}AllowableValues() + { return [ {{#allowableValues}}{{#enumVars}}self::{{datatypeWithEnum}}_{{{name}}},{{^-last}} {{/-last}}{{/enumVars}}{{/allowableValues}} @@ -115,7 +120,7 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA {{/vars}} /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -125,17 +130,17 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return $this->$offset; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -143,17 +148,17 @@ class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}implements ArrayA { $this->$offset = $value; } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->$offset); } - + /** * Gets the string presentation of the object. * @return string diff --git a/modules/swagger-codegen/src/main/resources/php/model_test.mustache b/modules/swagger-codegen/src/main/resources/php/model_test.mustache index 0d615eca102..3482629f917 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_test.mustache @@ -39,7 +39,7 @@ namespace {{modelPackage}}; * {{classname}}Test Class Doc Comment * * @category Class - * @description {{description}} + * @description {{#description}}{{description}}{{/description}}{{^description}}{{classname}}{{/description}} * @package {{invokerPackage}} * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,24 +51,26 @@ class {{classname}}Test extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test {{classname}} + * Test "{{classname}}" */ - public function test{{classname}}() { + public function test{{classname}}() + { } - } {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/rails5/.keep b/modules/swagger-codegen/src/main/resources/rails5/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/404.html b/modules/swagger-codegen/src/main/resources/rails5/404.html new file mode 100644 index 00000000000..b612547fc21 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/422.html b/modules/swagger-codegen/src/main/resources/rails5/422.html new file mode 100644 index 00000000000..a21f82b3bdb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/500.html b/modules/swagger-codegen/src/main/resources/rails5/500.html new file mode 100644 index 00000000000..061abc587dc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/modules/swagger-codegen/src/main/resources/rails5/Gemfile b/modules/swagger-codegen/src/main/resources/rails5/Gemfile new file mode 100644 index 00000000000..b553bf7355d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/Gemfile @@ -0,0 +1,36 @@ +source 'https://rubygems.org' + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '>= 5.0.0.racecar1', '< 5.1' +# Use mysql as the database for Active Record +gem 'mysql2', '>= 0.3.18', '< 0.5' +# Use Puma as the app server +gem 'puma', '~> 3.0' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.0' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 3.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platform: :mri +end + +group :development do + gem 'listen', '~> 3.0.5' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/modules/swagger-codegen/src/main/resources/rails5/README.md b/modules/swagger-codegen/src/main/resources/rails5/README.md new file mode 100644 index 00000000000..c5cb90075a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/README.md @@ -0,0 +1,25 @@ +# Swagger for Rails 5 + +This is a project to provide Swagger support inside the [Sinatra](http://rubyonrails.org/) framework. + +## Prerequisites +You need to install ruby >= 2.2.2 and run: + +``` +bundle install +``` + +## Getting started + +This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. + +``` +bin/rake db:create +bin/rails s +``` + +To list all your routes, use: + +``` +bin/rake routes +``` diff --git a/modules/swagger-codegen/src/main/resources/rails5/Rakefile b/modules/swagger-codegen/src/main/resources/rails5/Rakefile new file mode 100644 index 00000000000..e85f913914b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb b/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb new file mode 100644 index 00000000000..f613b40f804 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/active_record_belongs_to_required_by_default.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Require `belongs_to` associations by default. This is a new Rails 5.0 +# default, so it is introduced as a configuration option to ensure that apps +# made on earlier versions of Rails are not affected when upgrading. +Rails.application.config.active_record.belongs_to_required_by_default = true diff --git a/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon-precomposed.png b/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon-precomposed.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon.png b/modules/swagger-codegen/src/main/resources/rails5/apple-touch-icon.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/application.rb b/modules/swagger-codegen/src/main/resources/rails5/application.rb new file mode 100644 index 00000000000..70bea9ecf69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application.rb @@ -0,0 +1,30 @@ +require_relative 'boot' + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "action_cable/engine" +# require "sprockets/railtie" +require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ApiDemo + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb b/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb new file mode 100644 index 00000000000..4ac8823b095 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb b/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb new file mode 100644 index 00000000000..51639b67a00 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_controller_renderer.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_job.rb b/modules/swagger-codegen/src/main/resources/rails5/application_job.rb new file mode 100644 index 00000000000..a009ace51cc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb b/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb new file mode 100644 index 00000000000..286b2239d13 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/application_record.rb b/modules/swagger-codegen/src/main/resources/rails5/application_record.rb new file mode 100644 index 00000000000..10a4cba84df --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb b/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb new file mode 100644 index 00000000000..59385cdf379 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/modules/swagger-codegen/src/main/resources/rails5/boot.rb b/modules/swagger-codegen/src/main/resources/rails5/boot.rb new file mode 100644 index 00000000000..30f5120df69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/modules/swagger-codegen/src/main/resources/rails5/bundle b/modules/swagger-codegen/src/main/resources/rails5/bundle new file mode 100755 index 00000000000..66e9889e8b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/modules/swagger-codegen/src/main/resources/rails5/cable.yml b/modules/swagger-codegen/src/main/resources/rails5/cable.yml new file mode 100644 index 00000000000..aa4e832748c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/cable.yml @@ -0,0 +1,10 @@ +# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket. +production: + adapter: redis + url: redis://localhost:6379/1 + +development: + adapter: async + +test: + adapter: async diff --git a/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb b/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb new file mode 100644 index 00000000000..649e82280e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/callback_terminator.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Do not halt callback chains when a callback returns false. This is a new +# Rails 5.0 default, so it is introduced as a configuration option to ensure +# that apps made with earlier versions of Rails are not affected when upgrading. +ActiveSupport.halt_callback_chains_on_return_false = false diff --git a/modules/swagger-codegen/src/main/resources/rails5/channel.rb b/modules/swagger-codegen/src/main/resources/rails5/channel.rb new file mode 100644 index 00000000000..d56fa30f4d8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/channel.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/config.ru b/modules/swagger-codegen/src/main/resources/rails5/config.ru new file mode 100644 index 00000000000..f7ba0b527b1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/modules/swagger-codegen/src/main/resources/rails5/connection.rb b/modules/swagger-codegen/src/main/resources/rails5/connection.rb new file mode 100644 index 00000000000..b4f41389ad0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/connection.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/controller.mustache b/modules/swagger-codegen/src/main/resources/rails5/controller.mustache new file mode 100644 index 00000000000..321960875d8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/controller.mustache @@ -0,0 +1,49 @@ +class {{classname}} < ApplicationController +{{#operations}} +{{#operation}} + +{{#isRestfulIndex}} + def index + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulIndex}} +{{#isRestfulShow}} + def show + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulShow}} +{{#isRestfulCreate}} + def create + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulCreate}} +{{#isRestfulUpdate}} + def update + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulUpdate}} +{{#isRestfulDestroy}} + def destroy + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestfulDestroy}} +{{^isRestful}} + def {{nickname}} + # Your code here + + render json: {"message" => "yes, it worked"} + end +{{/isRestful}} +{{/operation}} +{{/operations}} +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/cors.rb b/modules/swagger-codegen/src/main/resources/rails5/cors.rb new file mode 100644 index 00000000000..3b1c1b5ed14 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/modules/swagger-codegen/src/main/resources/rails5/database.yml b/modules/swagger-codegen/src/main/resources/rails5/database.yml new file mode 100644 index 00000000000..e536d9f37dc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/database.yml @@ -0,0 +1,54 @@ +# MySQL. Versions 5.0 and up are supported. +# +# Install the MySQL driver +# gem install mysql2 +# +# Ensure the MySQL gem is defined in your Gemfile +# gem 'mysql2' +# +# And be sure to use new-style password hashing: +# http://dev.mysql.com/doc/refman/5.7/en/old-client.html +# +default: &default + adapter: mysql2 + encoding: utf8 + pool: 5 + username: root + password: + socket: /tmp/mysql.sock + +development: + <<: *default + database: api_demo_development + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: api_demo_test + +# As with config/secrets.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password as a unix environment variable when you boot +# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full rundown on how to provide these environment variables in a +# production deployment. +# +# On Heroku and other platform providers, you may have a full connection URL +# available as an environment variable. For example: +# +# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase" +# +# You can use this database configuration with: +# +# production: +# url: <%= ENV['DATABASE_URL'] %> +# +production: + <<: *default + database: api_demo_production + username: api_demo + password: <%= ENV['API_DEMO_DATABASE_PASSWORD'] %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/development.rb b/modules/swagger-codegen/src/main/resources/rails5/development.rb new file mode 100644 index 00000000000..082a013ab36 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/development.rb @@ -0,0 +1,47 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=172800' + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/en.yml b/modules/swagger-codegen/src/main/resources/rails5/en.yml new file mode 100644 index 00000000000..0653957166e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/modules/swagger-codegen/src/main/resources/rails5/environment.rb b/modules/swagger-codegen/src/main/resources/rails5/environment.rb new file mode 100644 index 00000000000..426333bb469 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/modules/swagger-codegen/src/main/resources/rails5/favicon.ico b/modules/swagger-codegen/src/main/resources/rails5/favicon.ico new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb b/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb new file mode 100644 index 00000000000..4a994e1e7bb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/modules/swagger-codegen/src/main/resources/rails5/inflections.rb b/modules/swagger-codegen/src/main/resources/rails5/inflections.rb new file mode 100644 index 00000000000..ac033bf9dc8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb b/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb new file mode 100644 index 00000000000..cbd34d2e9dd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb b/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb new file mode 100644 index 00000000000..37f0bddbd74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb b/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb new file mode 100644 index 00000000000..dc1899682b0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/modules/swagger-codegen/src/main/resources/rails5/production.rb b/modules/swagger-codegen/src/main/resources/rails5/production.rb new file mode 100644 index 00000000000..6cb0a8fe61c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/production.rb @@ -0,0 +1,80 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Action Cable endpoint configuration + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Don't mount Action Cable in the main server process. + # config.action_cable.mount_path = nil + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "api_demo_#{Rails.env}" + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/puma.rb b/modules/swagger-codegen/src/main/resources/rails5/puma.rb new file mode 100644 index 00000000000..c7f311f8116 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/puma.rb @@ -0,0 +1,47 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum, this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests, default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. If you use this option +# you need to make sure to reconnect any threads in the `on_worker_boot` +# block. +# +# preload_app! + +# The code in the `on_worker_boot` will be called if you are using +# clustered mode by specifying a number of `workers`. After each worker +# process is booted this block will be run, if you are using `preload_app!` +# option you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, Ruby +# cannot share connections between processes. +# +# on_worker_boot do +# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) +# end + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/modules/swagger-codegen/src/main/resources/rails5/rails b/modules/swagger-codegen/src/main/resources/rails5/rails new file mode 100755 index 00000000000..07396602377 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/modules/swagger-codegen/src/main/resources/rails5/rake b/modules/swagger-codegen/src/main/resources/rails5/rake new file mode 100755 index 00000000000..17240489f64 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/modules/swagger-codegen/src/main/resources/rails5/restart.txt b/modules/swagger-codegen/src/main/resources/rails5/restart.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/rails5/robots.txt b/modules/swagger-codegen/src/main/resources/rails5/robots.txt new file mode 100644 index 00000000000..3c9c7c01f30 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/modules/swagger-codegen/src/main/resources/rails5/routes.mustache b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache new file mode 100644 index 00000000000..6ebc0d4965d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/routes.mustache @@ -0,0 +1,17 @@ +Rails.application.routes.draw do + + def add_swagger_route http_method, path, opts = {} + full_path = path.gsub(/{(.*?)}/, ':\1') + match full_path, to: "#{opts.fetch(:controller_name)}##{opts[:action_name]}", via: http_method + end + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + add_swagger_route '{{httpMethod}}', '{{basePathWithoutHost}}{{path}}', controller_name: '{{classVarName}}', action_name: {{#isRestfulIndex}}'index'{{/isRestfulIndex}}{{#isRestfulCreate}}'create'{{/isRestfulCreate}}{{#isRestfulUpdate}}'update'{{/isRestfulUpdate}}{{#isRestfulShow}}'show'{{/isRestfulShow}}{{#isRestfulDestroy}}'destroy'{{/isRestfulDestroy}}{{^isRestful}}'{{nickname}}'{{/isRestful}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/schema.rb b/modules/swagger-codegen/src/main/resources/rails5/schema.rb new file mode 100644 index 00000000000..4dfbb16804e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/schema.rb @@ -0,0 +1,16 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 0) do + +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/secrets.yml b/modules/swagger-codegen/src/main/resources/rails5/secrets.yml new file mode 100644 index 00000000000..179b066b84d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: 2e13a003477a557ba3fcc6260c2ec69e411238b9b8b530c3c70e71f7cfc905b5f746f5c195a0282342a77ad6acd4e6ef8949106723200a99414fe83393d67344 + +test: + secret_key_base: fedf54236a94882c00e2fa0af308a4135f50941396437b9fbc38dd340c0a8bcf38cfcf6264cc2abc2af5bda26252293fe48e9a3e90fbfc4d25d6886d6d14b300 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/modules/swagger-codegen/src/main/resources/rails5/seeds.rb b/modules/swagger-codegen/src/main/resources/rails5/seeds.rb new file mode 100644 index 00000000000..1beea2accd7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/modules/swagger-codegen/src/main/resources/rails5/setup b/modules/swagger-codegen/src/main/resources/rails5/setup new file mode 100755 index 00000000000..e620b4dadb2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/spring.rb b/modules/swagger-codegen/src/main/resources/rails5/spring.rb new file mode 100644 index 00000000000..c9119b40c08 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/spring.rb @@ -0,0 +1,6 @@ +%w( + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +).each { |path| Spring.watch(path) } diff --git a/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb b/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb new file mode 100644 index 00000000000..1775dea1e76 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/ssl_options.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure SSL options to enable HSTS with subdomains. +Rails.application.config.ssl_options = { hsts: { subdomains: true } } diff --git a/modules/swagger-codegen/src/main/resources/rails5/test.rb b/modules/swagger-codegen/src/main/resources/rails5/test.rb new file mode 100644 index 00000000000..30587ef6d5e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/test.rb @@ -0,0 +1,42 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=3600' + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb b/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb new file mode 100644 index 00000000000..92e39b2d78c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/test_helper.rb @@ -0,0 +1,10 @@ +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +require 'rails/test_help' + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb b/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb new file mode 100644 index 00000000000..8674be3227e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/to_time_preserves_timezone.rb @@ -0,0 +1,10 @@ +# Be sure to restart your server when you modify this file. + +# Preserve the timezone of the receiver when calling to `to_time`. +# Ruby 2.4 will change the behavior of `to_time` to preserve the timezone +# when converting to an instance of `Time` instead of the previous behavior +# of converting to the local system timezone. +# +# Rails 5.0 introduced this config option so that apps made with earlier +# versions of Rails are not affected when upgrading. +ActiveSupport.to_time_preserves_timezone = true diff --git a/modules/swagger-codegen/src/main/resources/rails5/update b/modules/swagger-codegen/src/main/resources/rails5/update new file mode 100755 index 00000000000..a8e4462f203 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/update @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb b/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb new file mode 100644 index 00000000000..bbfc3961bff --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/rails5/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache index 418f1c8512b..7041709f365 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache @@ -18,4 +18,22 @@ class APIHelper { } return destination } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject] { + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + if (source != nil) { + for (key, value) in source! { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + } + return destination + } + } diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 378c83525f1..49798250e72 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -46,9 +46,9 @@ class Decoders { } static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { - let sourceDictinoary = source as! [Key: AnyObject] + let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() - for (key, value) in sourceDictinoary { + for (key, value) in sourceDictionary { dictionary[key] = Decoders.decode(clazz: T.self, source: value) } return dictionary diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 9801182e082..8e3216052a0 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -80,11 +80,14 @@ public class {{classname}}: APIBase { ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} "{{baseName}}": {{paramName}}{{#isInteger}}{{^required}}?{{/required}}.encodeToJSON(){{/isInteger}}{{#isLong}}{{^required}}?{{/required}}.encodeToJSON(){{/isLong}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} + let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: convertedParameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache index 427479cf675..5a735cc58e1 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache @@ -15,10 +15,10 @@ namespace {{package}} { protected basePath = '{{basePath}}'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index fd37bdd1194..efc6e00c633 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -18,7 +19,7 @@ export class {{classname}} { protected basePath = '{{basePath}}'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache index 0b2e50acb44..547200a6695 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/package.mustache @@ -16,17 +16,30 @@ "build": "typings install && tsc" }, "peerDependencies": { - "angular2": "^2.0.0-beta.15", - "rxjs": "^5.0.0-beta.2" + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12" }, "devDependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12", "typescript": "^1.8.10", "typings": "^0.8.1", - "angular2": "^2.0.0-beta.15", "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0", - "rxjs": "5.0.0-beta.2", - "zone.js": "^0.6.10" + "es7-reflect-metadata": "^1.6.0" }{{#npmRepository}}, "publishConfig":{ "registry":"{{npmRepository}}" diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java index 82bb13029e5..82ffa437f2a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java @@ -18,7 +18,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true"; - public static final String LIBRARY_VALUE = "volley"; + public static final String LIBRARY_VALUE = "httpclient"; @Override public String getLanguage() { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java new file mode 100644 index 00000000000..c75053b84e2 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Rails5ServerOptionsProvider.java @@ -0,0 +1,23 @@ +package io.swagger.codegen.options; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class Rails5ServerOptionsProvider implements OptionsProvider { + @Override + public String getLanguage() { + return "Rails5"; + } + + @Override + public Map createOptions() { + //Rails5ServerCodegen doesn't have its own options and base options are cleared + return ImmutableMap.of(); + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/pom.xml b/pom.xml index 1b5c3d7580f..4b11b1230e2 100644 --- a/pom.xml +++ b/pom.xml @@ -267,7 +267,7 @@ - samples/client/petstore/android/default + samples/client/petstore/android/volley @@ -471,7 +471,7 @@ - samples/client/petstore/android/default + samples/client/petstore/android/volley samples/client/petstore/clojure samples/client/petstore/java/default samples/client/petstore/java/feign diff --git a/samples/client/petstore/android/default/.gitignore b/samples/client/petstore/android/httpclient/.gitignore similarity index 100% rename from samples/client/petstore/android/default/.gitignore rename to samples/client/petstore/android/httpclient/.gitignore diff --git a/samples/client/petstore/android/default/README.md b/samples/client/petstore/android/httpclient/README.md similarity index 100% rename from samples/client/petstore/android/default/README.md rename to samples/client/petstore/android/httpclient/README.md index a1c37674b81..65931066a32 100644 --- a/samples/client/petstore/android/default/README.md +++ b/samples/client/petstore/android/httpclient/README.md @@ -116,6 +116,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -125,12 +131,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/android/default/build.gradle b/samples/client/petstore/android/httpclient/build.gradle similarity index 100% rename from samples/client/petstore/android/default/build.gradle rename to samples/client/petstore/android/httpclient/build.gradle diff --git a/samples/client/petstore/android/default/docs/Category.md b/samples/client/petstore/android/httpclient/docs/Category.md similarity index 100% rename from samples/client/petstore/android/default/docs/Category.md rename to samples/client/petstore/android/httpclient/docs/Category.md diff --git a/samples/client/petstore/android/default/docs/Order.md b/samples/client/petstore/android/httpclient/docs/Order.md similarity index 100% rename from samples/client/petstore/android/default/docs/Order.md rename to samples/client/petstore/android/httpclient/docs/Order.md diff --git a/samples/client/petstore/android/default/docs/Pet.md b/samples/client/petstore/android/httpclient/docs/Pet.md similarity index 100% rename from samples/client/petstore/android/default/docs/Pet.md rename to samples/client/petstore/android/httpclient/docs/Pet.md diff --git a/samples/client/petstore/android/default/docs/PetApi.md b/samples/client/petstore/android/httpclient/docs/PetApi.md similarity index 99% rename from samples/client/petstore/android/default/docs/PetApi.md rename to samples/client/petstore/android/httpclient/docs/PetApi.md index f8ba698c05a..f0f8ad40fbe 100644 --- a/samples/client/petstore/android/default/docs/PetApi.md +++ b/samples/client/petstore/android/httpclient/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/android/default/docs/StoreApi.md b/samples/client/petstore/android/httpclient/docs/StoreApi.md similarity index 100% rename from samples/client/petstore/android/default/docs/StoreApi.md rename to samples/client/petstore/android/httpclient/docs/StoreApi.md diff --git a/samples/client/petstore/android/default/docs/Tag.md b/samples/client/petstore/android/httpclient/docs/Tag.md similarity index 100% rename from samples/client/petstore/android/default/docs/Tag.md rename to samples/client/petstore/android/httpclient/docs/Tag.md diff --git a/samples/client/petstore/android/default/docs/User.md b/samples/client/petstore/android/httpclient/docs/User.md similarity index 100% rename from samples/client/petstore/android/default/docs/User.md rename to samples/client/petstore/android/httpclient/docs/User.md diff --git a/samples/client/petstore/android/default/docs/UserApi.md b/samples/client/petstore/android/httpclient/docs/UserApi.md similarity index 100% rename from samples/client/petstore/android/default/docs/UserApi.md rename to samples/client/petstore/android/httpclient/docs/UserApi.md diff --git a/samples/client/petstore/android/default/git_push.sh b/samples/client/petstore/android/httpclient/git_push.sh similarity index 100% rename from samples/client/petstore/android/default/git_push.sh rename to samples/client/petstore/android/httpclient/git_push.sh diff --git a/samples/client/petstore/android/default/pom.xml b/samples/client/petstore/android/httpclient/pom.xml similarity index 100% rename from samples/client/petstore/android/default/pom.xml rename to samples/client/petstore/android/httpclient/pom.xml diff --git a/samples/client/petstore/android/default/settings.gradle b/samples/client/petstore/android/httpclient/settings.gradle similarity index 100% rename from samples/client/petstore/android/default/settings.gradle rename to samples/client/petstore/android/httpclient/settings.gradle diff --git a/samples/client/petstore/android/default/src/main/AndroidManifest.xml b/samples/client/petstore/android/httpclient/src/main/AndroidManifest.xml similarity index 100% rename from samples/client/petstore/android/default/src/main/AndroidManifest.xml rename to samples/client/petstore/android/httpclient/src/main/AndroidManifest.xml diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiException.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiException.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/ApiInvoker.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/ApiInvoker.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/HttpPatch.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/HttpPatch.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/HttpPatch.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/JsonUtil.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/JsonUtil.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/JsonUtil.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/Pair.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/Pair.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/PetApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/PetApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/StoreApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/StoreApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/api/UserApi.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/api/UserApi.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Category.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Category.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Order.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Order.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Pet.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Pet.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/Tag.java diff --git a/samples/client/petstore/android/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java similarity index 100% rename from samples/client/petstore/android/default/src/main/java/io/swagger/client/model/User.java rename to samples/client/petstore/android/httpclient/src/main/java/io/swagger/client/model/User.java diff --git a/samples/client/petstore/android/volley/.gitignore b/samples/client/petstore/android/volley/.gitignore new file mode 100644 index 00000000000..a7b72d554da --- /dev/null +++ b/samples/client/petstore/android/volley/.gitignore @@ -0,0 +1,39 @@ +# Built application files +*.apk +*.ap_ + +# Files for the Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij +*.iml + +# Keystore files +*.jks \ No newline at end of file diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md index 6f0a2c65f92..65931066a32 100644 --- a/samples/client/petstore/android/volley/README.md +++ b/samples/client/petstore/android/volley/README.md @@ -1,4 +1,4 @@ -# swagger-petstore-android-volley +# swagger-android-client ## Requirements @@ -27,7 +27,7 @@ Add this dependency to your project's POM: ```xml io.swagger - swagger-petstore-android-volley + swagger-android-client 1.0.0 compile @@ -38,7 +38,7 @@ Add this dependency to your project's POM: Add this dependency to your project's build file: ```groovy -compile "io.swagger:swagger-petstore-android-volley:1.0.0" +compile "io.swagger:swagger-android-client:1.0.0" ``` ### Others @@ -49,7 +49,7 @@ At first generate the JAR by executing: Then manually install the following JARs: -* target/swagger-petstore-android-volley-1.0.0.jar +* target/swagger-android-client-1.0.0.jar * target/lib/*.jar ## Getting Started @@ -116,6 +116,12 @@ Class | Method | HTTP request | Description ## Documentation for Authorization Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ### petstore_auth - **Type**: OAuth @@ -125,12 +131,6 @@ Authentication schemes defined for the API: - write:pets: modify pets in your account - read:pets: read your pets -### api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## Recommendation diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md index f8ba698c05a..f0f8ad40fbe 100644 --- a/samples/client/petstore/android/volley/docs/PetApi.md +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh b/samples/client/petstore/android/volley/git_push.sh similarity index 96% rename from samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh rename to samples/client/petstore/android/volley/git_push.sh index ed374619b13..f711c4b3130 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/git_push.sh +++ b/samples/client/petstore/android/volley/git_push.sh @@ -48,5 +48,4 @@ 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' - +git push origin master 2>&1 | grep -v 'To https' \ No newline at end of file diff --git a/samples/client/petstore/android/volley/pom.xml b/samples/client/petstore/android/volley/pom.xml index 98572662fb2..04369688c3b 100644 --- a/samples/client/petstore/android/volley/pom.xml +++ b/samples/client/petstore/android/volley/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 io.swagger - swagger-petstore-android-volley + swagger-android-client 1.0.0 @@ -37,11 +37,24 @@ ${android-platform-version} + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.6 + 1.6 + + + + - 1.5.0 + 1.5.8 4.4.4 4.5.2 - 2.3.1 + 2.6.2 1.0.19 4.1.1.4 diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 3c26ad6be49..1088cf28dc3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{74456AF8-75EE-4ABC-97EB-CA96A472DD21}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Debug|Any CPU.Build.0 = Debug|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Release|Any CPU.ActiveCfg = Release|Any CPU -{C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A}.Release|Any CPU.Build.0 = Release|Any CPU +{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Debug|Any CPU.Build.0 = Debug|Any CPU +{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Release|Any CPU.ActiveCfg = Release|Any CPU +{74456AF8-75EE-4ABC-97EB-CA96A472DD21}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index c546b834c18..fbeb46025d0 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -1,12 +1,12 @@ # IO.Swagger - the C# library for the Swagger Petstore -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-05-10T17:39:13.582+08:00 +- Build date: 2016-05-13T21:50:05.372+08:00 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 743b0b97853..fb3fb1ab975 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -65,7 +65,7 @@ - {C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A} + {74456AF8-75EE-4ABC-97EB-CA96A472DD21} IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs index 42299503d2a..fa4f899389a 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ApiClient.cs @@ -18,6 +18,11 @@ namespace IO.Swagger.Client ///
public class ApiClient { + private JsonSerializerSettings serializerSettings = new JsonSerializerSettings + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }; + /// /// Initializes a new instance of the class /// with default configuration and base path (http://petstore.swagger.io/v2). @@ -289,7 +294,7 @@ namespace IO.Swagger.Client // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content, type); + return JsonConvert.DeserializeObject(response.Content, type, serializerSettings); } catch (Exception e) { diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index ad86456ecea..16f73d99230 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {C075FB79-0DDE-43E3-9FA5-E239EE9B9B5A} + {74456AF8-75EE-4ABC-97EB-CA96A472DD21} Library Properties Swagger Library diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs index 87a17aa4fae..ba5bf4d2ab4 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Animal : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Animal() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs index fee880c5d82..10ea622f999 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Cat : Animal, IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Cat() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs index fb65e3e0c99..bbd61a8535b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Dog : Animal, IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Dog() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs index 33301f02a95..51c2d920e30 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class FormatTest : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected FormatTest() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs index 25273ffb97b..6ca08ca5f7e 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs @@ -17,6 +17,11 @@ namespace IO.Swagger.Model [DataContract] public partial class Name : IEquatable { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Name() { } /// /// Initializes a new instance of the class. /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs index 420ab138b07..50cdb903f94 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs @@ -53,6 +53,11 @@ namespace IO.Swagger.Model /// /// Initializes a new instance of the class. /// + [JsonConstructorAttribute] + protected Pet() { } + /// + /// Initializes a new instance of the class. + /// /// Id. /// Category. /// Name (required). diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index b87503528b6..a232c3d0177 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -5,7 +5,7 @@ - + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index 4d348dcd9cb..70505097dfa 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -14,7 +14,7 @@ import feign.codec.EncodeException; import feign.codec.Encoder; import feign.RequestTemplate; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class FormAwareEncoder implements Encoder { public static final String UTF_8 = "utf-8"; private static final String LINE_FEED = "\r\n"; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index 3d1b4a72710..47bb5836fa5 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index b1dc92805ab..1231d3f3e0a 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -11,13 +11,13 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public interface FakeApi extends ApiClient.Api { /** - * Fake endpoint for testing various parameters - * Fake endpoint for testing various parameters + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @param number None (required) * @param _double None (required) * @param string None (required) diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index e44f445d291..3b50531c607 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -3,8 +3,8 @@ package io.swagger.client.api; import io.swagger.client.ApiClient; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; @@ -12,7 +12,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public interface PetApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index 04993aa879a..7bf3a3b44c5 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -10,7 +10,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public interface StoreApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index 13171d4bed4..51e47cb6e33 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -10,7 +10,7 @@ import java.util.List; import java.util.Map; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public interface UserApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java index 5aafbf81a2f..2653474747d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java @@ -23,14 +23,17 @@ import feign.Request.Options; import feign.RequestInterceptor; import feign.RequestTemplate; import feign.Response; +import feign.RetryableException; import feign.Util; import io.swagger.client.StringUtil; public class OAuth implements RequestInterceptor { + static final int MILLIS_PER_SECOND = 1000; + public interface AccessTokenListener { - public void notify(BasicOAuthToken token); + void notify(BasicOAuthToken token); } private volatile String accessToken; @@ -41,21 +44,13 @@ public class OAuth implements RequestInterceptor { private AccessTokenListener accessTokenListener; public OAuth(Client client, TokenRequestBuilder requestBuilder) { - setOauthClient(client); + this.oauthClient = new OAuthClient(new OAuthFeignClient(client)); this.tokenRequestBuilder = requestBuilder; } public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); - setFlow(flow); - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); - } - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); - } - - public void setFlow(OAuthFlow flow) { switch(flow) { case accessCode: case implicit: @@ -70,6 +65,11 @@ public class OAuth implements RequestInterceptor { default: break; } + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); } @Override @@ -80,34 +80,29 @@ public class OAuth implements RequestInterceptor { } // If first time, get the token if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { - try { - updateAccessToken(); - } catch (OAuthSystemException e) { - e.printStackTrace(); - return; - } catch (OAuthProblemException e) { - e.printStackTrace(); - return; - } + updateAccessToken(); } if (getAccessToken() != null) { template.header("Authorization", "Bearer " + getAccessToken()); } } - public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { - if (getAccessToken() == null) { - OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); - if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { - setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); - } + public synchronized void updateAccessToken() { + OAuthJSONAccessTokenResponse accessTokenResponse; + try { + accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + } catch (Exception e) { + throw new RetryableException(e.getMessage(), e,null); + } + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); } } } - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) { this.accessTokenListener = accessTokenListener; } @@ -117,7 +112,7 @@ public class OAuth implements RequestInterceptor { public synchronized void setAccessToken(String accessToken, Long expiresIn) { this.accessToken = accessToken; - this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND; } public TokenRequestBuilder getTokenRequestBuilder() { @@ -148,7 +143,7 @@ public class OAuth implements RequestInterceptor { this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); } - public class OAuthFeignClient implements HttpClient { + public static class OAuthFeignClient implements HttpClient { private Client client; @@ -198,6 +193,5 @@ public class OAuth implements RequestInterceptor { public void shutdown() { // Nothing to do here } - } } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index d6249c18d7e..2722d7bf0d3 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,10 +10,11 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Animal { private String className = null; + private String color = "red"; /** @@ -32,6 +34,23 @@ public class Animal { } + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -41,12 +60,13 @@ public class Animal { return false; } Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override public int hashCode() { - return Objects.hash(className); + return Objects.hash(className, color); } @Override @@ -55,6 +75,7 @@ public class Animal { sb.append("class Animal {\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index f38bf504d50..29d71fb8604 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import io.swagger.client.model.Animal; import java.util.ArrayList; @@ -9,7 +10,7 @@ import java.util.List; /** * AnimalFarm */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class AnimalFarm extends ArrayList { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index 278889e60d4..b84e83dc9fb 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,10 +11,11 @@ import io.swagger.client.model.Animal; /** * Cat */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Cat extends Animal { private String className = null; + private String color = "red"; private Boolean declawed = null; @@ -34,6 +36,23 @@ public class Cat extends Animal { } + /** + **/ + public Cat color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Cat declawed(Boolean declawed) { @@ -61,13 +80,14 @@ public class Cat extends Animal { } Cat cat = (Cat) o; return Objects.equals(this.className, cat.className) && + Objects.equals(this.color, cat.color) && Objects.equals(this.declawed, cat.declawed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, declawed, super.hashCode()); + return Objects.hash(className, color, declawed, super.hashCode()); } @Override @@ -76,6 +96,7 @@ public class Cat extends Animal { sb.append("class Cat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index f1df969c29c..d0579ee435f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Category */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 1a6374d54bf..5a7162dce4d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,10 +11,11 @@ import io.swagger.client.model.Animal; /** * Dog */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Dog extends Animal { private String className = null; + private String color = "red"; private String breed = null; @@ -34,6 +36,23 @@ public class Dog extends Animal { } + /** + **/ + public Dog color(String color) { + this.color = color; + return this; + } + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("color") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + /** **/ public Dog breed(String breed) { @@ -61,13 +80,14 @@ public class Dog extends Animal { } Dog dog = (Dog) o; return Objects.equals(this.className, dog.className) && + Objects.equals(this.color, dog.color) && Objects.equals(this.breed, dog.breed) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(className, breed, super.hashCode()); + return Objects.hash(className, color, breed, super.hashCode()); } @Override @@ -76,6 +96,7 @@ public class Dog extends Animal { sb.append("class Dog {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java index 716bfbbc85e..42434e297ff 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 9148bd3d5d5..6ef0a34b1f9 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; /** * EnumTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class EnumTest { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index 072decf8079..cea8883add4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -11,7 +12,7 @@ import java.util.Date; /** * FormatTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-06T18:35:05.435+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class FormatTest { private Integer integer = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index 4573c22c3da..a2bee4c634e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Model200Response { private Integer name = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index eca2b1fb388..3d4cf0bfc96 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * ModelApiResponse */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class ModelApiResponse { private Integer code = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index 476bf479288..d3fdac81f3d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,7 +11,7 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class ModelReturn { private Integer _return = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index 19ababb8f1c..7a0af504643 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -10,12 +11,13 @@ import io.swagger.annotations.ApiModelProperty; * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Name { private Integer name = null; private Integer snakeCase = null; private String property = null; + private Integer _123Number = null; /** @@ -59,6 +61,13 @@ public class Name { } + @ApiModelProperty(example = "null", value = "") + @JsonProperty("123Number") + public Integer get123Number() { + return _123Number; + } + + @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -70,12 +79,13 @@ public class Name { Name name = (Name) o; return Objects.equals(this.name, name.name) && Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property); + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); } @Override public int hashCode() { - return Objects.hash(name, snakeCase, property); + return Objects.hash(name, snakeCase, property, _123Number); } @Override @@ -86,6 +96,7 @@ public class Name { sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 359d0105b80..2ca9531a8af 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -11,7 +12,7 @@ import java.util.Date; /** * Order */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Order { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index 511100f868d..bd9248120e8 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @@ -14,7 +15,7 @@ import java.util.List; /** * Pet */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index 37c5823ed2c..58df0f961f0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * SpecialModelName */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class SpecialModelName { private Long specialPropertyName = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index ff51db61fef..24d51b8e59e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * Tag */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 6a4414b5f82..450f177103d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; @@ -9,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; /** * User */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-04-27T23:17:22.230+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-05-13T16:29:08.210Z") public class User { private Long id = null; diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index f4b3f2f2f76..d5b72d7cfe9 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-05-08T12:06:01.121+02:00 +- Build date: 2016-05-13T17:46:25.156+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 740680eb9e2..885b29f7806 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -13,7 +13,7 @@ Pod::Spec.new do |s| s.summary = "Swagger Petstore" s.description = <<-DESC - This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters DESC s.platform = :ios, '7.0' @@ -29,8 +29,8 @@ Pod::Spec.new do |s| s.source_files = 'SwaggerClient/**/*' s.public_header_files = 'SwaggerClient/**/*.h' - s.dependency 'AFNetworking', '~> 2.3' - s.dependency 'JSONModel', '~> 1.1' - s.dependency 'ISO8601', '~> 0.3' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h similarity index 84% rename from samples/client/petstore/objc/SwaggerClient/SWGPetApi.h rename to samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h index 908771588e0..6fea33df4d6 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.h @@ -19,27 +19,25 @@ -(unsigned long) requestQueueSize; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGPetApi*) sharedAPI; -/// -/// /// Add a new pet to the store /// /// /// @param body Pet object that needs to be added to the store (optional) /// +/// code:405 message:"Invalid input" /// /// @return -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) /// +/// code:400 message:"Invalid pet value" /// /// @return -(NSNumber*) deletePetWithPetId: (NSNumber*) petId @@ -47,60 +45,60 @@ completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Finds Pets by status /// Multiple status values can be provided with comma seperated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid status value" /// /// @return NSArray* -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; -/// -/// /// Finds Pets by tags /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid tag value" /// /// @return NSArray* -(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; -/// -/// /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// @param petId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found" /// /// @return SWGPet* -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; -/// -/// /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found", +/// code:405 message:"Validation exception" /// /// @return -(NSNumber*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Updates a pet in the store with form data /// /// @@ -108,6 +106,7 @@ /// @param name Updated name of the pet (optional) /// @param status Updated status of the pet (optional) /// +/// code:405 message:"Invalid input" /// /// @return -(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId @@ -116,8 +115,6 @@ completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// uploads an image /// /// @@ -125,6 +122,7 @@ /// @param additionalMetadata Additional data to pass to server (optional) /// @param file file to upload (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) uploadFileWithPetId: (NSNumber*) petId diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.m similarity index 75% rename from samples/client/petstore/objc/SwaggerClient/SWGPetApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.m index b3ebc31bf68..37b0f9407f7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGPetApi.m @@ -13,7 +13,7 @@ static SWGPetApi* singletonAPI = nil; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; @@ -26,7 +26,7 @@ static SWGPetApi* singletonAPI = nil; return self; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { +- (instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { self.apiClient = apiClient; @@ -79,31 +79,23 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -151,9 +143,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -168,22 +158,16 @@ static SWGPetApi* singletonAPI = nil; } // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -222,9 +206,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -235,22 +217,16 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -289,9 +265,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -302,22 +276,16 @@ static SWGPetApi* singletonAPI = nil; } NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -361,9 +329,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -373,22 +339,16 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth", @"api_key"]; @@ -427,31 +387,23 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -502,9 +454,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -514,22 +464,16 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; @@ -585,9 +529,7 @@ static SWGPetApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}/uploadImage"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { @@ -597,22 +539,16 @@ static SWGPetApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"multipart/form-data"]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"multipart/form-data"]]; // Authentication setting NSArray *authSettings = @[@"petstore_auth"]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h similarity index 84% rename from samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h rename to samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h index d86eb23a046..4a29c72e644 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.h @@ -19,51 +19,51 @@ -(unsigned long) requestQueueSize; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGStoreApi*) sharedAPI; -/// -/// /// Delete purchase order by ID /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// /// @param orderId ID of the order that needs to be deleted /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" /// /// @return -(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Returns pet inventories by status /// Returns a map of status codes to quantities /// /// +/// code:200 message:"successful operation" /// /// @return NSDictionary* -(NSNumber*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; -/// -/// /// Find purchase order by ID /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// @param orderId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" /// /// @return SWGOrder* -(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; -/// -/// /// Place an order for a pet /// /// /// @param body order placed for purchasing the pet (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid Order" /// /// @return SWGOrder* -(NSNumber*) placeOrderWithBody: (SWGOrder*) body diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.m similarity index 77% rename from samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.m index 336258c3c5b..91e5e495af2 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGStoreApi.m @@ -13,7 +13,7 @@ static SWGStoreApi* singletonAPI = nil; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; @@ -26,7 +26,7 @@ static SWGStoreApi* singletonAPI = nil; return self; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { +- (instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { self.apiClient = apiClient; @@ -84,9 +84,7 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { @@ -96,22 +94,16 @@ static SWGStoreApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -148,31 +140,23 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[@"api_key"]; @@ -216,9 +200,7 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { @@ -228,22 +210,16 @@ static SWGStoreApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -282,31 +258,23 @@ static SWGStoreApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h similarity index 82% rename from samples/client/petstore/objc/SwaggerClient/SWGUserApi.h rename to samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h index 6f3561dfbf3..73dcef55c02 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.h @@ -19,79 +19,77 @@ -(unsigned long) requestQueueSize; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGUserApi*) sharedAPI; -/// -/// /// Create user /// This can only be done by the logged in user. /// /// @param body Created user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Creates list of users with given input array /// /// /// @param body List of user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Creates list of users with given input array /// /// /// @param body List of user object (optional) /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted /// +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" /// /// @return -(NSNumber*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" /// /// @return SWGUser* -(NSNumber*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; -/// -/// /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username/password supplied" /// /// @return NSString* -(NSNumber*) loginUserWithUsername: (NSString*) username @@ -99,26 +97,25 @@ completionHandler: (void (^)(NSString* output, NSError* error)) handler; -/// -/// /// Logs out current logged in user session /// /// /// +/// code:0 message:"successful operation" /// /// @return -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; -/// -/// /// Updated user /// This can only be done by the logged in user. /// /// @param username name that need to be deleted /// @param body Updated user object (optional) /// +/// code:400 message:"Invalid user supplied", +/// code:404 message:"User not found" /// /// @return -(NSNumber*) updateUserWithUsername: (NSString*) username diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.m similarity index 75% rename from samples/client/petstore/objc/SwaggerClient/SWGUserApi.m rename to samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.m index 914d1822402..ecb5aa7ba53 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/Api/SWGUserApi.m @@ -13,7 +13,7 @@ static SWGUserApi* singletonAPI = nil; #pragma mark - Initialize methods -- (id) init { +- (instancetype) init { self = [super init]; if (self) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; @@ -26,7 +26,7 @@ static SWGUserApi* singletonAPI = nil; return self; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { +- (instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { self.apiClient = apiClient; @@ -79,31 +79,23 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -143,31 +135,23 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -207,31 +191,23 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -276,9 +252,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -288,22 +262,16 @@ static SWGUserApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -347,9 +315,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -359,22 +325,16 @@ static SWGUserApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -416,9 +376,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; @@ -431,22 +389,16 @@ static SWGUserApi* singletonAPI = nil; } NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -483,31 +435,23 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; @@ -554,9 +498,7 @@ static SWGUserApi* singletonAPI = nil; NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { - [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; - } + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { @@ -566,22 +508,16 @@ static SWGUserApi* singletonAPI = nil; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; // HTTP header `Accept` - headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; - if ([headerParams[@"Accept"] length] == 0) { - [headerParams removeObjectForKey:@"Accept"]; + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"application/xml"]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; } // response content type - NSString *responseContentType; - if ([headerParams objectForKey:@"Accept"]) { - responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; - } - else { - responseContentType = @""; - } + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; // request content type - NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting NSArray *authSettings = @[]; diff --git a/samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.h b/samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.h rename to samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h diff --git a/samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.m b/samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/JSONValueTransformer+ISO8601.m rename to samples/client/petstore/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.h similarity index 79% rename from samples/client/petstore/objc/SwaggerClient/SWGApiClient.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.h index 82472ab20bf..adbb8f15a62 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.h @@ -7,6 +7,7 @@ #import "SWGConfiguration.h" #import "SWGResponseDeserializer.h" #import "SWGSanitizer.h" +#import "SWGLogger.h" /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen @@ -30,13 +31,6 @@ */ extern NSString *const SWGResponseObjectErrorKey; -/** - * Log debug message macro - */ -#ifndef SWGDebugLog - #define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -#endif - @interface SWGApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @@ -117,15 +111,6 @@ extern NSString *const SWGResponseObjectErrorKey; */ +(void) cancelRequest:(NSNumber*)requestId; -/** - * Gets URL encoded NSString - * - * @param unescaped The string which will be escaped. - * - * @return The escaped string. - */ -+(NSString*) escape:(id)unescaped; - /** * Customizes the behavior when the reachability changed * @@ -138,24 +123,6 @@ extern NSString *const SWGResponseObjectErrorKey; */ - (void)configureCacheReachibility; -/** - * Detects Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ -+(NSString *) selectHeaderAccept:(NSArray *)accepts; - -/** - * Detects Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header - * - * @return The Content-Type header - */ -+(NSString *) selectHeaderContentType:(NSArray *)contentTypes; - /** * Sets header for request * @@ -176,19 +143,6 @@ extern NSString *const SWGResponseObjectErrorKey; queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; -/** - * Logs request and response - * - * @param response NSURLResponse for the HTTP request. - * @param responseObject response object of the HTTP request. - * @param request The HTTP request. - * @param error The error of the HTTP request. - */ -- (void)logResponse:(NSURLResponse *)response - responseObject:(id)responseObject - request:(NSURLRequest *)request - error:(NSError *)error; - /** * Performs request * @@ -226,9 +180,5 @@ extern NSString *const SWGResponseObjectErrorKey; */ - (AFSecurityPolicy *) customSecurityPolicy; -/** - * Log debug message - */ -+(void)debugLog:(NSString *)method message:(NSString *)format, ...; @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m similarity index 69% rename from samples/client/petstore/objc/SwaggerClient/SWGApiClient.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m index 1246dff7fca..55e84a056a4 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGApiClient.m @@ -2,7 +2,7 @@ NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; -static long requestId = 0; +static NSUInteger requestId = 0; static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; @@ -36,7 +36,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { @interface SWGApiClient () -@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; +@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; @end @@ -88,49 +88,6 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; } -#pragma mark - Log Methods - -+ (void)debugLog:(NSString *)method - message:(NSString *)format, ... { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (!config.debug) { - return; - } - - NSMutableString *message = [NSMutableString stringWithCapacity:1]; - - if (method) { - [message appendString:[NSString stringWithFormat:@"%@: ", method]]; - } - - va_list args; - va_start(args, format); - - [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; - - // If set logging file handler, log into file, - // otherwise log into console. - if (config.loggingFileHanlder) { - [config.loggingFileHanlder seekToEndOfFile]; - [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; - } - else { - NSLog(@"%@", message); - } - - va_end(args); -} - -- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { - - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - responseObject]; - - SWGDebugLog(message); -} - #pragma mark - Cache Methods +(void)clearCache { @@ -151,70 +108,6 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { [NSURLCache setSharedURLCache:cache]; } -#pragma mark - Utility Methods - -/* - * Detect `Accept` from accepts - */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts { - if (accepts == nil || [accepts count] == 0) { - return @""; - } - - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - for (NSString *string in accepts) { - NSString * lowerAccept = [string lowercaseString]; - // use rangeOfString instead of containsString for iOS 7 support - if ([lowerAccept rangeOfString:@"application/json"].location != NSNotFound) { - return @"application/json"; - } - [lowerAccepts addObject:lowerAccept]; - } - - if (lowerAccepts.count == 1) { - return [lowerAccepts firstObject]; - } - - return [lowerAccepts componentsJoinedByString:@", "]; -} - -/* - * Detect `Content-Type` from contentTypes - */ -+ (NSString *) selectHeaderContentType:(NSArray *)contentTypes -{ - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; - } - - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; - } -} - -+ (NSString*)escape:(id)unescaped { - if ([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - #pragma mark - Request Methods +(unsigned long)requestQueueSize { @@ -223,14 +116,12 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { +(NSNumber*) nextRequestId { @synchronized(self) { - long nextId = ++requestId; - SWGDebugLog(@"got id %ld", nextId); - return [NSNumber numberWithLong:nextId]; + return @(++requestId); } } +(NSNumber*) queueRequest { - NSNumber* requestId = [SWGApiClient nextRequestId]; + NSNumber* requestId = [[self class] nextRequestId]; SWGDebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; @@ -294,7 +185,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { if (![strongSelf executeRequestWithId:requestId]) { return; } - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + SWGDebugLogResponse(response, responseObject,request,error); strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); @@ -321,7 +212,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return; } strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); - [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + SWGDebugLogResponse(response, responseObject,request,error); if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -370,14 +261,13 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { self.requestSerializer = [AFHTTPRequestSerializer serializer]; } else { - NSAssert(false, @"unsupport request type %@", requestContentType); + NSAssert(NO, @"Unsupported request type %@", requestContentType); } // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { self.responseSerializer = [SWGJSONResponseSerializer serializer]; - } - else { + } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } @@ -393,8 +283,9 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSMutableString *resourcePath = [NSMutableString stringWithString:path]; [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] - withString:[SWGApiClient escape:obj]]; + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = SWGPercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; NSMutableURLRequest * request = nil; @@ -438,10 +329,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { } // request cache - BOOL hasHeaderParams = false; - if (headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } + BOOL hasHeaderParams = [headerParams count] > 0; if (offlineState) { SWGDebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; @@ -462,9 +350,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { } [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + [self postProcessRequest:request]; NSNumber* requestId = [SWGApiClient queueRequest]; if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { @@ -485,59 +371,66 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return requestId; } +//Added for easier override to modify request +-(void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + #pragma mark - - (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } NSString * separator = nil; - int counter = 0; + NSUInteger counter = 0; NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if (queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if (counter == 0) separator = @"?"; - else separator = @"&"; - id queryParam = [queryParams valueForKey:key]; - if ([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [SWGApiClient escape:[queryParams valueForKey:key]]]]; - } - else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ - SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - if ([format isEqualToString:@"csv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; - - } - else if ([format isEqualToString:@"tsv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; - - } - else if ([format isEqualToString:@"pipes"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; - - } - else if ([format isEqualToString:@"multi"]) { - for(id obj in values) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; - counter += 1; - } - - } - } - else { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [SWGApiClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; - } - - counter += 1; + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = SWGPercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, SWGPercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ + SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = SWGPercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = SWGPercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = SWGPercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; } return requestUrl; } @@ -558,15 +451,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { SWGConfiguration *config = [SWGConfiguration sharedConfig]; for (NSString *auth in authSettings) { - NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - - if (authSetting) { // auth setting is set only if the key is non-empty - if ([authSetting[@"in"] isEqualToString:@"header"] && [authSetting[@"key"] length] != 0) { - [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - else if ([authSetting[@"in"] isEqualToString:@"query"] && [authSetting[@"key"] length] != 0) { - [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } + NSDictionary *authSetting = [config authSettings][auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.h similarity index 89% rename from samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.h index 27cfe5d6d24..056175019a4 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.h @@ -1,5 +1,6 @@ #import #import "SWGApiClient.h" +#import "SWGLogger.h" /** The `SWGConfiguration` class manages the configurations for the sdk. * @@ -12,6 +13,11 @@ @interface SWGConfiguration : NSObject +/** + * Default api logger + */ +@property (nonatomic, strong) SWGLogger * logger; + /** * Default api client */ @@ -37,7 +43,7 @@ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename for HTTP Basic Authentication + * Username for HTTP Basic Authentication */ @property (nonatomic) NSString *username; @@ -56,25 +62,11 @@ */ @property (nonatomic) NSString *tempFolderPath; -/** - * Logging Settings - */ - /** * Debug switch, default false */ @property (nonatomic) BOOL debug; -/** - * Debug file location, default log in console - */ -@property (nonatomic) NSString *loggingFile; - -/** - * Log file handler, this property is used by sdk internally. - */ -@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; - /** * Gets configuration singleton instance */ @@ -143,7 +135,7 @@ - (NSString *) getAccessToken; /** - * Gets Authentication Setings + * Gets Authentication Settings */ - (NSDictionary *) authSettings; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.m similarity index 73% rename from samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.m index dd1596bf8ce..b2430daaecd 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGConfiguration.m @@ -30,12 +30,10 @@ self.username = @""; self.password = @""; self.accessToken= @""; - self.tempFolderPath = nil; - self.debug = NO; self.verifySSL = YES; - self.loggingFile = nil; self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + self.logger = [SWGLogger sharedLogger]; } return self; } @@ -43,11 +41,13 @@ #pragma mark - Instance Methods - (NSString *) getApiKeyWithPrefix:(NSString *)key { - if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // both api key prefix and api key are set - return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; } - else if ([self.apiKey objectForKey:key] != (id)[NSNull null] && [[self.apiKey objectForKey:key] length] != 0) { // only api key, no api key prefix - return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; } else { // return empty string if nothing is set return @""; @@ -70,8 +70,7 @@ - (NSString *) getAccessToken { if (self.accessToken.length == 0) { // token not set, return empty string return @""; - } - else { + } else { return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; } } @@ -94,20 +93,6 @@ [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } -- (void) setLoggingFile:(NSString *)loggingFile { - // close old file handler - if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { - [self.loggingFileHanlder closeFile]; - } - - _loggingFile = loggingFile; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (_loggingFileHanlder == nil) { - [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - } -} - #pragma mark - Getter Methods - (NSDictionary *) apiKey { @@ -139,4 +124,12 @@ }; } +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONRequestSerializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGJSONResponseSerializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.h new file mode 100644 index 00000000000..19c1e509dfa --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.h @@ -0,0 +1,54 @@ +#import + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#ifndef SWGDebugLogResponse +#define SWGDebugLogResponse(response, responseObject,request, error) [[SWGLogger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; +#endif + +/** + * Log debug message macro + */ +#ifndef SWGDebugLog +#define SWGDebugLog(format, ...) [[SWGLogger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif + +@interface SWGLogger : NSObject + ++(instancetype)sharedLogger; + +/** + * Enabled switch, default NO - default set by SWGConfiguration debug property + */ +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +/** + * Debug file location, default log in console + */ +@property (nonatomic, strong) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; + +/** + * Log debug message + */ +-(void)debugLog:(NSString *)method message:(NSString *)format, ...; + +/** + * Logs request and response + * + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.m new file mode 100644 index 00000000000..322ae9678d7 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGLogger.m @@ -0,0 +1,74 @@ +#import "SWGLogger.h" + +@interface SWGLogger () + +@end + +@implementation SWGLogger + ++ (instancetype) sharedLogger { + static SWGLogger *shardLogger = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardLogger = [[self alloc] init]; + }); + return shardLogger; +} + +#pragma mark - Log Methods + +- (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + if (!self.isEnabled) { + return; + } + + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendFormat:@"%@: ", method]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. + if (self.loggingFileHandler) { + [self.loggingFileHandler seekToEndOfFile]; + [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } else { + NSLog(@"%@", message); + } + + va_end(args); +} + +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + responseObject]; + + SWGDebugLog(message); +} + +- (void) setLoggingFile:(NSString *)loggingFile { + if(_loggingFile == loggingFile) { + return; + } + // close old file handler + if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHandler closeFile]; + } + _loggingFile = loggingFile; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHandler == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGObject.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGObject.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGObject.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGObject.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGObject.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGObject.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGObject.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGObject.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGQueryParamCollection.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGQueryParamCollection.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m rename to samples/client/petstore/objc/SwaggerClient/Core/SWGResponseDeserializer.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.h similarity index 54% rename from samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h rename to samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.h index 5803999f362..aa2c6f85163 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.h +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.h @@ -6,6 +6,8 @@ * Do not edit the class manually. */ +extern NSString * SWGPercentEscapedStringFromString(NSString *string); + @protocol SWGSanitizer /** @@ -20,6 +22,24 @@ */ - (NSString *) parameterToString: (id) param; +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ +-(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ +-(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + @end @interface SWGSanitizer : NSObject diff --git a/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.m b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.m new file mode 100644 index 00000000000..a74f72afbe3 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient/Core/SWGSanitizer.m @@ -0,0 +1,168 @@ +#import "SWGSanitizer.h" +#import "SWGObject.h" +#import "SWGQueryParamCollection.h" +#import + +NSString * SWGPercentEscapedStringFromString(NSString *string) { + static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@"; + static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kSWGCharactersGeneralDelimitersToEncode stringByAppendingString:kSWGCharactersSubDelimitersToEncode]]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +@interface SWGSanitizer () + +@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; + +@end + +@implementation SWGSanitizer + +static NSString * kApplicationJSONType = @"application/json"; + +-(instancetype)init { + self = [super init]; + if ( !self ) { + return nil; + } + _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; + return self; +} + + +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [self dateParameterToString:object]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + [sanitizedObjs addObject:sanitizedObj]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + sanitizedObjs[key] = sanitizedObj; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [self dateParameterToString:param]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam = [NSMutableArray array]; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@","]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + +- (NSString *)dateParameterToString:(id)param { + return [param ISO8601String]; +} + +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ +- (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts.count == 0) { + return @""; + } + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { + return kApplicationJSONType; + } + [lowerAccepts addObject:[string lowercaseString]]; + } + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ +- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { + if (contentTypes.count == 0) { + return kApplicationJSONType; + } + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + for (NSString *string in contentTypes) { + if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ + return kApplicationJSONType; + } + [lowerContentTypes addObject:[string lowercaseString]]; + } + return [lowerContentTypes firstObject]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGCategory.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGCategory.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGCategory.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGOrder.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGOrder.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGOrder.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGPet.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGPet.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGPet.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGPet.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGPet.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGTag.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGTag.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGTag.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGTag.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGTag.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.h b/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.h similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGUser.h rename to samples/client/petstore/objc/SwaggerClient/Model/SWGUser.h diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/Model/SWGUser.m similarity index 100% rename from samples/client/petstore/objc/SwaggerClient/SWGUser.m rename to samples/client/petstore/objc/SwaggerClient/Model/SWGUser.m diff --git a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m b/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m deleted file mode 100644 index 3f1dea7726e..00000000000 --- a/samples/client/petstore/objc/SwaggerClient/SWGSanitizer.m +++ /dev/null @@ -1,82 +0,0 @@ -#import "SWGSanitizer.h" -#import "SWGObject.h" -#import "SWGQueryParamCollection.h" -#import - -@interface SWGSanitizer () - -@end - -@implementation SWGSanitizer - -- (id) sanitizeForSerialization:(id) object { - if (object == nil) { - return nil; - } - else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { - return object; - } - else if ([object isKindOfClass:[NSDate class]]) { - return [object ISO8601String]; - } - else if ([object isKindOfClass:[NSArray class]]) { - NSArray *objectArray = object; - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; - [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - id sanitizedObj = [self sanitizeForSerialization:obj]; - if (sanitizedObj) { - [sanitizedObjs addObject:sanitizedObj]; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[NSDictionary class]]) { - NSDictionary *objectDict = object; - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; - [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - id sanitizedObj = [self sanitizeForSerialization:obj]; - if (sanitizedObj) { - sanitizedObjs[key] = sanitizedObj; - } - }]; - return sanitizedObjs; - } - else if ([object isKindOfClass:[SWGObject class]]) { - return [object toDictionary]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] - userInfo:nil]; - @throw e; - } -} - -- (NSString *) parameterToString:(id)param { - if ([param isKindOfClass:[NSString class]]) { - return param; - } - else if ([param isKindOfClass:[NSNumber class]]) { - return [param stringValue]; - } - else if ([param isKindOfClass:[NSDate class]]) { - return [param ISO8601String]; - } - else if ([param isKindOfClass:[NSArray class]]) { - NSMutableArray *mutableParam = [NSMutableArray array]; - [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [mutableParam addObject:[self parameterToString:obj]]; - }]; - return [mutableParam componentsJoinedByString:@","]; - } - else { - NSException *e = [NSException - exceptionWithName:@"InvalidObjectArgumentException" - reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] - userInfo:nil]; - @throw e; - } -} - -@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m index 7ddc817e9ef..f472c4d6ab5 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m @@ -1,7 +1,6 @@ #import #import #import -#import @interface PetApiTest : XCTestCase { @private @@ -165,13 +164,13 @@ which causes an exception when deserializing the data SWGTag* tag = [[SWGTag alloc] init]; tag.name = @"tony"; NSLog(@"%@", pet._id); - pet.tags = (id)[[NSArray alloc] initWithObjects:tag, nil]; + pet.tags = (id) @[tag]; [api addPetWithBody:pet completionHandler:^(NSError *error) { if(error) { XCTFail(@"got error %@", error); } - NSArray* tags = [[NSArray alloc] initWithObjects:@"tony", nil]; + NSArray* tags = @[@"tony",@"tony2"]; [api findPetsByTagsWithTags:tags completionHandler:^(NSArray *output, NSError *error) { if(error){ @@ -275,7 +274,7 @@ which causes an exception when deserializing the data - (SWGPet*) createPet { SWGPet * pet = [[SWGPet alloc] init]; - pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; + pet._id = @((long) [[NSDate date] timeIntervalSince1970]); pet.name = @"monkey"; SWGCategory * category = [[SWGCategory alloc] init]; @@ -289,11 +288,11 @@ which causes an exception when deserializing the data SWGTag *tag2 = [[SWGTag alloc] init]; tag2._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; tag2.name = @"test tag 2"; - pet.tags = (NSArray *)[[NSArray alloc] initWithObjects:tag1, tag2, nil]; + pet.tags = (NSArray *) @[tag1, tag2]; pet.status = @"available"; - NSArray * photos = [[NSArray alloc] initWithObjects:@"http://foo.bar.com/3", @"http://foo.bar.com/4", nil]; + NSArray * photos = @[@"http://foo.bar.com/3", @"http://foo.bar.com/4"]; pet.photoUrls = photos; return pet; } diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index ed87d8f9e2d..205c3a290f8 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -25,38 +25,61 @@ NSArray *accepts = nil; accepts = @[@"APPLICATION/JSON", @"APPLICATION/XML"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + SWGSanitizer * sanitizer = [[SWGSanitizer alloc] init]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"application/json", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"APPLICATION/xml", @"APPLICATION/json"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/json;charset=utf-8", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github.v3.html+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); + + accepts = @[@"application/vnd.github.v3.html+json"]; + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"application/json"); accepts = @[@"text/plain", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @"text/plain, application/xml"); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @"text/plain, application/xml"); accepts = @[]; - XCTAssertEqualObjects([SWGApiClient selectHeaderAccept:accepts], @""); + XCTAssertEqualObjects([sanitizer selectHeaderAccept:accepts], @""); } - (void)testSelectHeaderContentType { NSArray *contentTypes = nil; - + SWGSanitizer * sanitizer = [[SWGSanitizer alloc] init]; + contentTypes = @[@"APPLICATION/JSON", @"APPLICATION/XML"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); contentTypes = @[@"application/json", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); contentTypes = @[@"APPLICATION/xml", @"APPLICATION/json"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); - + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/vnd.github+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/json;charset=utf-8", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + + contentTypes = @[@"application/vnd.github.v3.html+json", @"application/vnd.github+xml"]; + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); + contentTypes = @[@"text/plain", @"application/xml"]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"text/plain"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"text/plain"); contentTypes = @[]; - XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); + XCTAssertEqualObjects([sanitizer selectHeaderContentType:contentTypes], @"application/json"); } - (void)testConfiguration { diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index fe09a19fa93..9da8dacc922 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -1,11 +1,11 @@ # SwaggerClient-php -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Package version: 1.0.0 -- Build date: 2016-05-10T22:37:00.768+08:00 +- Package version: +- Build date: 2016-05-14T13:02:51.476+02:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -41,7 +41,7 @@ Download the files and include `autoload.php`: require_once('/path/to/SwaggerClient-php/autoload.php'); ``` -## Tests +## Tests To run the unit tests: @@ -87,59 +87,53 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**testEndpointParameters**](docs/ApiFakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*PetApi* | [**addPet**](docs/ApiPetApi.md#addpet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](docs/ApiPetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](docs/ApiPetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](docs/ApiPetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](docs/ApiPetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](docs/ApiPetApi.md#updatepet) | **PUT** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](docs/ApiPetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](docs/ApiPetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](docs/ApiStoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**getInventory**](docs/ApiStoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](docs/ApiStoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](docs/ApiStoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet -*UserApi* | [**createUser**](docs/ApiUserApi.md#createuser) | **POST** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](docs/ApiUserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](docs/ApiUserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](docs/ApiUserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user -*UserApi* | [**getUserByName**](docs/ApiUserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](docs/ApiUserApi.md#loginuser) | **GET** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](docs/ApiUserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](docs/ApiUserApi.md#updateuser) | **PUT** /user/{username} | Updated user +*FakeApi* | [**testEndpointParameters**](docs/Api/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*PetApi* | [**addPet**](docs/Api/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/Api/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/Api/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/Api/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/Api/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/Api/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/Api/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/Api/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/Api/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/Api/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/Api/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/Api/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/Api/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/Api/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/Api/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/Api/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/Api/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/Api/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/Api/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/Api/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models - - [Animal](docs/ModelAnimal.md) - - [AnimalFarm](docs/ModelAnimalFarm.md) - - [ApiResponse](docs/ModelApiResponse.md) - - [Cat](docs/ModelCat.md) - - [Category](docs/ModelCategory.md) - - [Dog](docs/ModelDog.md) - - [EnumClass](docs/ModelEnumClass.md) - - [EnumTest](docs/ModelEnumTest.md) - - [FormatTest](docs/ModelFormatTest.md) - - [Model200Response](docs/ModelModel200Response.md) - - [ModelReturn](docs/ModelModelReturn.md) - - [Name](docs/ModelName.md) - - [Order](docs/ModelOrder.md) - - [Pet](docs/ModelPet.md) - - [SpecialModelName](docs/ModelSpecialModelName.md) - - [Tag](docs/ModelTag.md) - - [User](docs/ModelUser.md) + - [Animal](docs/Model/Animal.md) + - [AnimalFarm](docs/Model/AnimalFarm.md) + - [ApiResponse](docs/Model/ApiResponse.md) + - [Cat](docs/Model/Cat.md) + - [Category](docs/Model/Category.md) + - [Dog](docs/Model/Dog.md) + - [EnumClass](docs/Model/EnumClass.md) + - [EnumTest](docs/Model/EnumTest.md) + - [FormatTest](docs/Model/FormatTest.md) + - [Model200Response](docs/Model/Model200Response.md) + - [ModelReturn](docs/Model/ModelReturn.md) + - [Name](docs/Model/Name.md) + - [Order](docs/Model/Order.md) + - [Pet](docs/Model/Pet.md) + - [SpecialModelName](docs/Model/SpecialModelName.md) + - [Tag](docs/Model/Tag.md) + - [User](docs/Model/User.md) ## Documentation For Authorization -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## petstore_auth - **Type**: OAuth @@ -149,6 +143,12 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/php/SwaggerClient-php/autoload.php b/samples/client/petstore/php/SwaggerClient-php/autoload.php index acbd3968b23..3cbe3df8a21 100644 --- a/samples/client/petstore/php/SwaggerClient-php/autoload.php +++ b/samples/client/petstore/php/SwaggerClient-php/autoload.php @@ -1,14 +1,15 @@ testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); } catch (Exception $e) { echo 'Exception when calling FakeApi->testEndpointParameters: ', $e->getMessage(), "\n"; @@ -71,5 +71,5 @@ No authorization required - **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) +[[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/php/SwaggerClient-php/docs/Api/PetApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md index bf119270a58..6ab902730c7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md @@ -21,7 +21,7 @@ Add a new pet to the store -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store -try { +try { $api_instance->addPet($body); } catch (Exception $e) { echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), "\n"; @@ -44,7 +44,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Pet**](\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | + **body** | [**\Swagger\Client\Model\Pet**](../Model/\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -52,14 +52,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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($pet_id, $api_key) @@ -68,7 +68,7 @@ Deletes a pet -### Example +### Example ```php deletePet($pet_id, $api_key); } catch (Exception $e) { echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), "\n"; @@ -101,14 +101,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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** > \Swagger\Client\Model\Pet[] findPetsByStatus($status) @@ -117,7 +117,7 @@ Finds Pets by status Multiple status values can be provided with comma separated strings -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $status = array("status_example"); // string[] | Status values that need to be considered for filter -try { +try { $result = $api_instance->findPetsByStatus($status); print_r($result); } catch (Exception $e) { @@ -141,22 +141,22 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**string[]**](string.md)| Status values that need to be considered for filter | + **status** | [**string[]**](../Model/string.md)| Status values that need to be considered for filter | ### Return type -[**\Swagger\Client\Model\Pet[]**](Pet.md) +[**\Swagger\Client\Model\Pet[]**](../Model/Pet.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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** > \Swagger\Client\Model\Pet[] findPetsByTags($tags) @@ -165,7 +165,7 @@ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $tags = array("tags_example"); // string[] | Tags to filter by -try { +try { $result = $api_instance->findPetsByTags($tags); print_r($result); } catch (Exception $e) { @@ -189,22 +189,22 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**string[]**](string.md)| Tags to filter by | + **tags** | [**string[]**](../Model/string.md)| Tags to filter by | ### Return type -[**\Swagger\Client\Model\Pet[]**](Pet.md) +[**\Swagger\Client\Model\Pet[]**](../Model/Pet.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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** > \Swagger\Client\Model\Pet getPetById($pet_id) @@ -213,7 +213,7 @@ Find pet by ID Returns a single pet -### Example +### Example ```php setApiKey('api_key', 'Y $api_instance = new Swagger\Client\Api\PetApi(); $pet_id = 789; // int | ID of pet to return -try { +try { $result = $api_instance->getPetById($pet_id); print_r($result); } catch (Exception $e) { @@ -243,18 +243,18 @@ Name | Type | Description | Notes ### Return type -[**\Swagger\Client\Model\Pet**](Pet.md) +[**\Swagger\Client\Model\Pet**](../Model/Pet.md) ### Authorization -[api_key](../README.md#api_key) +[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) +[[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($body) @@ -263,7 +263,7 @@ Update an existing pet -### Example +### Example ```php setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store -try { +try { $api_instance->updatePet($body); } catch (Exception $e) { echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), "\n"; @@ -286,7 +286,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Pet**](\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | + **body** | [**\Swagger\Client\Model\Pet**](../Model/\Swagger\Client\Model\Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -294,14 +294,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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($pet_id, $name, $status) @@ -310,7 +310,7 @@ Updates a pet in the store with form data -### Example +### Example ```php updatePetWithForm($pet_id, $name, $status); } catch (Exception $e) { echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), "\n"; @@ -345,14 +345,14 @@ void (empty response body) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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** > \Swagger\Client\Model\ApiResponse uploadFile($pet_id, $additional_metadata, $file) @@ -361,7 +361,7 @@ uploads an image -### Example +### Example ```php uploadFile($pet_id, $additional_metadata, $file); print_r($result); } catch (Exception $e) { @@ -393,16 +393,16 @@ Name | Type | Description | Notes ### Return type -[**\Swagger\Client\Model\ApiResponse**](ApiResponse.md) +[**\Swagger\Client\Model\ApiResponse**](../Model/ApiResponse.md) ### Authorization -[petstore_auth](../README.md#petstore_auth) +[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) +[[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/php/SwaggerClient-php/docs/Api/StoreApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md index 7040df371a4..24cacd22b47 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md @@ -17,7 +17,7 @@ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -### Example +### Example ```php deleteOrder($order_id); } catch (Exception $e) { echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), "\n"; @@ -52,7 +52,7 @@ No authorization required - **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) +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) # **getInventory** > map[string,int] getInventory() @@ -61,7 +61,7 @@ Returns pet inventories by status Returns a map of status codes to quantities -### Example +### Example ```php setApiKey('api_key', 'Y $api_instance = new Swagger\Client\Api\StoreApi(); -try { +try { $result = $api_instance->getInventory(); print_r($result); } catch (Exception $e) { @@ -87,18 +87,18 @@ This endpoint does not need any parameter. ### Return type -[**map[string,int]**](map.md) +[**map[string,int]**](../Model/map.md) ### Authorization -[api_key](../README.md#api_key) +[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) +[[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** > \Swagger\Client\Model\Order getOrderById($order_id) @@ -107,7 +107,7 @@ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -### Example +### Example ```php getOrderById($order_id); print_r($result); } catch (Exception $e) { @@ -132,7 +132,7 @@ Name | Type | Description | Notes ### Return type -[**\Swagger\Client\Model\Order**](Order.md) +[**\Swagger\Client\Model\Order**](../Model/Order.md) ### Authorization @@ -143,7 +143,7 @@ No authorization required - **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) +[[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** > \Swagger\Client\Model\Order placeOrder($body) @@ -152,7 +152,7 @@ Place an order for a pet -### Example +### Example ```php placeOrder($body); print_r($result); } catch (Exception $e) { @@ -173,11 +173,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\Order**](\Swagger\Client\Model\Order.md)| order placed for purchasing the pet | + **body** | [**\Swagger\Client\Model\Order**](../Model/\Swagger\Client\Model\Order.md)| order placed for purchasing the pet | ### Return type -[**\Swagger\Client\Model\Order**](Order.md) +[**\Swagger\Client\Model\Order**](../Model/Order.md) ### Authorization @@ -188,5 +188,5 @@ No authorization required - **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) +[[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/php/SwaggerClient-php/docs/Api/UserApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md index 7f048a429e3..5737f3cdb5e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/UserApi.md @@ -21,7 +21,7 @@ Create user This can only be done by the logged in user. -### Example +### Example ```php createUser($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), "\n"; @@ -41,7 +41,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User**](\Swagger\Client\Model\User.md)| Created user object | + **body** | [**\Swagger\Client\Model\User**](../Model/\Swagger\Client\Model\User.md)| Created user object | ### Return type @@ -56,7 +56,7 @@ No authorization required - **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) +[[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) @@ -65,7 +65,7 @@ Creates list of users with given input array -### Example +### Example ```php createUsersWithArrayInput($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), "\n"; @@ -85,7 +85,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User[]**](User.md)| List of user object | + **body** | [**\Swagger\Client\Model\User[]**](../Model/User.md)| List of user object | ### Return type @@ -100,7 +100,7 @@ No authorization required - **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) +[[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) @@ -109,7 +109,7 @@ Creates list of users with given input array -### Example +### Example ```php createUsersWithListInput($body); } catch (Exception $e) { echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), "\n"; @@ -129,7 +129,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**\Swagger\Client\Model\User[]**](User.md)| List of user object | + **body** | [**\Swagger\Client\Model\User[]**](../Model/User.md)| List of user object | ### Return type @@ -144,7 +144,7 @@ No authorization required - **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) +[[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) @@ -153,7 +153,7 @@ Delete user This can only be done by the logged in user. -### Example +### Example ```php deleteUser($username); } catch (Exception $e) { echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), "\n"; @@ -188,7 +188,7 @@ No authorization required - **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) +[[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** > \Swagger\Client\Model\User getUserByName($username) @@ -197,7 +197,7 @@ Get user by user name -### Example +### Example ```php getUserByName($username); print_r($result); } catch (Exception $e) { @@ -222,7 +222,7 @@ Name | Type | Description | Notes ### Return type -[**\Swagger\Client\Model\User**](User.md) +[**\Swagger\Client\Model\User**](../Model/User.md) ### Authorization @@ -233,7 +233,7 @@ No authorization required - **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) +[[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) @@ -242,7 +242,7 @@ Logs user into the system -### Example +### Example ```php loginUser($username, $password); print_r($result); } catch (Exception $e) { @@ -280,7 +280,7 @@ No authorization required - **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) +[[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() @@ -289,14 +289,14 @@ Logs out current logged in user session -### Example +### Example ```php logoutUser(); } catch (Exception $e) { echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), "\n"; @@ -320,7 +320,7 @@ No authorization required - **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) +[[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) @@ -329,7 +329,7 @@ Updated user This can only be done by the logged in user. -### Example +### Example ```php updateUser($username, $body); } catch (Exception $e) { echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), "\n"; @@ -351,7 +351,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **string**| name that need to be deleted | - **body** | [**\Swagger\Client\Model\User**](\Swagger\Client\Model\User.md)| Updated user object | + **body** | [**\Swagger\Client\Model\User**](../Model/\Swagger\Client\Model\User.md)| Updated user object | ### Return type @@ -366,5 +366,5 @@ No authorization required - **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) +[[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/php/SwaggerClient-php/docs/ApiResponse.md b/samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md new file mode 100644 index 00000000000..9d351183422 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | [optional] +**type** | **string** | | [optional] +**message** | **string** | | [optional] + +[[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/php/SwaggerClient-php/docs/Cat.md b/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md new file mode 100644 index 00000000000..8d30565d014 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Cat.md @@ -0,0 +1,10 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **bool** | | [optional] + +[[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/php/SwaggerClient-php/docs/Category.md b/samples/client/petstore/php/SwaggerClient-php/docs/Category.md new file mode 100644 index 00000000000..80aef312e5e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[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/php/SwaggerClient-php/docs/Dog.md b/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md new file mode 100644 index 00000000000..3c04bdf4cf7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Dog.md @@ -0,0 +1,10 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **string** | | [optional] + +[[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/php/SwaggerClient-php/docs/EnumClass.md b/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md new file mode 100644 index 00000000000..2ef9e6adaac --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **string** | | [optional] +**enum_integer** | **int** | | [optional] +**enum_number** | **double** | | [optional] + +[[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/php/SwaggerClient-php/docs/FormatTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md new file mode 100644 index 00000000000..90531d28c40 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **int** | | [optional] +**int32** | **int** | | [optional] +**int64** | **int** | | [optional] +**number** | **float** | | +**float** | **float** | | [optional] +**double** | **double** | | [optional] +**string** | **string** | | [optional] +**byte** | **string** | | +**binary** | **string** | | [optional] +**date** | [**\DateTime**](Date.md) | | +**date_time** | [**\DateTime**](\DateTime.md) | | [optional] +**uuid** | [**UUID**](UUID.md) | | [optional] +**password** | **string** | | + +[[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/php/SwaggerClient-php/docs/Model200Response.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md new file mode 100644 index 00000000000..e29747a87e7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model200Response.md @@ -0,0 +1,10 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | [optional] + +[[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/php/SwaggerClient-php/docs/ModelReturn.md b/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md new file mode 100644 index 00000000000..9adb62e1e12 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**return** | **int** | | [optional] + +[[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/php/SwaggerClient-php/docs/Name.md b/samples/client/petstore/php/SwaggerClient-php/docs/Name.md new file mode 100644 index 00000000000..4565647e1ef --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **int** | | +**snake_case** | **int** | | [optional] +**property** | **string** | | [optional] +**_123_number** | **int** | | [optional] + +[[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/php/SwaggerClient-php/docs/Order.md b/samples/client/petstore/php/SwaggerClient-php/docs/Order.md new file mode 100644 index 00000000000..ddae5cc2b57 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**pet_id** | **int** | | [optional] +**quantity** | **int** | | [optional] +**ship_date** | [**\DateTime**](\DateTime.md) | | [optional] +**status** | **string** | Order Status | [optional] +**complete** | **bool** | | [optional] [default to false] + +[[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/php/SwaggerClient-php/docs/Pet.md b/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md new file mode 100644 index 00000000000..4525fe7d776 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**category** | [**\Swagger\Client\Model\Category**](Category.md) | | [optional] +**name** | **string** | | +**photo_urls** | **string[]** | | +**tags** | [**\Swagger\Client\Model\Tag[]**](Tag.md) | | [optional] +**status** | **string** | pet status in the store | [optional] + +[[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/php/SwaggerClient-php/docs/SpecialModelName.md b/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md new file mode 100644 index 00000000000..022ee19169c --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**special_property_name** | **int** | | [optional] + +[[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/php/SwaggerClient-php/docs/Tag.md b/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md new file mode 100644 index 00000000000..15ec3e0a91d --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**name** | **string** | | [optional] + +[[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/php/SwaggerClient-php/docs/User.md b/samples/client/petstore/php/SwaggerClient-php/docs/User.md new file mode 100644 index 00000000000..ff278fd4889 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] +**username** | **string** | | [optional] +**first_name** | **string** | | [optional] +**last_name** | **string** | | [optional] +**email** | **string** | | [optional] +**password** | **string** | | [optional] +**phone** | **string** | | [optional] +**user_status** | **int** | User Status | [optional] + +[[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/php/SwaggerClient-php/git_push.sh b/samples/client/petstore/php/SwaggerClient-php/git_push.sh index ed374619b13..792320114fb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/git_push.sh +++ b/samples/client/petstore/php/SwaggerClient-php/git_push.sh @@ -28,7 +28,7 @@ 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. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 5620c82fdcd..63abb0c94b6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +52,41 @@ class FakeApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return FakeApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,11 +94,11 @@ class FakeApi $this->apiClient = $apiClient; return $this; } - + /** - * testEndpointParameters + * Operation testEndpointParameters * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 . * * @param float $number None (required) * @param double $double None (required) @@ -107,20 +112,21 @@ class FakeApi * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function testEndpointParameters($number, $double, $string, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $binary = null, $date = null, $date_time = null, $password = null) { - list($response) = $this->testEndpointParametersWithHttpInfo ($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); - return $response; + list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password); + return $response; } /** - * testEndpointParametersWithHttpInfo + * Operation testEndpointParametersWithHttpInfo * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 . * * @param float $number None (required) * @param double $double None (required) @@ -134,6 +140,7 @@ class FakeApi * @param \DateTime $date None (optional) * @param \DateTime $date_time None (optional) * @param string $password None (optional) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -202,7 +209,7 @@ class FakeApi throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } - + // parse inputs $resourcePath = "/fake"; $httpBody = ''; @@ -214,7 +221,7 @@ class FakeApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -259,7 +266,7 @@ class FakeApi $formParams['password'] = $this->apiClient->getSerializer()->toFormValue($password); } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -269,16 +276,17 @@ class FakeApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 4ab1529c7c0..402d727c5bf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +52,41 @@ class PetApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return PetApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +94,31 @@ class PetApi $this->apiClient = $apiClient; return $this; } - + /** - * addPet + * Operation addPet * - * Add a new pet to the store + * Add a new pet to the store. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function addPet($body) { - list($response) = $this->addPetWithHttpInfo ($body); - return $response; + list($response) = $this->addPetWithHttpInfo($body); + return $response; } /** - * addPetWithHttpInfo + * Operation addPetWithHttpInfo * - * Add a new pet to the store + * Add a new pet to the store. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -122,7 +129,7 @@ class PetApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling addPet'); } - + // parse inputs $resourcePath = "/pet"; $httpBody = ''; @@ -134,7 +141,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); - + @@ -147,7 +154,7 @@ class PetApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -162,43 +169,46 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * deletePet + * Operation deletePet * - * Deletes a pet + * Deletes a pet. * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deletePet($pet_id, $api_key = null) { - list($response) = $this->deletePetWithHttpInfo ($pet_id, $api_key); - return $response; + list($response) = $this->deletePetWithHttpInfo($pet_id, $api_key); + return $response; } /** - * deletePetWithHttpInfo + * Operation deletePetWithHttpInfo * - * Deletes a pet + * Deletes a pet. * * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -209,7 +219,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -221,7 +231,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // header params if ($api_key !== null) { @@ -240,7 +250,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -255,41 +265,44 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * findPetsByStatus + * Operation findPetsByStatus * - * Finds Pets by status + * Finds Pets by status. * * @param string[] $status Status values that need to be considered for filter (required) + * * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByStatus($status) { - list($response) = $this->findPetsByStatusWithHttpInfo ($status); - return $response; + list($response) = $this->findPetsByStatusWithHttpInfo($status); + return $response; } /** - * findPetsByStatusWithHttpInfo + * Operation findPetsByStatusWithHttpInfo * - * Finds Pets by status + * Finds Pets by status. * * @param string[] $status Status values that need to be considered for filter (required) + * * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -300,7 +313,7 @@ class PetApi if ($status === null) { throw new \InvalidArgumentException('Missing the required parameter $status when calling findPetsByStatus'); } - + // parse inputs $resourcePath = "/pet/findByStatus"; $httpBody = ''; @@ -312,7 +325,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if (is_array($status)) { $status = $this->apiClient->getSerializer()->serializeCollection($status, 'csv', true); @@ -327,7 +340,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -342,48 +355,53 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet[]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * findPetsByTags + * Operation findPetsByTags * - * Finds Pets by tags + * Finds Pets by tags. * * @param string[] $tags Tags to filter by (required) + * * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByTags($tags) { - list($response) = $this->findPetsByTagsWithHttpInfo ($tags); - return $response; + list($response) = $this->findPetsByTagsWithHttpInfo($tags); + return $response; } /** - * findPetsByTagsWithHttpInfo + * Operation findPetsByTagsWithHttpInfo * - * Finds Pets by tags + * Finds Pets by tags. * * @param string[] $tags Tags to filter by (required) + * * @return Array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -394,7 +412,7 @@ class PetApi if ($tags === null) { throw new \InvalidArgumentException('Missing the required parameter $tags when calling findPetsByTags'); } - + // parse inputs $resourcePath = "/pet/findByTags"; $httpBody = ''; @@ -406,7 +424,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if (is_array($tags)) { $tags = $this->apiClient->getSerializer()->serializeCollection($tags, 'csv', true); @@ -421,7 +439,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -436,48 +454,53 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet[]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * getPetById + * Operation getPetById * - * Find pet by ID + * Find pet by ID. * * @param int $pet_id ID of pet to return (required) + * * @return \Swagger\Client\Model\Pet * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) { - list($response) = $this->getPetByIdWithHttpInfo ($pet_id); - return $response; + list($response) = $this->getPetByIdWithHttpInfo($pet_id); + return $response; } /** - * getPetByIdWithHttpInfo + * Operation getPetByIdWithHttpInfo * - * Find pet by ID + * Find pet by ID. * * @param int $pet_id ID of pet to return (required) + * * @return Array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -488,7 +511,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -500,7 +523,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -516,7 +539,7 @@ class PetApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -533,48 +556,53 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * updatePet + * Operation updatePet * - * Update an existing pet + * Update an existing pet. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePet($body) { - list($response) = $this->updatePetWithHttpInfo ($body); - return $response; + list($response) = $this->updatePetWithHttpInfo($body); + return $response; } /** - * updatePetWithHttpInfo + * Operation updatePetWithHttpInfo * - * Update an existing pet + * Update an existing pet. * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -585,7 +613,7 @@ class PetApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updatePet'); } - + // parse inputs $resourcePath = "/pet"; $httpBody = ''; @@ -597,7 +625,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); - + @@ -610,7 +638,7 @@ class PetApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -625,45 +653,48 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'PUT', - $queryParams, $httpBody, + $resourcePath, + 'PUT', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * updatePetWithForm + * Operation updatePetWithForm * - * Updates a pet in the store with form data + * Updates a pet in the store with form data. * * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePetWithForm($pet_id, $name = null, $status = null) { - list($response) = $this->updatePetWithFormWithHttpInfo ($pet_id, $name, $status); - return $response; + list($response) = $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); + return $response; } /** - * updatePetWithFormWithHttpInfo + * Operation updatePetWithFormWithHttpInfo * - * Updates a pet in the store with form data + * Updates a pet in the store with form data. * * @param int $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -674,7 +705,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $httpBody = ''; @@ -686,7 +717,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); - + // path params @@ -708,7 +739,7 @@ class PetApi $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -723,45 +754,48 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * uploadFile + * Operation uploadFile * - * uploads an image + * uploads an image. * * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) + * * @return \Swagger\Client\Model\ApiResponse * @throws \Swagger\Client\ApiException on non-2xx response */ public function uploadFile($pet_id, $additional_metadata = null, $file = null) { - list($response) = $this->uploadFileWithHttpInfo ($pet_id, $additional_metadata, $file); - return $response; + list($response) = $this->uploadFileWithHttpInfo($pet_id, $additional_metadata, $file); + return $response; } /** - * uploadFileWithHttpInfo + * Operation uploadFileWithHttpInfo * - * uploads an image + * uploads an image. * * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) + * * @return Array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -772,7 +806,7 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } - + // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; $httpBody = ''; @@ -784,7 +818,7 @@ class PetApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); - + // path params @@ -808,11 +842,11 @@ class PetApi if (function_exists('curl_file_create')) { $formParams['file'] = curl_file_create($this->apiClient->getSerializer()->toFormValue($file)); } else { - $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); + $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); } } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -827,23 +861,26 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\ApiResponse' + $resourcePath, + 'POST', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\ApiResponse' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index a238eb41312..cfc6ddba361 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +52,41 @@ class StoreApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return StoreApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +94,31 @@ class StoreApi $this->apiClient = $apiClient; return $this; } - + /** - * deleteOrder + * Operation deleteOrder * - * Delete purchase order by ID + * Delete purchase order by ID. * * @param string $order_id ID of the order that needs to be deleted (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrder($order_id) { - list($response) = $this->deleteOrderWithHttpInfo ($order_id); - return $response; + list($response) = $this->deleteOrderWithHttpInfo($order_id); + return $response; } /** - * deleteOrderWithHttpInfo + * Operation deleteOrderWithHttpInfo * - * Delete purchase order by ID + * Delete purchase order by ID. * * @param string $order_id ID of the order that needs to be deleted (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -126,7 +133,7 @@ class StoreApi throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.deleteOrder, must be bigger than or equal to 1.0.'); } - + // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; @@ -138,7 +145,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -154,7 +161,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -164,45 +171,48 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * getInventory + * Operation getInventory + * + * Returns pet inventories by status. * - * Returns pet inventories by status * * @return map[string,int] * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventory() { - list($response) = $this->getInventoryWithHttpInfo (); - return $response; + list($response) = $this->getInventoryWithHttpInfo(); + return $response; } /** - * getInventoryWithHttpInfo + * Operation getInventoryWithHttpInfo + * + * Returns pet inventories by status. * - * Returns pet inventories by status * * @return Array of map[string,int], HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventoryWithHttpInfo() { - + // parse inputs $resourcePath = "/store/inventory"; $httpBody = ''; @@ -214,7 +224,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -223,7 +233,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -240,48 +250,53 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'map[string,int]' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + 'map[string,int]' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * getOrderById + * Operation getOrderById * - * Find purchase order by ID + * Find purchase order by ID. * * @param int $order_id ID of pet that needs to be fetched (required) + * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ public function getOrderById($order_id) { - list($response) = $this->getOrderByIdWithHttpInfo ($order_id); - return $response; + list($response) = $this->getOrderByIdWithHttpInfo($order_id); + return $response; } /** - * getOrderByIdWithHttpInfo + * Operation getOrderByIdWithHttpInfo * - * Find purchase order by ID + * Find purchase order by ID. * * @param int $order_id ID of pet that needs to be fetched (required) + * * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -299,7 +314,7 @@ class StoreApi throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.0.'); } - + // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; @@ -311,7 +326,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -327,7 +342,7 @@ class StoreApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -337,48 +352,53 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Order' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * placeOrder + * Operation placeOrder * - * Place an order for a pet + * Place an order for a pet. * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ public function placeOrder($body) { - list($response) = $this->placeOrderWithHttpInfo ($body); - return $response; + list($response) = $this->placeOrderWithHttpInfo($body); + return $response; } /** - * placeOrderWithHttpInfo + * Operation placeOrderWithHttpInfo * - * Place an order for a pet + * Place an order for a pet. * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * * @return Array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -389,7 +409,7 @@ class StoreApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling placeOrder'); } - + // parse inputs $resourcePath = "/store/order"; $httpBody = ''; @@ -401,7 +421,7 @@ class StoreApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -414,7 +434,7 @@ class StoreApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -424,23 +444,26 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order' + $resourcePath, + 'POST', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Order' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index ed9744b8255..7d3188747a5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -52,36 +52,41 @@ class UserApi /** * API Client + * * @var \Swagger\Client\ApiClient instance of the ApiClient */ protected $apiClient; - + /** * Constructor + * * @param \Swagger\Client\ApiClient|null $apiClient The api client to use */ - function __construct(\Swagger\Client\ApiClient $apiClient = null) + public function __construct(\Swagger\Client\ApiClient $apiClient = null) { if ($apiClient == null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } - + $this->apiClient = $apiClient; } - + /** * Get API client + * * @return \Swagger\Client\ApiClient get the API client */ public function getApiClient() { return $this->apiClient; } - + /** * Set the API client + * * @param \Swagger\Client\ApiClient $apiClient set the API client + * * @return UserApi */ public function setApiClient(\Swagger\Client\ApiClient $apiClient) @@ -89,29 +94,31 @@ class UserApi $this->apiClient = $apiClient; return $this; } - + /** - * createUser + * Operation createUser * - * Create user + * Create user. * * @param \Swagger\Client\Model\User $body Created user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUser($body) { - list($response) = $this->createUserWithHttpInfo ($body); - return $response; + list($response) = $this->createUserWithHttpInfo($body); + return $response; } /** - * createUserWithHttpInfo + * Operation createUserWithHttpInfo * - * Create user + * Create user. * * @param \Swagger\Client\Model\User $body Created user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -122,7 +129,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUser'); } - + // parse inputs $resourcePath = "/user"; $httpBody = ''; @@ -134,7 +141,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -147,7 +154,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -157,41 +164,44 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * createUsersWithArrayInput + * Operation createUsersWithArrayInput * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithArrayInput($body) { - list($response) = $this->createUsersWithArrayInputWithHttpInfo ($body); - return $response; + list($response) = $this->createUsersWithArrayInputWithHttpInfo($body); + return $response; } /** - * createUsersWithArrayInputWithHttpInfo + * Operation createUsersWithArrayInputWithHttpInfo * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -202,7 +212,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithArrayInput'); } - + // parse inputs $resourcePath = "/user/createWithArray"; $httpBody = ''; @@ -214,7 +224,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -227,7 +237,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -237,41 +247,44 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * createUsersWithListInput + * Operation createUsersWithListInput * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithListInput($body) { - list($response) = $this->createUsersWithListInputWithHttpInfo ($body); - return $response; + list($response) = $this->createUsersWithListInputWithHttpInfo($body); + return $response; } /** - * createUsersWithListInputWithHttpInfo + * Operation createUsersWithListInputWithHttpInfo * - * Creates list of users with given input array + * Creates list of users with given input array. * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -282,7 +295,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithListInput'); } - + // parse inputs $resourcePath = "/user/createWithList"; $httpBody = ''; @@ -294,7 +307,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -307,7 +320,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -317,41 +330,44 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'POST', - $queryParams, $httpBody, + $resourcePath, + 'POST', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * deleteUser + * Operation deleteUser * - * Delete user + * Delete user. * * @param string $username The name that needs to be deleted (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteUser($username) { - list($response) = $this->deleteUserWithHttpInfo ($username); - return $response; + list($response) = $this->deleteUserWithHttpInfo($username); + return $response; } /** - * deleteUserWithHttpInfo + * Operation deleteUserWithHttpInfo * - * Delete user + * Delete user. * * @param string $username The name that needs to be deleted (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -362,7 +378,7 @@ class UserApi if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -374,7 +390,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -390,7 +406,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -400,41 +416,44 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'DELETE', - $queryParams, $httpBody, + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * getUserByName + * Operation getUserByName * - * Get user by user name + * Get user by user name. * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * * @return \Swagger\Client\Model\User * @throws \Swagger\Client\ApiException on non-2xx response */ public function getUserByName($username) { - list($response) = $this->getUserByNameWithHttpInfo ($username); - return $response; + list($response) = $this->getUserByNameWithHttpInfo($username); + return $response; } /** - * getUserByNameWithHttpInfo + * Operation getUserByNameWithHttpInfo * - * Get user by user name + * Get user by user name. * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * * @return Array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -445,7 +464,7 @@ class UserApi if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -457,7 +476,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -473,7 +492,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -483,50 +502,55 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\User' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\User' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * loginUser + * Operation loginUser * - * Logs user into the system + * Logs user into the system. * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) + * * @return string * @throws \Swagger\Client\ApiException on non-2xx response */ public function loginUser($username, $password) { - list($response) = $this->loginUserWithHttpInfo ($username, $password); - return $response; + list($response) = $this->loginUserWithHttpInfo($username, $password); + return $response; } /** - * loginUserWithHttpInfo + * Operation loginUserWithHttpInfo * - * Logs user into the system + * Logs user into the system. * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) + * * @return Array of string, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -542,7 +566,7 @@ class UserApi if ($password === null) { throw new \InvalidArgumentException('Missing the required parameter $password when calling loginUser'); } - + // parse inputs $resourcePath = "/user/login"; $httpBody = ''; @@ -554,7 +578,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // query params if ($username !== null) { $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); @@ -569,7 +593,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -579,52 +603,57 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, - $headerParams, 'string' + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + 'string' ); if (!$response) { return array(null, $statusCode, $httpHeader); } return array($this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; } - + throw $e; } } /** - * logoutUser + * Operation logoutUser + * + * Logs out current logged in user session. * - * Logs out current logged in user session * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUser() { - list($response) = $this->logoutUserWithHttpInfo (); - return $response; + list($response) = $this->logoutUserWithHttpInfo(); + return $response; } /** - * logoutUserWithHttpInfo + * Operation logoutUserWithHttpInfo + * + * Logs out current logged in user session. * - * Logs out current logged in user session * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUserWithHttpInfo() { - + // parse inputs $resourcePath = "/user/logout"; $httpBody = ''; @@ -636,7 +665,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + @@ -645,7 +674,7 @@ class UserApi - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -655,43 +684,46 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'GET', - $queryParams, $httpBody, + $resourcePath, + 'GET', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } /** - * updateUser + * Operation updateUser * - * Updated user + * Updated user. * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function updateUser($username, $body) { - list($response) = $this->updateUserWithHttpInfo ($username, $body); - return $response; + list($response) = $this->updateUserWithHttpInfo($username, $body); + return $response; } /** - * updateUserWithHttpInfo + * Operation updateUserWithHttpInfo * - * Updated user + * Updated user. * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) + * * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -707,7 +739,7 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updateUser'); } - + // parse inputs $resourcePath = "/user/{username}"; $httpBody = ''; @@ -719,7 +751,7 @@ class UserApi $headerParams['Accept'] = $_header_accept; } $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - + // path params @@ -739,7 +771,7 @@ class UserApi if (isset($body)) { $_tempBody = $body; } - + // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present @@ -749,16 +781,17 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, 'PUT', - $queryParams, $httpBody, + $resourcePath, + 'PUT', + $queryParams, + $httpBody, $headerParams ); - return array(null, $statusCode, $httpHeader); } catch (ApiException $e) { - switch ($e->getCode()) { + switch ($e->getCode()) { } - + throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index b28f2f26140..6370b9be7a5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -55,18 +55,21 @@ class ApiClient /** * Configuration + * * @var Configuration */ protected $config; /** * Object Serializer + * * @var ObjectSerializer */ protected $serializer; /** * Constructor of the class + * * @param Configuration $config config for this ApiClient */ public function __construct(\Swagger\Client\Configuration $config = null) @@ -81,6 +84,7 @@ class ApiClient /** * Get the config + * * @return Configuration */ public function getConfig() @@ -90,6 +94,7 @@ class ApiClient /** * Get the serializer + * * @return ObjectSerializer */ public function getSerializer() @@ -99,7 +104,9 @@ class ApiClient /** * Get API key (with prefix if set) + * * @param string $apiKeyIdentifier name of apikey + * * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKeyIdentifier) @@ -122,12 +129,14 @@ class ApiClient /** * Make the HTTP call (Sync) + * * @param string $resourcePath path to method endpoint * @param string $method method to call * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header * @param string $responseType expected response type of the endpoint + * * @throws \Swagger\Client\ApiException on a non 2xx response * @return mixed */ @@ -160,7 +169,7 @@ class ApiClient if ($this->config->getCurlTimeout() != 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } - // return the result on success, rather than just true + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); @@ -171,7 +180,7 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } - if (! empty($queryParams)) { + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } @@ -216,7 +225,7 @@ class ApiClient // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = $this->http_parse_headers(substr($response, 0, $http_header_size)); + $http_header = $this->httpParseHeaders(substr($response, 0, $http_header_size)); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); @@ -228,7 +237,7 @@ class ApiClient // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file if ($responseType == '\SplFileObject' || $responseType == 'string') { return array($http_body, $response_info['http_code'], $http_header); @@ -246,7 +255,9 @@ class ApiClient throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $data + $response_info['http_code'], + $http_header, + $data ); } return array($data, $response_info['http_code'], $http_header); @@ -295,40 +306,35 @@ class ApiClient * * @return string[] Array of HTTP response heaers */ - protected function http_parse_headers($raw_headers) + protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 $headers = array(); $key = ''; - - foreach(explode("\n", $raw_headers) as $h) - { + + foreach (explode("\n", $raw_headers) as $h) { $h = explode(':', $h, 2); - - if (isset($h[1])) - { - if (!isset($headers[$h[0]])) + + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); - elseif (is_array($headers[$h[0]])) - { + } elseif (is_array($headers[$h[0]])) { $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); - } - else - { + } else { $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); } - + $key = $h[0]; - } - else - { - if (substr($h[0], 0, 1) == "\t") - $headers[$key] .= "\r\n\t".trim($h[0]); - elseif (!$key) - $headers[0] = trim($h[0]);trim($h[0]); + } else { + if (substr($h[0], 0, 1) == "\t") { + $headers[$key] .= "\r\n\t".trim($h[0]); + } elseif (!$key) { + $headers[0] = trim($h[0]); + } + trim($h[0]); } } - + return $headers; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index d6040a0ff20..94421bac149 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -48,30 +48,34 @@ class ApiException extends Exception /** * The HTTP body of the server response either as Json or string. + * * @var mixed */ protected $responseBody; /** * The HTTP header of the server response. + * * @var string[] */ protected $responseHeaders; /** * The deserialized response object + * * @var $responseObject; */ protected $responseObject; /** * Constructor + * * @param string $message Error message * @param int $code HTTP status code * @param string $responseHeaders HTTP response header * @param mixed $responseBody HTTP body of the server response either as Json or string */ - public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) + public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null) { parent::__construct($message, $code); $this->responseHeaders = $responseHeaders; @@ -100,7 +104,9 @@ class ApiException extends Exception /** * Sets the deseralized response object (during deserialization) + * * @param mixed $obj Deserialized response object + * * @return void */ public function setResponseObject($obj) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 9da9c7edac0..33bf0e93651 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -47,7 +47,7 @@ namespace Swagger\Client; class Configuration { - private static $_defaultConfiguration = null; + private static $defaultConfiguration = null; /** * Associate array to store API key(s) @@ -110,7 +110,7 @@ class Configuration * * @var string */ - protected $userAgent = "Swagger-Codegen/1.0.0/php"; + protected $userAgent = "Swagger-Codegen//php"; /** * Debug switch (default set to false) @@ -487,11 +487,11 @@ class Configuration */ public static function getDefaultConfiguration() { - if (self::$_defaultConfiguration == null) { - self::$_defaultConfiguration = new Configuration(); + if (self::$defaultConfiguration == null) { + self::$defaultConfiguration = new Configuration(); } - return self::$_defaultConfiguration; + return self::$defaultConfiguration; } /** @@ -503,7 +503,7 @@ class Configuration */ public static function setDefaultConfiguration(Configuration $config) { - self::$_defaultConfiguration = $config; + self::$defaultConfiguration = $config; } /** @@ -517,10 +517,9 @@ class Configuration $report .= " OS: ".php_uname()."\n"; $report .= " PHP Version: ".phpversion()."\n"; $report .= " OpenAPI Spec Version: 1.0.0\n"; - $report .= " SDK Package Version: 1.0.0\n"; + $report .= " SDK Package Version: \n"; $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; return $report; } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 9120535bf5a..6b05974a644 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Animal Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,31 +50,33 @@ class Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Animal'; + protected static $swaggerModelName = 'Animal'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'class_name' => 'string', 'color' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'class_name' => 'className', 'color' => 'color' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +84,13 @@ class Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'class_name' => 'setClassName', 'color' => 'setColor' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +98,13 @@ class Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'class_name' => 'getClassName', 'color' => 'getColor' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -131,14 +134,14 @@ class Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); if ($this->container['class_name'] === null) { - $invalid_properties[] = "'$class_name' can't be null"; + $invalid_properties[] = "'class_name' can't be null"; } return $invalid_properties; } @@ -146,8 +149,8 @@ class Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -169,7 +172,7 @@ class Animal implements ArrayAccess /** * Sets class_name - * @param string $class_name + * @param string $class_name * @return $this */ public function setClassName($class_name) @@ -190,7 +193,7 @@ class Animal implements ArrayAccess /** * Sets color - * @param string $color + * @param string $color * @return $this */ public function setColor($color) @@ -201,7 +204,7 @@ class Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -211,17 +214,17 @@ class Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -233,17 +236,17 @@ class Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index 2ff9da6a4ea..a699455bcf9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -39,7 +39,6 @@ use \ArrayAccess; * AnimalFarm Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +50,31 @@ class AnimalFarm implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'AnimalFarm'; + protected static $swaggerModelName = 'AnimalFarm'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +82,12 @@ class AnimalFarm implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +95,12 @@ class AnimalFarm implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -121,10 +124,10 @@ class AnimalFarm implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -133,8 +136,8 @@ class AnimalFarm implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -143,7 +146,7 @@ class AnimalFarm implements ArrayAccess /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -153,17 +156,17 @@ class AnimalFarm implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -175,17 +178,17 @@ class AnimalFarm implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index 8894f835aea..53ced7e8810 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -39,7 +39,6 @@ use \ArrayAccess; * ApiResponse Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,33 +50,35 @@ class ApiResponse implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'ApiResponse'; + protected static $swaggerModelName = 'ApiResponse'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'code' => 'int', 'type' => 'string', 'message' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'code' => 'code', 'type' => 'type', 'message' => 'message' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -85,13 +86,14 @@ class ApiResponse implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'code' => 'setCode', 'type' => 'setType', 'message' => 'setMessage' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -99,13 +101,14 @@ class ApiResponse implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'code' => 'getCode', 'type' => 'getType', 'message' => 'getMessage' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -132,10 +135,10 @@ class ApiResponse implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -144,8 +147,8 @@ class ApiResponse implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -164,7 +167,7 @@ class ApiResponse implements ArrayAccess /** * Sets code - * @param int $code + * @param int $code * @return $this */ public function setCode($code) @@ -185,7 +188,7 @@ class ApiResponse implements ArrayAccess /** * Sets type - * @param string $type + * @param string $type * @return $this */ public function setType($type) @@ -206,7 +209,7 @@ class ApiResponse implements ArrayAccess /** * Sets message - * @param string $message + * @param string $message * @return $this */ public function setMessage($message) @@ -217,7 +220,7 @@ class ApiResponse implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -227,17 +230,17 @@ class ApiResponse implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -249,17 +252,17 @@ class ApiResponse implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 393f89e5b0f..9eb4de596d8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Cat Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +50,31 @@ class Cat extends Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Cat'; + protected static $swaggerModelName = 'Cat'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'declawed' => 'bool' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes + parent::swaggerTypes(); } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'declawed' => 'declawed' ); - static function attributeMap() { + public static function attributeMap() + { return parent::attributeMap() + self::$attributeMap; } @@ -81,11 +82,12 @@ class Cat extends Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'declawed' => 'setDeclawed' ); - static function setters() { + public static function setters() + { return parent::setters() + self::$setters; } @@ -93,11 +95,12 @@ class Cat extends Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'declawed' => 'getDeclawed' ); - - static function getters() { + + public static function getters() + { return parent::getters() + self::$getters; } @@ -124,10 +127,10 @@ class Cat extends Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -136,8 +139,8 @@ class Cat extends Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -156,7 +159,7 @@ class Cat extends Animal implements ArrayAccess /** * Sets declawed - * @param bool $declawed + * @param bool $declawed * @return $this */ public function setDeclawed($declawed) @@ -167,7 +170,7 @@ class Cat extends Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -177,17 +180,17 @@ class Cat extends Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -199,17 +202,17 @@ class Cat extends Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 1c1a2340378..8e3c5e6fb5e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Category Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,31 +50,33 @@ class Category implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Category'; + protected static $swaggerModelName = 'Category'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'name' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +84,13 @@ class Category implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +98,13 @@ class Category implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'name' => 'getName' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -127,10 +130,10 @@ class Category implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -139,8 +142,8 @@ class Category implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -159,7 +162,7 @@ class Category implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -180,7 +183,7 @@ class Category implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) @@ -191,7 +194,7 @@ class Category implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -201,17 +204,17 @@ class Category implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -223,17 +226,17 @@ class Category implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index b79e76a4187..9212a8c5d3b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Dog Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +50,31 @@ class Dog extends Animal implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Dog'; + protected static $swaggerModelName = 'Dog'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'breed' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes + parent::swaggerTypes(); } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'breed' => 'breed' ); - static function attributeMap() { + public static function attributeMap() + { return parent::attributeMap() + self::$attributeMap; } @@ -81,11 +82,12 @@ class Dog extends Animal implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'breed' => 'setBreed' ); - static function setters() { + public static function setters() + { return parent::setters() + self::$setters; } @@ -93,11 +95,12 @@ class Dog extends Animal implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'breed' => 'getBreed' ); - - static function getters() { + + public static function getters() + { return parent::getters() + self::$getters; } @@ -124,10 +127,10 @@ class Dog extends Animal implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -136,8 +139,8 @@ class Dog extends Animal implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -156,7 +159,7 @@ class Dog extends Animal implements ArrayAccess /** * Sets breed - * @param string $breed + * @param string $breed * @return $this */ public function setBreed($breed) @@ -167,7 +170,7 @@ class Dog extends Animal implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -177,17 +180,17 @@ class Dog extends Animal implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -199,17 +202,17 @@ class Dog extends Animal implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php index 2b6d36c9b66..71fb3357d14 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -39,7 +39,6 @@ use \ArrayAccess; * EnumClass Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +50,31 @@ class EnumClass implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'EnumClass'; + protected static $swaggerModelName = 'EnumClass'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +82,12 @@ class EnumClass implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +95,12 @@ class EnumClass implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -121,10 +124,10 @@ class EnumClass implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -133,8 +136,8 @@ class EnumClass implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -143,7 +146,7 @@ class EnumClass implements ArrayAccess /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -153,17 +156,17 @@ class EnumClass implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -175,17 +178,17 @@ class EnumClass implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index 6e10f45dd8f..77751f9c43f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -39,7 +39,6 @@ use \ArrayAccess; * EnumTest Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,33 +50,35 @@ class EnumTest implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Enum_Test'; + protected static $swaggerModelName = 'Enum_Test'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'enum_string' => 'string', 'enum_integer' => 'int', 'enum_number' => 'double' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'enum_string' => 'enum_string', 'enum_integer' => 'enum_integer', 'enum_number' => 'enum_number' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -85,13 +86,14 @@ class EnumTest implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'enum_string' => 'setEnumString', 'enum_integer' => 'setEnumInteger', 'enum_number' => 'setEnumNumber' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -99,13 +101,14 @@ class EnumTest implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'enum_string' => 'getEnumString', 'enum_integer' => 'getEnumInteger', 'enum_number' => 'getEnumNumber' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -122,7 +125,8 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumStringAllowableValues() { + public function getEnumStringAllowableValues() + { return [ self::ENUM_STRING_UPPER, self::ENUM_STRING_LOWER, @@ -133,7 +137,8 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumIntegerAllowableValues() { + public function getEnumIntegerAllowableValues() + { return [ self::ENUM_INTEGER_1, self::ENUM_INTEGER_MINUS_1, @@ -144,7 +149,8 @@ class EnumTest implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getEnumNumberAllowableValues() { + public function getEnumNumberAllowableValues() + { return [ self::ENUM_NUMBER_1_DOT_1, self::ENUM_NUMBER_MINUS_1_DOT_2, @@ -171,23 +177,23 @@ class EnumTest implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); $allowed_values = array("UPPER", "lower"); if (!in_array($this->container['enum_string'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_string', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_string', must be one of #{allowed_values}."; } $allowed_values = array("1", "-1"); if (!in_array($this->container['enum_integer'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_integer', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_integer', must be one of #{allowed_values}."; } $allowed_values = array("1.1", "-1.2"); if (!in_array($this->container['enum_number'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$enum_number', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_number', must be one of #{allowed_values}."; } return $invalid_properties; } @@ -195,8 +201,8 @@ class EnumTest implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -227,7 +233,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_string - * @param string $enum_string + * @param string $enum_string * @return $this */ public function setEnumString($enum_string) @@ -252,7 +258,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_integer - * @param int $enum_integer + * @param int $enum_integer * @return $this */ public function setEnumInteger($enum_integer) @@ -277,7 +283,7 @@ class EnumTest implements ArrayAccess /** * Sets enum_number - * @param double $enum_number + * @param double $enum_number * @return $this */ public function setEnumNumber($enum_number) @@ -292,7 +298,7 @@ class EnumTest implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -302,17 +308,17 @@ class EnumTest implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -324,17 +330,17 @@ class EnumTest implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index bf674b05102..07148e70189 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -39,7 +39,6 @@ use \ArrayAccess; * FormatTest Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +50,13 @@ class FormatTest implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'format_test'; + protected static $swaggerModelName = 'format_test'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'integer' => 'int', 'int32' => 'int', 'int64' => 'int', @@ -73,15 +72,16 @@ class FormatTest implements ArrayAccess 'password' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'integer' => 'integer', 'int32' => 'int32', 'int64' => 'int64', @@ -97,7 +97,8 @@ class FormatTest implements ArrayAccess 'password' => 'password' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -105,7 +106,7 @@ class FormatTest implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'integer' => 'setInteger', 'int32' => 'setInt32', 'int64' => 'setInt64', @@ -121,7 +122,8 @@ class FormatTest implements ArrayAccess 'password' => 'setPassword' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -129,7 +131,7 @@ class FormatTest implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'integer' => 'getInteger', 'int32' => 'getInt32', 'int64' => 'getInt64', @@ -144,8 +146,9 @@ class FormatTest implements ArrayAccess 'uuid' => 'getUuid', 'password' => 'getPassword' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -182,62 +185,62 @@ class FormatTest implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); if ($this->container['integer'] > 100.0) { - $invalid_properties[] = "invalid value for '$integer', must be smaller than or equal to 100.0."; + $invalid_properties[] = "invalid value for 'integer', must be smaller than or equal to 100.0."; } if ($this->container['integer'] < 10.0) { - $invalid_properties[] = "invalid value for '$integer', must be bigger than or equal to 10.0."; + $invalid_properties[] = "invalid value for 'integer', must be bigger than or equal to 10.0."; } if ($this->container['int32'] > 200.0) { - $invalid_properties[] = "invalid value for '$int32', must be smaller than or equal to 200.0."; + $invalid_properties[] = "invalid value for 'int32', must be smaller than or equal to 200.0."; } if ($this->container['int32'] < 20.0) { - $invalid_properties[] = "invalid value for '$int32', must be bigger than or equal to 20.0."; + $invalid_properties[] = "invalid value for 'int32', must be bigger than or equal to 20.0."; } if ($this->container['number'] === null) { - $invalid_properties[] = "'$number' can't be null"; + $invalid_properties[] = "'number' can't be null"; } if ($this->container['number'] > 543.2) { - $invalid_properties[] = "invalid value for '$number', must be smaller than or equal to 543.2."; + $invalid_properties[] = "invalid value for 'number', must be smaller than or equal to 543.2."; } if ($this->container['number'] < 32.1) { - $invalid_properties[] = "invalid value for '$number', must be bigger than or equal to 32.1."; + $invalid_properties[] = "invalid value for 'number', must be bigger than or equal to 32.1."; } if ($this->container['float'] > 987.6) { - $invalid_properties[] = "invalid value for '$float', must be smaller than or equal to 987.6."; + $invalid_properties[] = "invalid value for 'float', must be smaller than or equal to 987.6."; } if ($this->container['float'] < 54.3) { - $invalid_properties[] = "invalid value for '$float', must be bigger than or equal to 54.3."; + $invalid_properties[] = "invalid value for 'float', must be bigger than or equal to 54.3."; } if ($this->container['double'] > 123.4) { - $invalid_properties[] = "invalid value for '$double', must be smaller than or equal to 123.4."; + $invalid_properties[] = "invalid value for 'double', must be smaller than or equal to 123.4."; } if ($this->container['double'] < 67.8) { - $invalid_properties[] = "invalid value for '$double', must be bigger than or equal to 67.8."; + $invalid_properties[] = "invalid value for 'double', must be bigger than or equal to 67.8."; } if (!preg_match("/[a-z]/i", $this->container['string'])) { - $invalid_properties[] = "invalid value for '$string', must be conform to the pattern /[a-z]/i."; + $invalid_properties[] = "invalid value for 'string', must be conform to the pattern /[a-z]/i."; } if ($this->container['byte'] === null) { - $invalid_properties[] = "'$byte' can't be null"; + $invalid_properties[] = "'byte' can't be null"; } if ($this->container['date'] === null) { - $invalid_properties[] = "'$date' can't be null"; + $invalid_properties[] = "'date' can't be null"; } if ($this->container['password'] === null) { - $invalid_properties[] = "'$password' can't be null"; + $invalid_properties[] = "'password' can't be null"; } if (strlen($this->container['password']) > 64) { - $invalid_properties[] = "invalid value for '$password', the character length must be smaller than or equal to 64."; + $invalid_properties[] = "invalid value for 'password', the character length must be smaller than or equal to 64."; } if (strlen($this->container['password']) < 10) { - $invalid_properties[] = "invalid value for '$password', the character length must be bigger than or equal to 10."; + $invalid_properties[] = "invalid value for 'password', the character length must be bigger than or equal to 10."; } return $invalid_properties; } @@ -245,8 +248,8 @@ class FormatTest implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -316,7 +319,7 @@ class FormatTest implements ArrayAccess /** * Sets integer - * @param int $integer + * @param int $integer * @return $this */ public function setInteger($integer) @@ -344,7 +347,7 @@ class FormatTest implements ArrayAccess /** * Sets int32 - * @param int $int32 + * @param int $int32 * @return $this */ public function setInt32($int32) @@ -372,7 +375,7 @@ class FormatTest implements ArrayAccess /** * Sets int64 - * @param int $int64 + * @param int $int64 * @return $this */ public function setInt64($int64) @@ -393,7 +396,7 @@ class FormatTest implements ArrayAccess /** * Sets number - * @param float $number + * @param float $number * @return $this */ public function setNumber($number) @@ -421,7 +424,7 @@ class FormatTest implements ArrayAccess /** * Sets float - * @param float $float + * @param float $float * @return $this */ public function setFloat($float) @@ -449,7 +452,7 @@ class FormatTest implements ArrayAccess /** * Sets double - * @param double $double + * @param double $double * @return $this */ public function setDouble($double) @@ -477,7 +480,7 @@ class FormatTest implements ArrayAccess /** * Sets string - * @param string $string + * @param string $string * @return $this */ public function setString($string) @@ -502,7 +505,7 @@ class FormatTest implements ArrayAccess /** * Sets byte - * @param string $byte + * @param string $byte * @return $this */ public function setByte($byte) @@ -523,7 +526,7 @@ class FormatTest implements ArrayAccess /** * Sets binary - * @param string $binary + * @param string $binary * @return $this */ public function setBinary($binary) @@ -544,7 +547,7 @@ class FormatTest implements ArrayAccess /** * Sets date - * @param \DateTime $date + * @param \DateTime $date * @return $this */ public function setDate($date) @@ -565,7 +568,7 @@ class FormatTest implements ArrayAccess /** * Sets date_time - * @param \DateTime $date_time + * @param \DateTime $date_time * @return $this */ public function setDateTime($date_time) @@ -586,7 +589,7 @@ class FormatTest implements ArrayAccess /** * Sets uuid - * @param string $uuid + * @param string $uuid * @return $this */ public function setUuid($uuid) @@ -607,7 +610,7 @@ class FormatTest implements ArrayAccess /** * Sets password - * @param string $password + * @param string $password * @return $this */ public function setPassword($password) @@ -624,7 +627,7 @@ class FormatTest implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -634,17 +637,17 @@ class FormatTest implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -656,17 +659,17 @@ class FormatTest implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 68eae680dc6..88a28981f29 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -51,29 +51,31 @@ class Model200Response implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = '200_response'; + protected static $swaggerModelName = '200_response'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'name' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +83,12 @@ class Model200Response implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +96,12 @@ class Model200Response implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'name' => 'getName' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -122,10 +126,10 @@ class Model200Response implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -134,8 +138,8 @@ class Model200Response implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -154,7 +158,7 @@ class Model200Response implements ArrayAccess /** * Sets name - * @param int $name + * @param int $name * @return $this */ public function setName($name) @@ -165,7 +169,7 @@ class Model200Response implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +179,17 @@ class Model200Response implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +201,17 @@ class Model200Response implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 7dce6f0029d..d1b188ff231 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -51,29 +51,31 @@ class ModelReturn implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Return'; + protected static $swaggerModelName = 'Return'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'return' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'return' => 'return' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +83,12 @@ class ModelReturn implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'return' => 'setReturn' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +96,12 @@ class ModelReturn implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'return' => 'getReturn' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -122,10 +126,10 @@ class ModelReturn implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -134,8 +138,8 @@ class ModelReturn implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -154,7 +158,7 @@ class ModelReturn implements ArrayAccess /** * Sets return - * @param int $return + * @param int $return * @return $this */ public function setReturn($return) @@ -165,7 +169,7 @@ class ModelReturn implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +179,17 @@ class ModelReturn implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +201,17 @@ class ModelReturn implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index b77f3d78d0c..294d45dffe3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -51,35 +51,37 @@ class Name implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Name'; + protected static $swaggerModelName = 'Name'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'name' => 'int', 'snake_case' => 'int', 'property' => 'string', '_123_number' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'name' => 'name', 'snake_case' => 'snake_case', 'property' => 'property', '_123_number' => '123Number' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -87,14 +89,15 @@ class Name implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'name' => 'setName', 'snake_case' => 'setSnakeCase', 'property' => 'setProperty', '_123_number' => 'set123Number' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -102,14 +105,15 @@ class Name implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'name' => 'getName', 'snake_case' => 'getSnakeCase', 'property' => 'getProperty', '_123_number' => 'get123Number' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -137,14 +141,14 @@ class Name implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); if ($this->container['name'] === null) { - $invalid_properties[] = "'$name' can't be null"; + $invalid_properties[] = "'name' can't be null"; } return $invalid_properties; } @@ -152,8 +156,8 @@ class Name implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -175,7 +179,7 @@ class Name implements ArrayAccess /** * Sets name - * @param int $name + * @param int $name * @return $this */ public function setName($name) @@ -196,7 +200,7 @@ class Name implements ArrayAccess /** * Sets snake_case - * @param int $snake_case + * @param int $snake_case * @return $this */ public function setSnakeCase($snake_case) @@ -217,7 +221,7 @@ class Name implements ArrayAccess /** * Sets property - * @param string $property + * @param string $property * @return $this */ public function setProperty($property) @@ -238,7 +242,7 @@ class Name implements ArrayAccess /** * Sets _123_number - * @param int $_123_number + * @param int $_123_number * @return $this */ public function set123Number($_123_number) @@ -249,7 +253,7 @@ class Name implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -259,17 +263,17 @@ class Name implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -281,17 +285,17 @@ class Name implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 88779ed8c73..3bd377eae71 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Order Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +50,13 @@ class Order implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Order'; + protected static $swaggerModelName = 'Order'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'pet_id' => 'int', 'quantity' => 'int', @@ -66,15 +65,16 @@ class Order implements ArrayAccess 'complete' => 'bool' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'pet_id' => 'petId', 'quantity' => 'quantity', @@ -83,7 +83,8 @@ class Order implements ArrayAccess 'complete' => 'complete' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -91,7 +92,7 @@ class Order implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'pet_id' => 'setPetId', 'quantity' => 'setQuantity', @@ -100,7 +101,8 @@ class Order implements ArrayAccess 'complete' => 'setComplete' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -108,7 +110,7 @@ class Order implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'pet_id' => 'getPetId', 'quantity' => 'getQuantity', @@ -116,8 +118,9 @@ class Order implements ArrayAccess 'status' => 'getStatus', 'complete' => 'getComplete' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -131,7 +134,8 @@ class Order implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getStatusAllowableValues() { + public function getStatusAllowableValues() + { return [ self::STATUS_PLACED, self::STATUS_APPROVED, @@ -162,15 +166,15 @@ class Order implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); $allowed_values = array("placed", "approved", "delivered"); if (!in_array($this->container['status'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$status', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; } return $invalid_properties; } @@ -178,8 +182,8 @@ class Order implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -202,7 +206,7 @@ class Order implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -223,7 +227,7 @@ class Order implements ArrayAccess /** * Sets pet_id - * @param int $pet_id + * @param int $pet_id * @return $this */ public function setPetId($pet_id) @@ -244,7 +248,7 @@ class Order implements ArrayAccess /** * Sets quantity - * @param int $quantity + * @param int $quantity * @return $this */ public function setQuantity($quantity) @@ -265,7 +269,7 @@ class Order implements ArrayAccess /** * Sets ship_date - * @param \DateTime $ship_date + * @param \DateTime $ship_date * @return $this */ public function setShipDate($ship_date) @@ -311,7 +315,7 @@ class Order implements ArrayAccess /** * Sets complete - * @param bool $complete + * @param bool $complete * @return $this */ public function setComplete($complete) @@ -322,7 +326,7 @@ class Order implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -332,17 +336,17 @@ class Order implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -354,17 +358,17 @@ class Order implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 5a65e432538..378c979629c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Pet Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +50,13 @@ class Pet implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Pet'; + protected static $swaggerModelName = 'Pet'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'category' => '\Swagger\Client\Model\Category', 'name' => 'string', @@ -66,15 +65,16 @@ class Pet implements ArrayAccess 'status' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'category' => 'category', 'name' => 'name', @@ -83,7 +83,8 @@ class Pet implements ArrayAccess 'status' => 'status' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -91,7 +92,7 @@ class Pet implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'category' => 'setCategory', 'name' => 'setName', @@ -100,7 +101,8 @@ class Pet implements ArrayAccess 'status' => 'setStatus' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -108,7 +110,7 @@ class Pet implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'category' => 'getCategory', 'name' => 'getName', @@ -116,8 +118,9 @@ class Pet implements ArrayAccess 'tags' => 'getTags', 'status' => 'getStatus' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -131,7 +134,8 @@ class Pet implements ArrayAccess * Gets allowable values of the enum * @return string[] */ - public function getStatusAllowableValues() { + public function getStatusAllowableValues() + { return [ self::STATUS_AVAILABLE, self::STATUS_PENDING, @@ -162,21 +166,21 @@ class Pet implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); if ($this->container['name'] === null) { - $invalid_properties[] = "'$name' can't be null"; + $invalid_properties[] = "'name' can't be null"; } if ($this->container['photo_urls'] === null) { - $invalid_properties[] = "'$photo_urls' can't be null"; + $invalid_properties[] = "'photo_urls' can't be null"; } $allowed_values = array("available", "pending", "sold"); if (!in_array($this->container['status'], $allowed_values)) { - $invalid_properties[] = "invalid value for '$status', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; } return $invalid_properties; } @@ -184,8 +188,8 @@ class Pet implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -214,7 +218,7 @@ class Pet implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -235,7 +239,7 @@ class Pet implements ArrayAccess /** * Sets category - * @param \Swagger\Client\Model\Category $category + * @param \Swagger\Client\Model\Category $category * @return $this */ public function setCategory($category) @@ -256,7 +260,7 @@ class Pet implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) @@ -277,7 +281,7 @@ class Pet implements ArrayAccess /** * Sets photo_urls - * @param string[] $photo_urls + * @param string[] $photo_urls * @return $this */ public function setPhotoUrls($photo_urls) @@ -298,7 +302,7 @@ class Pet implements ArrayAccess /** * Sets tags - * @param \Swagger\Client\Model\Tag[] $tags + * @param \Swagger\Client\Model\Tag[] $tags * @return $this */ public function setTags($tags) @@ -334,7 +338,7 @@ class Pet implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -344,17 +348,17 @@ class Pet implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -366,17 +370,17 @@ class Pet implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index 25ebecd55a0..025ee4b7b3b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -39,7 +39,6 @@ use \ArrayAccess; * SpecialModelName Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,29 +50,31 @@ class SpecialModelName implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = '$special[model.name]'; + protected static $swaggerModelName = '$special[model.name]'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'special_property_name' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'special_property_name' => '$special[property.name]' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -81,11 +82,12 @@ class SpecialModelName implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'special_property_name' => 'setSpecialPropertyName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -93,11 +95,12 @@ class SpecialModelName implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'special_property_name' => 'getSpecialPropertyName' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -122,10 +125,10 @@ class SpecialModelName implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -134,8 +137,8 @@ class SpecialModelName implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -154,7 +157,7 @@ class SpecialModelName implements ArrayAccess /** * Sets special_property_name - * @param int $special_property_name + * @param int $special_property_name * @return $this */ public function setSpecialPropertyName($special_property_name) @@ -165,7 +168,7 @@ class SpecialModelName implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -175,17 +178,17 @@ class SpecialModelName implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -197,17 +200,17 @@ class SpecialModelName implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index a2132ca7e5c..8fba6e43dd8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -39,7 +39,6 @@ use \ArrayAccess; * Tag Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,31 +50,33 @@ class Tag implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'Tag'; + protected static $swaggerModelName = 'Tag'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'name' => 'string' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'name' => 'name' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -83,12 +84,13 @@ class Tag implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'name' => 'setName' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -96,12 +98,13 @@ class Tag implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'name' => 'getName' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -127,10 +130,10 @@ class Tag implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -139,8 +142,8 @@ class Tag implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -159,7 +162,7 @@ class Tag implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -180,7 +183,7 @@ class Tag implements ArrayAccess /** * Sets name - * @param string $name + * @param string $name * @return $this */ public function setName($name) @@ -191,7 +194,7 @@ class Tag implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -201,17 +204,17 @@ class Tag implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -223,17 +226,17 @@ class Tag implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index a97727f0a8f..04b4f749437 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -39,7 +39,6 @@ use \ArrayAccess; * User Class Doc Comment * * @category Class - * @description * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -51,13 +50,13 @@ class User implements ArrayAccess * The original name of the model. * @var string */ - static $swaggerModelName = 'User'; + protected static $swaggerModelName = 'User'; /** - * Array of property to type mappings. Used for (de)serialization + * Array of property to type mappings. Used for (de)serialization * @var string[] */ - static $swaggerTypes = array( + protected static $swaggerTypes = array( 'id' => 'int', 'username' => 'string', 'first_name' => 'string', @@ -68,15 +67,16 @@ class User implements ArrayAccess 'user_status' => 'int' ); - static function swaggerTypes() { + public static function swaggerTypes() + { return self::$swaggerTypes; } - /** + /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - static $attributeMap = array( + protected static $attributeMap = array( 'id' => 'id', 'username' => 'username', 'first_name' => 'firstName', @@ -87,7 +87,8 @@ class User implements ArrayAccess 'user_status' => 'userStatus' ); - static function attributeMap() { + public static function attributeMap() + { return self::$attributeMap; } @@ -95,7 +96,7 @@ class User implements ArrayAccess * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ - static $setters = array( + protected static $setters = array( 'id' => 'setId', 'username' => 'setUsername', 'first_name' => 'setFirstName', @@ -106,7 +107,8 @@ class User implements ArrayAccess 'user_status' => 'setUserStatus' ); - static function setters() { + public static function setters() + { return self::$setters; } @@ -114,7 +116,7 @@ class User implements ArrayAccess * Array of attributes to getter functions (for serialization of requests) * @var string[] */ - static $getters = array( + protected static $getters = array( 'id' => 'getId', 'username' => 'getUsername', 'first_name' => 'getFirstName', @@ -124,8 +126,9 @@ class User implements ArrayAccess 'phone' => 'getPhone', 'user_status' => 'getUserStatus' ); - - static function getters() { + + public static function getters() + { return self::$getters; } @@ -157,10 +160,10 @@ class User implements ArrayAccess /** * show all the invalid properties with reasons. - * + * * @return array invalid properties with reasons */ - public function list_invalid_properties() + public function listInvalidProperties() { $invalid_properties = array(); return $invalid_properties; @@ -169,8 +172,8 @@ class User implements ArrayAccess /** * validate all the properties in the model * return true if all passed - * - * @return bool True if all properteis are valid + * + * @return bool True if all properteis are valid */ public function valid() { @@ -189,7 +192,7 @@ class User implements ArrayAccess /** * Sets id - * @param int $id + * @param int $id * @return $this */ public function setId($id) @@ -210,7 +213,7 @@ class User implements ArrayAccess /** * Sets username - * @param string $username + * @param string $username * @return $this */ public function setUsername($username) @@ -231,7 +234,7 @@ class User implements ArrayAccess /** * Sets first_name - * @param string $first_name + * @param string $first_name * @return $this */ public function setFirstName($first_name) @@ -252,7 +255,7 @@ class User implements ArrayAccess /** * Sets last_name - * @param string $last_name + * @param string $last_name * @return $this */ public function setLastName($last_name) @@ -273,7 +276,7 @@ class User implements ArrayAccess /** * Sets email - * @param string $email + * @param string $email * @return $this */ public function setEmail($email) @@ -294,7 +297,7 @@ class User implements ArrayAccess /** * Sets password - * @param string $password + * @param string $password * @return $this */ public function setPassword($password) @@ -315,7 +318,7 @@ class User implements ArrayAccess /** * Sets phone - * @param string $phone + * @param string $phone * @return $this */ public function setPhone($phone) @@ -347,7 +350,7 @@ class User implements ArrayAccess } /** * Returns true if offset exists. False otherwise. - * @param integer $offset Offset + * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) @@ -357,17 +360,17 @@ class User implements ArrayAccess /** * Gets offset. - * @param integer $offset Offset - * @return mixed + * @param integer $offset Offset + * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } - + /** * Sets value based on offset. - * @param integer $offset Offset + * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ @@ -379,17 +382,17 @@ class User implements ArrayAccess $this->container[$offset] = $value; } } - + /** * Unsets offset. - * @param integer $offset Offset + * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } - + /** * Gets the string presentation of the object * @return string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 3adaa899f5f..6d656ac2b97 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -1,6 +1,6 @@ getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - return $deserialized; + if (Configuration::getDefaultConfiguration()->getDebug()) { + error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + } + + return $deserialized; } else { // If a discriminator is defined and points to a valid subclass, use it. if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { @@ -282,11 +286,11 @@ class ObjectSerializer $instance = new $class(); foreach ($instance::swaggerTypes() as $property => $type) { $propertySetter = $instance::setters()[$property]; - + if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { continue; } - + $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); diff --git a/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml b/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml new file mode 100644 index 00000000000..a0173077aa9 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/phpcs-generated-code.xml @@ -0,0 +1,10 @@ + + + + Arnes Drupal code checker + + + + * + + diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php index dc599fbe5d7..7736ffd67a7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/FakeApiTest.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,24 +53,27 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test case for testEndpointParameters * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 . * */ - public function test_testEndpointParameters() { + public function testTestEndpointParameters() + { } } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php index af6b1018332..73a7b06b5eb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,87 +53,97 @@ class PetApiTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test case for addPet * - * Add a new pet to the store + * Add a new pet to the store. * */ - public function test_addPet() { + public function testAddPet() + { } /** * Test case for deletePet * - * Deletes a pet + * Deletes a pet. * */ - public function test_deletePet() { + public function testDeletePet() + { } /** * Test case for findPetsByStatus * - * Finds Pets by status + * Finds Pets by status. * */ - public function test_findPetsByStatus() { + public function testFindPetsByStatus() + { } /** * Test case for findPetsByTags * - * Finds Pets by tags + * Finds Pets by tags. * */ - public function test_findPetsByTags() { + public function testFindPetsByTags() + { } /** * Test case for getPetById * - * Find pet by ID + * Find pet by ID. * */ - public function test_getPetById() { + public function testGetPetById() + { } /** * Test case for updatePet * - * Update an existing pet + * Update an existing pet. * */ - public function test_updatePet() { + public function testUpdatePet() + { } /** * Test case for updatePetWithForm * - * Updates a pet in the store with form data + * Updates a pet in the store with form data. * */ - public function test_updatePetWithForm() { + public function testUpdatePetWithForm() + { } /** * Test case for uploadFile * - * uploads an image + * uploads an image. * */ - public function test_uploadFile() { + public function testUploadFile() + { } } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php index 25fa53169f2..aaa2df27fd7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,51 +53,57 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test case for deleteOrder * - * Delete purchase order by ID + * Delete purchase order by ID. * */ - public function test_deleteOrder() { + public function testDeleteOrder() + { } /** * Test case for getInventory * - * Returns pet inventories by status + * Returns pet inventories by status. * */ - public function test_getInventory() { + public function testGetInventory() + { } /** * Test case for getOrderById * - * Find purchase order by ID + * Find purchase order by ID. * */ - public function test_getOrderById() { + public function testGetOrderById() + { } /** * Test case for placeOrder * - * Place an order for a pet + * Place an order for a pet. * */ - public function test_placeOrder() { + public function testPlaceOrder() + { } } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php index 5df577e6d9e..c866015cf7a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php @@ -26,8 +26,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the endpoint. */ @@ -53,87 +53,97 @@ class UserApiTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** * Test case for createUser * - * Create user + * Create user. * */ - public function test_createUser() { + public function testCreateUser() + { } /** * Test case for createUsersWithArrayInput * - * Creates list of users with given input array + * Creates list of users with given input array. * */ - public function test_createUsersWithArrayInput() { + public function testCreateUsersWithArrayInput() + { } /** * Test case for createUsersWithListInput * - * Creates list of users with given input array + * Creates list of users with given input array. * */ - public function test_createUsersWithListInput() { + public function testCreateUsersWithListInput() + { } /** * Test case for deleteUser * - * Delete user + * Delete user. * */ - public function test_deleteUser() { + public function testDeleteUser() + { } /** * Test case for getUserByName * - * Get user by user name + * Get user by user name. * */ - public function test_getUserByName() { + public function testGetUserByName() + { } /** * Test case for loginUser * - * Logs user into the system + * Logs user into the system. * */ - public function test_loginUser() { + public function testLoginUser() + { } /** * Test case for logoutUser * - * Logs out current logged in user session + * Logs out current logged in user session. * */ - public function test_logoutUser() { + public function testLogoutUser() + { } /** * Test case for updateUser * - * Updated user + * Updated user. * */ - public function test_updateUser() { + public function testUpdateUser() + { } } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php index f154716c064..0471346bf24 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalFarmTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * AnimalFarmTest Class Doc Comment * * @category Class - * @description + * @description AnimalFarm * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class AnimalFarmTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test AnimalFarm + * Test "AnimalFarm" */ - public function testAnimalFarm() { + public function testAnimalFarm() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php index f66fc54f211..4890e367f51 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/AnimalTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * AnimalTest Class Doc Comment * * @category Class - * @description + * @description Animal * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class AnimalTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Animal + * Test "Animal" */ - public function testAnimal() { + public function testAnimal() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php index 5cc18107499..8032f2d9149 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ApiResponseTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * ApiResponseTest Class Doc Comment * * @category Class - * @description + * @description ApiResponse * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class ApiResponseTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test ApiResponse + * Test "ApiResponse" */ - public function testApiResponse() { + public function testApiResponse() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php index c6fddff26eb..0d0a876c1a3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/CatTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * CatTest Class Doc Comment * * @category Class - * @description + * @description Cat * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class CatTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Cat + * Test "Cat" */ - public function testCat() { + public function testCat() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php index 26214963d3f..80394da3493 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/CategoryTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * CategoryTest Class Doc Comment * * @category Class - * @description + * @description Category * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class CategoryTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Category + * Test "Category" */ - public function testCategory() { + public function testCategory() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/DogTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/DogTest.php index 7bd00617167..fe47efdd26d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/DogTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/DogTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * DogTest Class Doc Comment * * @category Class - * @description + * @description Dog * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class DogTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Dog + * Test "Dog" */ - public function testDog() { + public function testDog() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumClassTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumClassTest.php index 4d901dfd1c9..3433afad97e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumClassTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumClassTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * EnumClassTest Class Doc Comment * * @category Class - * @description + * @description EnumClass * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class EnumClassTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test EnumClass + * Test "EnumClass" */ - public function testEnumClass() { + public function testEnumClass() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php index 653a5129739..ca6c82e10ac 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/EnumTestTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * EnumTestTest Class Doc Comment * * @category Class - * @description + * @description EnumTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class EnumTestTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test EnumTest + * Test "EnumTest" */ - public function testEnumTest() { + public function testEnumTest() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php index ca9f9a71849..57675f2eada 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/FormatTestTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * FormatTestTest Class Doc Comment * * @category Class - * @description + * @description FormatTest * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class FormatTestTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test FormatTest + * Test "FormatTest" */ - public function testFormatTest() { + public function testFormatTest() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/Model200ResponseTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/Model200ResponseTest.php index 40a5fe6d8b7..20d6e492686 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/Model200ResponseTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/Model200ResponseTest.php @@ -49,22 +49,24 @@ class Model200ResponseTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Model200Response + * Test "Model200Response" */ - public function testModel200Response() { + public function testModel200Response() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelReturnTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelReturnTest.php index 1f3424acf71..80e692dd61a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelReturnTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/ModelReturnTest.php @@ -49,22 +49,24 @@ class ModelReturnTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test ModelReturn + * Test "ModelReturn" */ - public function testModelReturn() { + public function testModelReturn() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/NameTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/NameTest.php index c33395f2085..81397cab0cd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/NameTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/NameTest.php @@ -49,22 +49,24 @@ class NameTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Name + * Test "Name" */ - public function testName() { + public function testName() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/OrderTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/OrderTest.php index abfbe53d48f..e42007659f9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/OrderTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/OrderTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * OrderTest Class Doc Comment * * @category Class - * @description + * @description Order * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class OrderTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Order + * Test "Order" */ - public function testOrder() { + public function testOrder() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/PetTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/PetTest.php index 571e17f56cb..2f2ac140ca1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/PetTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/PetTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * PetTest Class Doc Comment * * @category Class - * @description + * @description Pet * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class PetTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Pet + * Test "Pet" */ - public function testPet() { + public function testPet() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/SpecialModelNameTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/SpecialModelNameTest.php index 542ffa68a13..0b5eff62e3c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/SpecialModelNameTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/SpecialModelNameTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * SpecialModelNameTest Class Doc Comment * * @category Class - * @description + * @description SpecialModelName * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class SpecialModelNameTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test SpecialModelName + * Test "SpecialModelName" */ - public function testSpecialModelName() { + public function testSpecialModelName() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/TagTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/TagTest.php index 34536dc0d4c..7360c3f7bb5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/TagTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/TagTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * TagTest Class Doc Comment * * @category Class - * @description + * @description Tag * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class TagTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test Tag + * Test "Tag" */ - public function testTag() { + public function testTag() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/UserTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/UserTest.php index ffde69ecf2f..f6a6edc8208 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Model/UserTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/UserTest.php @@ -37,7 +37,7 @@ namespace Swagger\Client\Model; * UserTest Class Doc Comment * * @category Class - * @description + * @description User * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 @@ -49,22 +49,24 @@ class UserTest extends \PHPUnit_Framework_TestCase /** * Setup before running each test case */ - public static function setUpBeforeClass() { + public static function setUpBeforeClass() + { } /** * Clean up after running each test case */ - public static function tearDownAfterClass() { + public static function tearDownAfterClass() + { } /** - * Test User + * Test "User" */ - public function testUser() { + public function testUser() + { } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php index 14bbc0de913..ce147d0e9e2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php @@ -1,6 +1,6 @@ assertSame("sun.gif", $s->sanitizeFilename("sun.gif")); $this->assertSame("sun.gif", $s->sanitizeFilename("../sun.gif")); @@ -22,8 +22,4 @@ class ObjectSerializerTest extends \PHPUnit_Framework_TestCase $this->assertSame("sun.gif", $s->sanitizeFilename("c:\var\tmp\sun.gif")); $this->assertSame("sun.gif", $s->sanitizeFilename(".\sun.gif")); } - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php index 8ef5a8e5058..8b5c8f7e499 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -1,12 +1,13 @@ assertSame(Swagger\Client\Model\Order::STATUS_PLACED, "placed"); - $this->assertSame(Swagger\Client\Model\Order::STATUS_APPROVED, "approved"); + $this->assertSame(Model\Order::STATUS_PLACED, "placed"); + $this->assertSame(Model\Order::STATUS_APPROVED, "approved"); } // test get inventory public function testOrder() { // initialize the API client - $order = new Swagger\Client\Model\Order(); + $order = new Model\Order(); $order->setStatus("placed"); $this->assertSame("placed", $order->getStatus()); @@ -31,11 +32,11 @@ class OrderApiTest extends \PHPUnit_Framework_TestCase /** * @expectedException InvalidArgumentException - */ + */ public function testOrderException() { // initialize the API client - $order = new Swagger\Client\Model\Order(); + $order = new Model\Order(); $order->setStatus("invalid_value"); } @@ -52,13 +53,16 @@ class OrderApiTest extends \PHPUnit_Framework_TestCase "complete": false } ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'Swagger\Client\Model\Order'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'Swagger\Client\Model\Order' + ); $this->assertInstanceOf('Swagger\Client\Model\Order', $order); $this->assertSame(10, $order->getId()); $this->assertSame(20, $order->getPetId()); $this->assertSame(30, $order->getQuantity()); - $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); $this->assertSame("placed", $order->getStatus()); $this->assertSame(false, $order->getComplete()); } @@ -76,16 +80,19 @@ ORDER; "complete": false }]] ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'Swagger\Client\Model\Order[][]'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'Swagger\Client\Model\Order[][]' + ); - $this->assertArrayHasKey(0, $order); + $this->assertArrayHasKey(0, $order); $this->assertArrayHasKey(0, $order[0]); $_order = $order[0][0]; $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); $this->assertSame(10, $_order->getId()); $this->assertSame(20, $_order->getPetId()); $this->assertSame(30, $_order->getQuantity()); - $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); $this->assertSame("placed", $_order->getStatus()); $this->assertSame(false, $_order->getComplete()); } @@ -107,21 +114,20 @@ ORDER; } } ORDER; - $order = \Swagger\Client\ObjectSerializer::deserialize(json_decode($order_json), 'map[string,map[string,\Swagger\Client\Model\Order]]'); + $order = ObjectSerializer::deserialize( + json_decode($order_json), + 'map[string,map[string,\Swagger\Client\Model\Order]]' + ); - $this->assertArrayHasKey('test', $order); + $this->assertArrayHasKey('test', $order); $this->assertArrayHasKey('test2', $order['test']); $_order = $order['test']['test2']; $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); $this->assertSame(10, $_order->getId()); $this->assertSame(20, $_order->getPetId()); $this->assertSame(30, $_order->getQuantity()); - $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); $this->assertSame("placed", $_order->getStatus()); $this->assertSame(false, $_order->getComplete()); } - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 9feabf142cf..fa3733a8be2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -1,16 +1,17 @@ setId($new_pet_id); $new_pet->setName("PHP Unit Test"); $new_pet->setPhotoUrls(array("http://test_php_unit_test.com")); // new tag - $tag= new Swagger\Client\Model\Tag; + $tag= new Model\Tag; $tag->setId($new_pet_id); // use the same id as pet $tag->setName("test php tag"); // new category - $category = new Swagger\Client\Model\Category; + $category = new Model\Category; $category->setId($new_pet_id); // use the same id as pet $category->setName("test php category"); $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } // test static functions defined in ApiClient public function testApiClient() - { + { // test selectHeaderAccept - $api_client = new Swagger\Client\ApiClient(); - $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json'))); - $this->assertSame(NULL, $api_client->selectHeaderAccept(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml'))); + $api_client = new ApiClient(); + $this->assertSame('application/json', $api_client->selectHeaderAccept(array( + 'application/xml', + 'application/json' + ))); + $this->assertSame(null, $api_client->selectHeaderAccept(array())); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array( + 'application/yaml', + 'application/xml' + ))); // test selectHeaderContentType - $this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml','application/json'))); + $this->assertSame('application/json', $api_client->selectHeaderContentType(array( + 'application/xml', + 'application/json' + ))); $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array( + 'application/yaml', + 'application/xml' + ))); // test addDefaultHeader and getDefaultHeader $api_client->getConfig()->addDefaultHeader('test1', 'value1'); @@ -74,16 +87,16 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertFalse(isset($defaultHeader['test2'])); - $pet_api2 = new Swagger\Client\Api\PetApi(); - $config3 = new Swagger\Client\Configuration(); - $apiClient3 = new Swagger\Client\ApiClient($config3); + $pet_api2 = new Api\PetApi(); + $config3 = new Configuration(); + $apiClient3 = new ApiClient($config3); $apiClient3->getConfig()->setUserAgent('api client 3'); - $config4 = new Swagger\Client\Configuration(); - $apiClient4 = new Swagger\Client\ApiClient($config4); + $config4 = new Configuration(); + $apiClient4 = new ApiClient($config4); $apiClient4->getConfig()->setUserAgent('api client 4'); - $pet_api3 = new Swagger\Client\Api\PetApi($apiClient3); + $pet_api3 = new Api\PetApi($apiClient3); - // 2 different api clients are not the same + // 2 different api clients are not the same $this->assertNotEquals($apiClient3, $apiClient4); // customied pet api not using the old pet api's api client $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); @@ -98,7 +111,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) $response = $pet_api->getPetById($pet_id); @@ -111,7 +124,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); } - /* + /** * comment out as we've removed invalid endpoints from the spec, we'll introduce something * similar in the future when we've time to update the petstore server * @@ -120,7 +133,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (inline model) $response = $pet_api->getPetByIdInObject($pet_id); @@ -144,7 +157,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); @@ -162,18 +175,18 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testFindPetByStatus() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); $this->assertGreaterThan(0, count($response)); // at least one object returned $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" + // loop through result to ensure status is "available" foreach ($response as $_pet) { $this->assertSame($_pet['status'], "available"); } - // test invalid status + // test invalid status $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); $this->assertSame(count($response), 0); // confirm no object returned } @@ -182,18 +195,18 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testFindPetsByTags() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // return Pet (model) $response = $pet_api->findPetsByTags("test php tag"); $this->assertGreaterThan(0, count($response)); // at least one object returned $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" + // loop through result to ensure status is "available" foreach ($response as $_pet) { $this->assertSame($_pet['tags'][0]['name'], "test php tag"); } - // test invalid status + // test invalid status $response = $pet_api->findPetsByTags("unknown_and_incorrect_tag"); $this->assertSame(count($response), 0); // confirm no object returned } @@ -202,19 +215,19 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePet() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // create updated pet object - $updated_pet = new Swagger\Client\Model\Pet; + $updated_pet = new Model\Pet; $updated_pet->setId($pet_id); $updated_pet->setName('updatePet'); // new name $updated_pet->setStatus('pending'); // new status // update Pet (model/json) $update_response = $pet_api->updatePet($updated_pet); // return nothing (void) - $this->assertSame($update_response, NULL); + $this->assertSame($update_response, null); // verify updated Pet $response = $pet_api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); @@ -226,12 +239,15 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePetWithFormWithHttpInfo() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // update Pet (form) - list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo($pet_id, 'update pet with form with http info'); + list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo( + $pet_id, + 'update pet with form with http info' + ); // return nothing (void) $this->assertNull($update_response); $this->assertSame($status_code, 200); @@ -245,14 +261,14 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePetWithForm() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // update Pet (form) $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) - $this->assertSame($update_response, NULL); + $this->assertSame($update_response, null); $response = $pet_api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getName(), 'update pet with form'); @@ -263,17 +279,17 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testAddPet() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test 2"); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); // return nothing (void) - $this->assertSame($add_response, NULL); + $this->assertSame($add_response, null); // verify added Pet $response = $pet_api->getPetById($new_pet_id); $this->assertSame($response->getId(), $new_pet_id); @@ -288,28 +304,28 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testAddPetUsingByteArray() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test 3"); // new tag - $tag= new Swagger\Client\Model\Tag; + $tag= new Model\Tag; $tag->setId($new_pet_id); // use the same id as pet $tag->setName("test php tag"); // new category - $category = new Swagger\Client\Model\Category; + $category = new Model\Category; $category->setId($new_pet_id); // use the same id as pet $category->setName("test php category"); $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $pet_api = new Api\PetApi($api_client); // add a new pet (model) - $object_serializer = new Swagger\Client\ObjectSerializer(); + $object_serializer = new ObjectSerializer(); $pet_json_string = json_encode($object_serializer->sanitizeForSerialization($new_pet)); $add_response = $pet_api->addPetUsingByteArray($pet_json_string); // return nothing (void) @@ -325,13 +341,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUploadFile() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $pet_api = new Api\PetApi($api_client); // upload file $pet_id = 10001; $response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); - // return ApiResponse + // return ApiResponse $this->assertInstanceOf('Swagger\Client\Model\ApiResponse', $response); } @@ -340,10 +356,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $config = new Swagger\Client\Configuration(); + $config = new Configuration(); $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\APIClient($config); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + $api_client = new APIClient($config); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventory(); @@ -359,10 +375,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetPetByIdWithByteArray() { // initialize the API client - $config = new Swagger\Client\Configuration(); + $config = new Configuration(); $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\APIClient($config); - $pet_api = new Swagger\Client\Api\PetApi($api_client); + $api_client = new APIClient($config); + $pet_api = new Api\PetApi($api_client); // test getPetByIdWithByteArray $pet_id = 10005; $bytes = $pet_api->petPetIdtestingByteArraytrueGet($pet_id); @@ -383,7 +399,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test empty object serialization public function testEmptyPetSerialization() { - $new_pet = new Swagger\Client\Model\Pet; + $new_pet = new Model\Pet; // the empty object should be serialised to {} $this->assertSame("{}", "$new_pet"); @@ -392,7 +408,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test inheritance in the model public function testInheritance() { - $new_dog = new Swagger\Client\Model\Dog; + $new_dog = new Model\Dog; // the object should be an instance of the derived class $this->assertInstanceOf('Swagger\Client\Model\Dog', $new_dog); // the object should also be an instance of the parent class @@ -408,7 +424,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase 'class_name' => 'Dog', 'breed' => 'Great Dane' ); - $new_dog = new Swagger\Client\Model\Dog($data); + $new_dog = new Model\Dog($data); // the property on the derived class should be set $this->assertSame('Great Dane', $new_dog->getBreed()); @@ -419,7 +435,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test if discriminator is initialized automatically public function testDiscriminatorInitialization() { - $new_dog = new Swagger\Client\Model\Dog(); + $new_dog = new Model\Dog(); $this->assertSame('Dog', $new_dog->getClassName()); } @@ -428,13 +444,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // create an AnimalFarm which is an object implementing the // ArrayAccess interface - $farm = new Swagger\Client\Model\AnimalFarm(); + $farm = new Model\AnimalFarm(); // add some animals to the farm to make sure the ArrayAccess // interface works - $farm[] = new Swagger\Client\Model\Dog(); - $farm[] = new Swagger\Client\Model\Cat(); - $farm[] = new Swagger\Client\Model\Animal(); + $farm[] = new Model\Dog(); + $farm[] = new Model\Cat(); + $farm[] = new Model\Animal(); // assert we can look up the animals in the farm by array // indices (let's try a random order) @@ -455,16 +471,12 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // add some animals to the farm to make sure the ArrayAccess // interface works - $dog = new Swagger\Client\Model\Dog(); - $animal = new Swagger\Client\Model\Animal(); + $dog = new Model\Dog(); + $animal = new Model\Animal(); // assert we can look up the animals in the farm by array // indices (let's try a random order) $this->assertSame('red', $dog->getColor()); $this->assertSame('red', $animal->getColor()); } - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index 7d7dcf3ede3..800cd512e4f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -1,34 +1,35 @@ setId($new_pet_id); $new_pet->setName("PHP Unit Test"); $new_pet->setStatus("available"); // new tag - $tag= new Swagger\Client\Model\Tag; + $tag= new Model\Tag; $tag->setId($new_pet_id); // use the same id as pet $tag->setName("test php tag"); // new category - $category = new Swagger\Client\Model\Category; + $category = new Model\Category; $category->setId($new_pet_id); // use the same id as pet $category->setName("test php category"); $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api = new Api\PetAPI(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } @@ -37,9 +38,9 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventory(); @@ -55,9 +56,9 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase public function testGetInventoryInObject() { // initialize the API client - //$config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient(); - $store_api = new Swagger\Client\Api\StoreApi($api_client); + //$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient(); + $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventoryInObject(); @@ -65,8 +66,4 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase $this->assertInternalType("int", $get_response['available']); } */ - } - -?> - diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index 3efce8b08ba..a8487e58764 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -1,33 +1,34 @@ setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $user_api = new Swagger\Client\Api\UserApi($api_client); - // login - $response = $user_api->loginUser("xxxxx", "yyyyyyyy"); - - $this->assertInternalType("string", $response); - $this->assertRegExp("/^logged in user session/", $response, "response string starts with 'logged in user session'"); - - } + // test login user + public function testLoginUser() + { + // initialize the API client + $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new ApiClient($config); + $user_api = new Api\UserApi($api_client); + // login + $response = $user_api->loginUser("xxxxx", "yyyyyyyy"); + + $this->assertInternalType("string", $response); + $this->assertRegExp( + "/^logged in user session/", + $response, + "response string starts with 'logged in user session'" + ); + } } - -?> - diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift index 418f1c8512b..7041709f365 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -18,4 +18,22 @@ class APIHelper { } return destination } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject] { + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + if (source != nil) { + for (key, value) in source! { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + } + return destination + } + } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 64aa3c8803c..c7e5a6402b5 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -57,10 +57,12 @@ public class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -111,11 +113,14 @@ public class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -174,11 +179,14 @@ public class PetAPI: APIBase { let nillableParameters: [String:AnyObject?] = [ "status": status ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -276,11 +284,14 @@ public class PetAPI: APIBase { let nillableParameters: [String:AnyObject?] = [ "tags": tags ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -380,11 +391,14 @@ public class PetAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -433,10 +447,12 @@ public class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -496,11 +512,14 @@ public class PetAPI: APIBase { "name": name, "status": status ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -560,11 +579,14 @@ public class PetAPI: APIBase { "additionalMetadata": additionalMetadata, "file": file ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 4521afd3d89..be7d36b91f3 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -56,11 +56,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -112,11 +115,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -194,11 +200,14 @@ public class StoreAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -274,10 +283,12 @@ public class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 62018cd83c2..1b5ada9da67 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -54,10 +54,12 @@ public class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -103,10 +105,12 @@ public class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -152,10 +156,12 @@ public class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -203,11 +209,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -293,11 +302,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -352,11 +364,14 @@ public class UserAPI: APIBase { "username": username, "password": password ] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -399,11 +414,14 @@ public class UserAPI: APIBase { let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) } /** @@ -453,10 +471,12 @@ public class UserAPI: APIBase { path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body?.encodeToJSON() as? [String:AnyObject] - + + let convertedParameters = APIHelper.convertBoolToString(parameters) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: parameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift index 0aa3b3e381c..5a8eade51b3 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift @@ -46,9 +46,9 @@ class Decoders { } static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { - let sourceDictinoary = source as! [Key: AnyObject] + let sourceDictionary = source as! [Key: AnyObject] var dictionary = [Key:T]() - for (key, value) in sourceDictinoary { + for (key, value) in sourceDictionary { dictionary[key] = Decoders.decode(clazz: T.self, source: value) } return dictionary @@ -156,7 +156,7 @@ class Decoders { instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"]) instance.quantity = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["quantity"]) instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"]) - instance.status = Order.ST(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"]) return instance } @@ -175,7 +175,7 @@ class Decoders { instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"]) instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) - instance.status = Pet.ST(rawValue: (sourceDictionary["status"] as? String) ?? "") + instance.status = Pet.Status(rawValue: (sourceDictionary["status"] as? String) ?? "") return instance } diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift index e4086143266..87b2a2c5247 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -9,7 +9,7 @@ import Foundation public class Order: JSONEncodable { - public enum ST: String { + public enum Status: String { case Placed = "placed" case Approved = "approved" case Delivered = "delivered" @@ -19,7 +19,7 @@ public class Order: JSONEncodable { public var quantity: Int32? public var shipDate: NSDate? /** Order Status */ - public var status: ST? + public var status: Status? public var complete: Bool? public init() {} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift index ee9aa295a53..ebcd2c1825f 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -9,7 +9,7 @@ import Foundation public class Pet: JSONEncodable { - public enum ST: String { + public enum Status: String { case Available = "available" case Pending = "pending" case Sold = "sold" @@ -20,7 +20,7 @@ public class Pet: JSONEncodable { public var photoUrls: [String]? public var tags: [Tag]? /** pet status in the store */ - public var status: ST? + public var status: Status? public init() {} diff --git a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift b/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift index 38948737687..b52fe4a0fa8 100644 --- a/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift +++ b/samples/client/petstore/swift/SwaggerClientTests/SwaggerClientTests/StoreAPITests.swift @@ -32,7 +32,8 @@ class StoreAPITests: XCTestCase { order.complete = false order.quantity = 10 order.shipDate = NSDate() - order.status = .Placed + // use explicit naming to reference the enum so that we test we don't regress on enum naming + order.status = Order.Status.Placed let expectation = self.expectationWithDescription("testPlaceOrder") StoreAPI.placeOrder(body: order).then { order -> Void in XCTAssert(order.id == 1000, "invalid id") diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 62492c17d80..90b44ec3e73 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -9,10 +9,10 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 976ee7acd48..7c3fed82fa3 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -9,10 +9,10 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 79f6326b99c..d237038d7da 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -9,10 +9,10 @@ namespace API.Client { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath) { + if (basePath !== undefined) { this.basePath = basePath; } } diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index e2121b52c0b..a708d49e9f9 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index 618b0c23624..e6602884a81 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index f52b407d126..04d2e8155d5 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 8120c59916e..0fdbf4a4ded 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201604282253 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605120027 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201604282253 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201605120027 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index e2121b52c0b..a708d49e9f9 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index 618b0c23624..e6602884a81 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class StoreApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index f52b407d126..04d2e8155d5 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -1,7 +1,8 @@ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http'; -import {Injectable} from 'angular2/core'; +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import * as models from '../model/models'; +import 'rxjs/Rx'; /* tslint:disable:no-unused-variable member-ordering */ @@ -12,7 +13,7 @@ export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : Headers = new Headers(); - constructor(protected http: Http, basePath: string) { + constructor(protected http: Http, @Optional() basePath: string) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index cab5097a4ed..8447881dafc 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201604282253", + "version": "0.0.1-SNAPSHOT.201605120027", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ @@ -16,17 +16,30 @@ "build": "typings install && tsc" }, "peerDependencies": { - "angular2": "^2.0.0-beta.15", - "rxjs": "^5.0.0-beta.2" + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12" }, "devDependencies": { + "@angular/common": "^2.0.0-rc.1", + "@angular/compiler": "^2.0.0-rc.1", + "@angular/core": "^2.0.0-rc.1", + "@angular/http": "^2.0.0-rc.1", + "@angular/platform-browser": "^2.0.0-rc.1", + "@angular/platform-browser-dynamic": "^2.0.0-rc.1", + "core-js": "^2.3.0", + "rxjs": "^5.0.0-beta.6", + "zone.js": "^0.6.12", "typescript": "^1.8.10", "typings": "^0.8.1", - "angular2": "^2.0.0-beta.15", "es6-shim": "^0.35.0", - "es7-reflect-metadata": "^1.6.0", - "rxjs": "5.0.0-beta.2", - "zone.js": "^0.6.10" + "es7-reflect-metadata": "^1.6.0" }, "publishConfig":{ "registry":"https://skimdb.npmjs.com/registry" diff --git a/samples/client/petstore/typescript-fetch/api.ts b/samples/client/petstore/typescript-fetch/api.ts deleted file mode 100644 index 0c8f4201e4c..00000000000 --- a/samples/client/petstore/typescript-fetch/api.ts +++ /dev/null @@ -1,859 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - - -export enum StatusEnum { - placed = 'placed', - approved = 'approved', - delivered = 'delivered' -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - - -export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold' -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - var error = new Error(response.statusText); - error['response'] = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/assign.ts b/samples/client/petstore/typescript-fetch/assign.ts deleted file mode 100644 index 040f87d7d98..00000000000 --- a/samples/client/petstore/typescript-fetch/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target, ...args) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/default/README.md b/samples/client/petstore/typescript-fetch/builds/default/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts new file mode 100644 index 00000000000..3882e79a66c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -0,0 +1,1122 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + } +} + + +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ +export class StoreApi extends BaseAPI { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + } +} + + +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore/typescript-fetch/default-es6/git_push.sh b/samples/client/petstore/typescript-fetch/builds/default/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/default-es6/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/default/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/default-es6/package.json b/samples/client/petstore/typescript-fetch/builds/default/package.json similarity index 81% rename from samples/client/petstore/typescript-fetch/default-es6/package.json rename to samples/client/petstore/typescript-fetch/builds/default/package.json index 84cf629d931..06bb023ad5b 100644 --- a/samples/client/petstore/typescript-fetch/default-es6/package.json +++ b/samples/client/petstore/typescript-fetch/builds/default/package.json @@ -1,15 +1,15 @@ { "name": "typescript-fetch-api", "version": "0.0.0", - "private": true, "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { + "core-js": "^2.4.0", "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json similarity index 85% rename from samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/default/tsconfig.json index 18db23e2f5f..72ff2567206 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/default/tsconfig.json @@ -4,7 +4,8 @@ "target": "es5", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json b/samples/client/petstore/typescript-fetch/builds/default/typings.json similarity index 65% rename from samples/client/petstore/typescript-fetch/with-package-metadata/typings.json rename to samples/client/petstore/typescript-fetch/builds/default/typings.json index eeca5afde97..32c5b1e2b0b 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/default/typings.json @@ -1,8 +1,8 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "ambientDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654", "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/README.md b/samples/client/petstore/typescript-fetch/builds/es6-target/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts new file mode 100644 index 00000000000..15a61ab6961 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -0,0 +1,1121 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + } +} + + +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ +export class StoreApi extends BaseAPI { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + } +} + + +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = Object.assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore/typescript-fetch/default/git_push.sh b/samples/client/petstore/typescript-fetch/builds/es6-target/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/default/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/es6-target/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/default/package.json b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json similarity index 83% rename from samples/client/petstore/typescript-fetch/default/package.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/package.json index 84cf629d931..ab5d5b0ce15 100644 --- a/samples/client/petstore/typescript-fetch/default/package.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json @@ -1,7 +1,6 @@ { "name": "typescript-fetch-api", "version": "0.0.0", - "private": true, "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", @@ -9,7 +8,7 @@ "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", diff --git a/samples/client/petstore/typescript-fetch/default-es6/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json similarity index 85% rename from samples/client/petstore/typescript-fetch/default-es6/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json index 9d5f166e764..06a8e0437b9 100644 --- a/samples/client/petstore/typescript-fetch/default-es6/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/default-es6/typings.json b/samples/client/petstore/typescript-fetch/builds/es6-target/typings.json similarity index 86% rename from samples/client/petstore/typescript-fetch/default-es6/typings.json rename to samples/client/petstore/typescript-fetch/builds/es6-target/typings.json index 3ce24427fc6..0f09addb324 100644 --- a/samples/client/petstore/typescript-fetch/default-es6/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/typings.json @@ -1,7 +1,7 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { + "ambientDependencies": { "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md b/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts new file mode 100644 index 00000000000..3882e79a66c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -0,0 +1,1122 @@ +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "http://petstore.swagger.io/v2"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +export interface Category { + "id"?: number; + "name"?: string; +} + +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: OrderStatusEnum; + "complete"?: boolean; +} + +export type OrderStatusEnum = "placed" | "approved" | "delivered"; +export interface Pet { + "id"?: number; + "category"?: Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: PetStatusEnum; +} + +export type PetStatusEnum = "available" | "pending" | "sold"; +export interface Tag { + "id"?: number; + "name"?: string; +} + +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; +} + + + +/** + * PetApi - fetch parameter creator + */ +export const PetApiFetchParamCreactor = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling deletePet"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): FetchArgs { + const baseUrl = `/pet/findByStatus`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "status": params.status, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): FetchArgs { + const baseUrl = `/pet/findByTags`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "tags": params.tags, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling getPetById"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): FetchArgs { + const baseUrl = `/pet`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling updatePetWithForm"); + } + const baseUrl = `/pet/{petId}` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "name": params.name, + "status": params.status, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + // verify required parameter "petId" is set + if (params["petId"] == null) { + throw new Error("Missing required parameter petId when calling uploadFile"); + } + const baseUrl = `/pet/{petId}/uploadImage` + .replace(`{${"petId"}}`, `${ params.petId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "additionalMetadata": params.additionalMetadata, + "file": params.file, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * PetApi - functional programming interface + */ +export const PetApiFp = { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * PetApi - object-oriented interface + */ +export class PetApi extends BaseAPI { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + addPet(params: { body?: Pet; }) { + return PetApiFp.addPet(params)(this.fetch, this.basePath); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + deletePet(params: { petId: number; apiKey?: string; }) { + return PetApiFp.deletePet(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + */ + findPetsByStatus(params: { status?: Array; }) { + return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + } + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + */ + findPetsByTags(params: { tags?: Array; }) { + return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + getPetById(params: { petId: number; }) { + return PetApiFp.getPetById(params)(this.fetch, this.basePath); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + updatePet(params: { body?: Pet; }) { + return PetApiFp.updatePet(params)(this.fetch, this.basePath); + } + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { + return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { + return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + } +} + + +/** + * StoreApi - fetch parameter creator + */ +export const StoreApiFetchParamCreactor = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling deleteOrder"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): FetchArgs { + const baseUrl = `/store/inventory`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): FetchArgs { + // verify required parameter "orderId" is set + if (params["orderId"] == null) { + throw new Error("Missing required parameter orderId when calling getOrderById"); + } + const baseUrl = `/store/order/{orderId}` + .replace(`{${"orderId"}}`, `${ params.orderId }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): FetchArgs { + const baseUrl = `/store/order`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * StoreApi - functional programming interface + */ +export const StoreApiFp = { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, +}; + +/** + * StoreApi - object-oriented interface + */ +export class StoreApi extends BaseAPI { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + deleteOrder(params: { orderId: string; }) { + return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + getInventory() { + return StoreApiFp.getInventory()(this.fetch, this.basePath); + } + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ + getOrderById(params: { orderId: string; }) { + return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + placeOrder(params: { body?: Order; }) { + return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + } +} + + +/** + * UserApi - fetch parameter creator + */ +export const UserApiFetchParamCreactor = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): FetchArgs { + const baseUrl = `/user`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithArray`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): FetchArgs { + const baseUrl = `/user/createWithList`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "POST" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling deleteUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "DELETE" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling getUserByName"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): FetchArgs { + const baseUrl = `/user/login`; + let urlObj = url.parse(baseUrl, true); + urlObj.query = assign({}, urlObj.query, { + "username": params.username, + "password": params.password, + }); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): FetchArgs { + const baseUrl = `/user/logout`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "GET" }; + + let contentTypeHeader: Dictionary; + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): FetchArgs { + // verify required parameter "username" is set + if (params["username"] == null) { + throw new Error("Missing required parameter username when calling updateUser"); + } + const baseUrl = `/user/{username}` + .replace(`{${"username"}}`, `${ params.username }`); + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/json" }; + if (params["body"]) { + fetchOptions.body = JSON.stringify(params["body"] || {}); + } + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * UserApi - functional programming interface + */ +export const UserApiFp = { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response.json(); + } else { + throw response; + } + }); + }; + }, + /** + * Logs out current logged in user session + * + */ + logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * UserApi - object-oriented interface + */ +export class UserApi extends BaseAPI { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + createUser(params: { body?: User; }) { + return UserApiFp.createUser(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithArrayInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + createUsersWithListInput(params: { body?: Array; }) { + return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + deleteUser(params: { username: string; }) { + return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + getUserByName(params: { username: string; }) { + return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + loginUser(params: { username?: string; password?: string; }) { + return UserApiFp.loginUser(params)(this.fetch, this.basePath); + } + /** + * Logs out current logged in user session + * + */ + logoutUser() { + return UserApiFp.logoutUser()(this.fetch, this.basePath); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + updateUser(params: { username: string; body?: User; }) { + return UserApiFp.updateUser(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore/typescript-fetch/git_push.sh b/samples/client/petstore/typescript-fetch/builds/with-npm-version/git_push.sh similarity index 100% rename from samples/client/petstore/typescript-fetch/git_push.sh rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/git_push.sh diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/package.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json similarity index 82% rename from samples/client/petstore/typescript-fetch/with-package-metadata/package.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json index ab2a67c51d0..7dc5e398bc9 100644 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/package.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json @@ -1,15 +1,15 @@ { "name": "@swagger/typescript-fetch-petstore", "version": "0.0.1", - "private": true, "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", "dependencies": { + "core-js": "^2.4.0", "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "install" : "typings install && tsc" + "prepublish" : "typings install && tsc" }, "devDependencies": { "typescript": "^1.8.10", diff --git a/samples/client/petstore/typescript-fetch/default/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json similarity index 85% rename from samples/client/petstore/typescript-fetch/default/tsconfig.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json index 18db23e2f5f..72ff2567206 100644 --- a/samples/client/petstore/typescript-fetch/default/tsconfig.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tsconfig.json @@ -4,7 +4,8 @@ "target": "es5", "module": "commonjs", "noImplicitAny": true, - "outDir": "dist" + "outDir": "dist", + "rootDir": "." }, "exclude": [ "dist", diff --git a/samples/client/petstore/typescript-fetch/default/typings.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json similarity index 65% rename from samples/client/petstore/typescript-fetch/default/typings.json rename to samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json index eeca5afde97..32c5b1e2b0b 100644 --- a/samples/client/petstore/typescript-fetch/default/typings.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/typings.json @@ -1,8 +1,8 @@ { "version": false, "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "ambientDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654", "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" } diff --git a/samples/client/petstore/typescript-fetch/default-es6/README.md b/samples/client/petstore/typescript-fetch/default-es6/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default-es6/api.ts b/samples/client/petstore/typescript-fetch/default-es6/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - -export namespace Order { - -export type StatusEnum = 'placed' | 'approved' | 'delivered'; -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - -export namespace Pet { - -export type StatusEnum = 'available' | 'pending' | 'sold'; -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/default-es6/assign.ts b/samples/client/petstore/typescript-fetch/default-es6/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/default-es6/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/README.md b/samples/client/petstore/typescript-fetch/default/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/default/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/default/api.ts b/samples/client/petstore/typescript-fetch/default/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/default/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - -export namespace Order { - -export type StatusEnum = 'placed' | 'approved' | 'delivered'; -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - -export namespace Pet { - -export type StatusEnum = 'available' | 'pending' | 'sold'; -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/default/assign.ts b/samples/client/petstore/typescript-fetch/default/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/default/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/package.json b/samples/client/petstore/typescript-fetch/package.json deleted file mode 100644 index 722c87cc323..00000000000 --- a/samples/client/petstore/typescript-fetch/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "private": true, - "dependencies": { - "isomorphic-fetch": "^2.2.1" - }, - "devDependencies": { - "typescript": "^1.8.10", - "typings": "^0.8.1" - } -} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/package.json b/samples/client/petstore/typescript-fetch/tests/default/package.json new file mode 100644 index 00000000000..7653b45f9a1 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/package.json @@ -0,0 +1,26 @@ +{ + "private": true, + "dependencies": { + "chai": "^3.5.0" + }, + "devDependencies": { + "browserify": "^13.0.1", + "ts-loader": "^0.8.2", + "tsify": "^0.15.5", + "typescript": "^1.8.10", + "typings": "^0.8.1", + "webpack": "^1.13.0" + }, + "scripts": { + "prepublish": "./scripts/prepublish.sh", + "test": "mocha" + }, + "name": "typescript-fetch-test", + "version": "1.0.0", + "directories": { + "test": "test" + }, + "author": "", + "license": "ISC", + "description": "" +} diff --git a/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html new file mode 100644 index 00000000000..5d378bac582 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_browserify.html @@ -0,0 +1,26 @@ + + + + Mocha Tests + + + +
+ + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html new file mode 100644 index 00000000000..625c8859422 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/run_tests_via_webpack.html @@ -0,0 +1,27 @@ + + + + Mocha Tests + + + +
+ + + + + + + + + + diff --git a/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh b/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh new file mode 100755 index 00000000000..3c0dfb05953 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/scripts/prepublish.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +npm install ../../builds/default +typings install + +# Build Node.js +tsc + +# Build Webpack +webpack + +# Build browserify +browserify test -p [ tsify ] > ./dist/test.browserify-bundle.js diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts new file mode 100644 index 00000000000..04b2c032a34 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts @@ -0,0 +1,63 @@ +import {expect} from 'chai'; +import {PetApi, Pet, Category} from 'typescript-fetch-api'; + +describe('PetApi', () => { + let api: PetApi; + let fixture: Pet = createTestFixture(); + + beforeEach(() => { + api = new PetApi(); + }); + + it('should add and delete Pet', () => { + return api.addPet({ body: fixture }).then(() => { + }); + }); + + it('should get Pet by ID', () => { + return api.getPetById({ petId: fixture.id }).then((result) => { + return expect(result).to.deep.equal(fixture); + }); + }); + + it('should update Pet by ID', () => { + return api.getPetById({ petId: fixture.id }).then( (result) => { + result.name = 'newname'; + return api.updatePet({ body: result }).then(() => { + return api.getPetById({ petId: fixture.id }).then( (result) => { + return expect(result.name).to.deep.equal('newname'); + }); + }); + }); + }); + + it('should delete Pet', () => { + return api.deletePet({ petId: fixture.id }); + }); + + it('should not contain deleted Pet', () => { + return api.getPetById({ petId: fixture.id }).then((result) => { + return expect(result).to.not.exist; + }, (err) => { + return expect(err).to.exist; + }); + }); +}); + +function createTestFixture(ts = Date.now()) { + const category: Category = { + 'id': ts, + 'name': `category${ts}`, + }; + + const pet: Pet = { + 'id': ts, + 'name': `pet${ts}`, + 'category': category, + 'photoUrls': ['http://foo.bar.com/1', 'http://foo.bar.com/2'], + 'status': 'available', + 'tags': [] + }; + + return pet; +}; diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts new file mode 100644 index 00000000000..420def0ab62 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts @@ -0,0 +1,18 @@ +import {expect} from 'chai'; +import {StoreApi} from 'typescript-fetch-api'; + +describe('StoreApi', function() { + let api: StoreApi; + + beforeEach(function() { + api = new StoreApi(); + }); + + it('should get inventory', function() { + return api.getInventory().then((result) => { + expect(Object.keys(result)).to.not.be.empty; + }); + }); + +}); + diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/index.ts b/samples/client/petstore/typescript-fetch/tests/default/test/index.ts new file mode 100644 index 00000000000..29369a2d0e2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/index.ts @@ -0,0 +1,2 @@ +import './PetApi'; +import './StoreApi'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts b/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts new file mode 100644 index 00000000000..12ea969970a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/test/mocha.opts @@ -0,0 +1 @@ +--timeout 10000 dist/test diff --git a/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json b/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json new file mode 100644 index 00000000000..e47c2647e01 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "noImplicitAny": true, + "sourceMap": false, + "outDir": "dist", + "rootDir": "." + }, + "exclude": [ + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tests/default/typings.json b/samples/client/petstore/typescript-fetch/tests/default/typings.json new file mode 100644 index 00000000000..e792f9ecd7e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/typings.json @@ -0,0 +1,9 @@ +{ + "name": "typescript-fetch-test", + "version": false, + "ambientDependencies": { + "chai": "registry:dt/chai#3.4.0+20160317120654", + "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", + "mocha": "registry:dt/mocha#2.2.5+20160317120654" + } +} diff --git a/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js b/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js new file mode 100644 index 00000000000..d3332281c5c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/tests/default/webpack.config.js @@ -0,0 +1,30 @@ +const webpack = require('webpack'); + +module.exports = { + entry: { + app: './test/index.ts', + vendor: [ + // libraries + 'typescript-fetch-api' + ], + }, + output: { + filename: './dist/test.webpack-bundle.js' + }, + plugins: [ + new webpack.optimize.CommonsChunkPlugin(/* chunkName= */'vendor', /* filename= */'./dist/vendor.webpack-bundle.js') + ], + resolve: { + // Add `.ts` and `.tsx` as a resolvable extension. + extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js'] + }, + module: { + loaders: [ + // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader` + { + test: /\.tsx?$/, + loader: 'ts-loader' + } + ] + } +}; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/tsconfig.json b/samples/client/petstore/typescript-fetch/tsconfig.json deleted file mode 100644 index fc93dc1610e..00000000000 --- a/samples/client/petstore/typescript-fetch/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "compilerOptions": { - "target": "es5" - }, - "exclude": [ - "node_modules", - "typings/browser", - "typings/main", - "typings/main.d.ts" - ] -} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/typings.json b/samples/client/petstore/typescript-fetch/typings.json deleted file mode 100644 index c22f086f7f0..00000000000 --- a/samples/client/petstore/typescript-fetch/typings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "version": false, - "dependencies": {}, - "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", - "node": "registry:dt/node#4.0.0+20160423143914", - "isomorphic-fetch": "github:leonyu/DefinitelyTyped/isomorphic-fetch/isomorphic-fetch.d.ts#isomorphic-fetch-fix-module" - } -} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/README.md b/samples/client/petstore/typescript-fetch/with-package-metadata/README.md deleted file mode 100644 index 8ec43e76497..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# TypeScript-Fetch - -This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments: - -* Node.JS -* Webpack -* Browserify - -It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) - -### Installation ### - -`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`. - -CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case. - -#### NPM repository ### -If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module. - -It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). - -#### NPM install local file ### -You should be able to directly install the module using `npm install file:///codegen_path`. - -NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute. - -#### direct copy/symlink ### -You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below) - -### Usage ### -With ES6 module syntax, the following syntaxes are supported: -``` -import * as localName from 'npmName'; -import {operationId} from 'npmName'; - -import * as localName from './symlinkDir'; -import {operationId} from './symlinkDir'; -``` -With CommonJS, the following syntaxes are supported: -``` -import localName = require('npmName'); - -import localName = require('./symlinkDir')'; -``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts b/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts deleted file mode 100644 index 3d075fc2809..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/api.ts +++ /dev/null @@ -1,855 +0,0 @@ -import * as querystring from 'querystring'; -import * as fetch from 'isomorphic-fetch'; -import {assign} from './assign'; - - -export interface Category { - "id"?: number; - "name"?: string; -} - -export interface Order { - "id"?: number; - "petId"?: number; - "quantity"?: number; - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - "complete"?: boolean; -} - -export namespace Order { - -export type StatusEnum = 'placed' | 'approved' | 'delivered'; -} -export interface Pet { - "id"?: number; - "category"?: Category; - "name": string; - "photoUrls": Array; - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; -} - -export namespace Pet { - -export type StatusEnum = 'available' | 'pending' | 'sold'; -} -export interface Tag { - "id"?: number; - "name"?: string; -} - -export interface User { - "id"?: number; - "username"?: string; - "firstName"?: string; - "lastName"?: string; - "email"?: string; - "password"?: string; - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; -} - - -//export namespace { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - headerParams['api_key'] = params.apiKey; - - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * @param status Status values that need to be considered for filter - */ - public findPetsByStatus (params: { status?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.status !== undefined) { - queryParameters['status'] = params.status; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by - */ - public findPetsByTags (params: { tags?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.tags !== undefined) { - queryParameters['tags'] = params.tags; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - */ - public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - formParams['name'] = params.name; - - formParams['status'] = params.status; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(params.petId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let formParams: any = {}; - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - // verify required parameter 'petId' is set - if (params.petId == null) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - formParams['additionalMetadata'] = params.additionalMetadata; - - formParams['file'] = params.file; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: querystring.stringify(formParams), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - */ - public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - */ - public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(params.orderId)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'orderId' is set - if (params.orderId == null) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} -//export namespace { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - constructor(basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (params: { body?: Array; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - let fetchParams = { - method: 'POST', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - let fetchParams = { - method: 'DELETE', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - if (params.username !== undefined) { - queryParameters['username'] = params.username; - } - - if (params.password !== undefined) { - queryParameters['password'] = params.password; - } - - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - let fetchParams = { - method: 'GET', - headers: headerParams, - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(params.username)); - - let queryParameters: any = assign({}, extraQueryParams); - let headerParams: any = assign({}, this.defaultHeaders); - headerParams['Content-Type'] = 'application/json'; - - // verify required parameter 'username' is set - if (params.username == null) { - throw new Error('Missing required parameter username when calling updateUser'); - } - let fetchParams = { - method: 'PUT', - headers: headerParams, - body: JSON.stringify(params.body), - - }; - - if (extraFetchParams) { - fetchParams = assign(fetchParams, extraFetchParams); - } - - let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters); - - return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => { - if (response.status >= 200 && response.status < 300) { - return response.json(); - } else { - let error = new Error(response.statusText); - (error as any).response = response; - throw error; - } - }); - } - } -//} diff --git a/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts b/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts deleted file mode 100644 index 23355144147..00000000000 --- a/samples/client/petstore/typescript-fetch/with-package-metadata/assign.ts +++ /dev/null @@ -1,18 +0,0 @@ -export function assign (target: any, ...args: any[]) { - 'use strict'; - if (target === undefined || target === null) { - throw new TypeError('Cannot convert undefined or null to object'); - } - - var output = Object(target); - for (let source of args) { - if (source !== undefined && source !== null) { - for (var nextKey in source) { - if (source.hasOwnProperty(nextKey)) { - output[nextKey] = source[nextKey]; - } - } - } - } - return output; -}; \ No newline at end of file diff --git a/samples/server/petstore/rails5/Gemfile b/samples/server/petstore/rails5/Gemfile new file mode 100644 index 00000000000..b553bf7355d --- /dev/null +++ b/samples/server/petstore/rails5/Gemfile @@ -0,0 +1,36 @@ +source 'https://rubygems.org' + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '>= 5.0.0.racecar1', '< 5.1' +# Use mysql as the database for Active Record +gem 'mysql2', '>= 0.3.18', '< 0.5' +# Use Puma as the app server +gem 'puma', '~> 3.0' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.0' +# Use Redis adapter to run Action Cable in production +# gem 'redis', '~> 3.0' +# Use ActiveModel has_secure_password +# gem 'bcrypt', '~> 3.1.7' + +# Use Capistrano for deployment +# gem 'capistrano-rails', group: :development + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platform: :mri +end + +group :development do + gem 'listen', '~> 3.0.5' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' + gem 'spring-watcher-listen', '~> 2.0.0' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/samples/server/petstore/rails5/Gemfile.lock b/samples/server/petstore/rails5/Gemfile.lock new file mode 100644 index 00000000000..f544bc0f702 --- /dev/null +++ b/samples/server/petstore/rails5/Gemfile.lock @@ -0,0 +1,141 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + nio4r (~> 1.2) + websocket-driver (~> 0.6.1) + actionmailer (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + actionview (= 5.0.0.rc1) + activejob (= 5.0.0.rc1) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 1.0, >= 1.0.5) + actionpack (5.0.0.rc1) + actionview (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + rack (~> 2.x) + rack-test (~> 0.6.3) + rails-dom-testing (~> 1.0, >= 1.0.5) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + actionview (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + builder (~> 3.1) + erubis (~> 2.7.0) + rails-dom-testing (~> 1.0, >= 1.0.5) + rails-html-sanitizer (~> 1.0, >= 1.0.2) + activejob (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + globalid (>= 0.3.6) + activemodel (5.0.0.rc1) + activesupport (= 5.0.0.rc1) + activerecord (5.0.0.rc1) + activemodel (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + arel (~> 7.0) + activesupport (5.0.0.rc1) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (~> 0.7) + minitest (~> 5.1) + tzinfo (~> 1.1) + arel (7.0.0) + builder (3.2.2) + byebug (9.0.0) + concurrent-ruby (1.0.2) + erubis (2.7.0) + ffi (1.9.10) + globalid (0.3.6) + activesupport (>= 4.1.0) + i18n (0.7.0) + jbuilder (2.4.1) + activesupport (>= 3.0.0, < 5.1) + multi_json (~> 1.2) + json (1.8.3) + listen (3.0.7) + rb-fsevent (>= 0.9.3) + rb-inotify (>= 0.9.7) + loofah (2.0.3) + nokogiri (>= 1.5.9) + mail (2.6.4) + mime-types (>= 1.16, < 4) + method_source (0.8.2) + mime-types (3.0) + mime-types-data (~> 3.2015) + mime-types-data (3.2016.0221) + mini_portile2 (2.0.0) + minitest (5.8.4) + multi_json (1.12.0) + mysql2 (0.4.4) + nio4r (1.2.1) + nokogiri (1.6.7.2) + mini_portile2 (~> 2.0.0.rc2) + puma (3.4.0) + rack (2.0.0.rc1) + json + rack-test (0.6.3) + rack (>= 1.0) + rails (5.0.0.rc1) + actioncable (= 5.0.0.rc1) + actionmailer (= 5.0.0.rc1) + actionpack (= 5.0.0.rc1) + actionview (= 5.0.0.rc1) + activejob (= 5.0.0.rc1) + activemodel (= 5.0.0.rc1) + activerecord (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + bundler (>= 1.3.0, < 2.0) + railties (= 5.0.0.rc1) + sprockets-rails (>= 2.0.0) + rails-deprecated_sanitizer (1.0.3) + activesupport (>= 4.2.0.alpha) + rails-dom-testing (1.0.7) + activesupport (>= 4.2.0.beta, < 5.0) + nokogiri (~> 1.6.0) + rails-deprecated_sanitizer (>= 1.0.1) + rails-html-sanitizer (1.0.3) + loofah (~> 2.0) + railties (5.0.0.rc1) + actionpack (= 5.0.0.rc1) + activesupport (= 5.0.0.rc1) + method_source + rake (>= 0.8.7) + thor (>= 0.18.1, < 2.0) + rake (11.1.2) + rb-fsevent (0.9.7) + rb-inotify (0.9.7) + ffi (>= 0.5.0) + spring (1.7.1) + spring-watcher-listen (2.0.0) + listen (>= 2.7, < 4.0) + spring (~> 1.2) + sprockets (3.6.0) + concurrent-ruby (~> 1.0) + rack (> 1, < 3) + sprockets-rails (3.0.4) + actionpack (>= 4.0) + activesupport (>= 4.0) + sprockets (>= 3.0.0) + thor (0.19.1) + thread_safe (0.3.5) + tzinfo (1.2.2) + thread_safe (~> 0.1) + websocket-driver (0.6.3) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.2) + +PLATFORMS + ruby + +DEPENDENCIES + byebug + jbuilder (~> 2.0) + listen (~> 3.0.5) + mysql2 (>= 0.3.18, < 0.5) + puma (~> 3.0) + rails (>= 5.0.0.racecar1, < 5.1) + spring + spring-watcher-listen (~> 2.0.0) + tzinfo-data + +BUNDLED WITH + 1.11.2 diff --git a/samples/server/petstore/rails5/README.md b/samples/server/petstore/rails5/README.md new file mode 100644 index 00000000000..c5cb90075a6 --- /dev/null +++ b/samples/server/petstore/rails5/README.md @@ -0,0 +1,25 @@ +# Swagger for Rails 5 + +This is a project to provide Swagger support inside the [Sinatra](http://rubyonrails.org/) framework. + +## Prerequisites +You need to install ruby >= 2.2.2 and run: + +``` +bundle install +``` + +## Getting started + +This sample was generated with the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. + +``` +bin/rake db:create +bin/rails s +``` + +To list all your routes, use: + +``` +bin/rake routes +``` diff --git a/samples/server/petstore/rails5/Rakefile b/samples/server/petstore/rails5/Rakefile new file mode 100644 index 00000000000..e85f913914b --- /dev/null +++ b/samples/server/petstore/rails5/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/samples/server/petstore/rails5/app/channels/application_cable/channel.rb b/samples/server/petstore/rails5/app/channels/application_cable/channel.rb new file mode 100644 index 00000000000..d56fa30f4d8 --- /dev/null +++ b/samples/server/petstore/rails5/app/channels/application_cable/channel.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/samples/server/petstore/rails5/app/channels/application_cable/connection.rb b/samples/server/petstore/rails5/app/channels/application_cable/connection.rb new file mode 100644 index 00000000000..b4f41389ad0 --- /dev/null +++ b/samples/server/petstore/rails5/app/channels/application_cable/connection.rb @@ -0,0 +1,5 @@ +# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading. +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/samples/server/petstore/rails5/app/controllers/application_controller.rb b/samples/server/petstore/rails5/app/controllers/application_controller.rb new file mode 100644 index 00000000000..4ac8823b095 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/samples/server/petstore/rails5/app/controllers/pet_controllers.rb b/samples/server/petstore/rails5/app/controllers/pet_controllers.rb new file mode 100644 index 00000000000..fa7e2557947 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/pet_controllers.rb @@ -0,0 +1,50 @@ +class PetController < ApplicationController + + def create + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def destroy + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def find_pets_by_status + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def find_pets_by_tags + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def show + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update_pet + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update_pet_with_form + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def upload_file + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/controllers/store_controllers.rb b/samples/server/petstore/rails5/app/controllers/store_controllers.rb new file mode 100644 index 00000000000..71fef4d92f8 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/store_controllers.rb @@ -0,0 +1,26 @@ +class StoreController < ApplicationController + + def delete_order + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def get_inventory + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def get_order_by_id + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def place_order + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/controllers/user_controllers.rb b/samples/server/petstore/rails5/app/controllers/user_controllers.rb new file mode 100644 index 00000000000..b8b2ce93634 --- /dev/null +++ b/samples/server/petstore/rails5/app/controllers/user_controllers.rb @@ -0,0 +1,50 @@ +class UserController < ApplicationController + + def create + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def create_users_with_array_input + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def create_users_with_list_input + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def destroy + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def show + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def login_user + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def logout_user + # Your code here + + render json: {"message" => "yes, it worked"} + end + + def update + # Your code here + + render json: {"message" => "yes, it worked"} + end +end diff --git a/samples/server/petstore/rails5/app/jobs/application_job.rb b/samples/server/petstore/rails5/app/jobs/application_job.rb new file mode 100644 index 00000000000..a009ace51cc --- /dev/null +++ b/samples/server/petstore/rails5/app/jobs/application_job.rb @@ -0,0 +1,2 @@ +class ApplicationJob < ActiveJob::Base +end diff --git a/samples/server/petstore/rails5/app/mailers/application_mailer.rb b/samples/server/petstore/rails5/app/mailers/application_mailer.rb new file mode 100644 index 00000000000..286b2239d13 --- /dev/null +++ b/samples/server/petstore/rails5/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/samples/server/petstore/rails5/app/models/application_record.rb b/samples/server/petstore/rails5/app/models/application_record.rb new file mode 100644 index 00000000000..10a4cba84df --- /dev/null +++ b/samples/server/petstore/rails5/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb b/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb new file mode 100644 index 00000000000..cbd34d2e9dd --- /dev/null +++ b/samples/server/petstore/rails5/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb b/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb new file mode 100644 index 00000000000..37f0bddbd74 --- /dev/null +++ b/samples/server/petstore/rails5/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/samples/server/petstore/rails5/bin/bundle b/samples/server/petstore/rails5/bin/bundle new file mode 100755 index 00000000000..66e9889e8b4 --- /dev/null +++ b/samples/server/petstore/rails5/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/samples/server/petstore/rails5/bin/rails b/samples/server/petstore/rails5/bin/rails new file mode 100755 index 00000000000..07396602377 --- /dev/null +++ b/samples/server/petstore/rails5/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/samples/server/petstore/rails5/bin/rake b/samples/server/petstore/rails5/bin/rake new file mode 100755 index 00000000000..17240489f64 --- /dev/null +++ b/samples/server/petstore/rails5/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/samples/server/petstore/rails5/bin/setup b/samples/server/petstore/rails5/bin/setup new file mode 100755 index 00000000000..e620b4dadb2 --- /dev/null +++ b/samples/server/petstore/rails5/bin/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a starting point to setup your application. + # Add necessary setup steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + # puts "\n== Copying sample files ==" + # unless File.exist?('config/database.yml') + # cp 'config/database.yml.sample', 'config/database.yml' + # end + + puts "\n== Preparing database ==" + system! 'bin/rails db:setup' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/samples/server/petstore/rails5/bin/update b/samples/server/petstore/rails5/bin/update new file mode 100755 index 00000000000..a8e4462f203 --- /dev/null +++ b/samples/server/petstore/rails5/bin/update @@ -0,0 +1,29 @@ +#!/usr/bin/env ruby +require 'pathname' +require 'fileutils' +include FileUtils + +# path to your application root. +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +chdir APP_ROOT do + # This script is a way to update your development environment automatically. + # Add necessary update steps to this file. + + puts '== Installing dependencies ==' + system! 'gem install bundler --conservative' + system('bundle check') || system!('bundle install') + + puts "\n== Updating database ==" + system! 'bin/rails db:migrate' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/samples/server/petstore/rails5/config.ru b/samples/server/petstore/rails5/config.ru new file mode 100644 index 00000000000..f7ba0b527b1 --- /dev/null +++ b/samples/server/petstore/rails5/config.ru @@ -0,0 +1,5 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application diff --git a/samples/server/petstore/rails5/config/application.rb b/samples/server/petstore/rails5/config/application.rb new file mode 100644 index 00000000000..70bea9ecf69 --- /dev/null +++ b/samples/server/petstore/rails5/config/application.rb @@ -0,0 +1,30 @@ +require_relative 'boot' + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "action_cable/engine" +# require "sprockets/railtie" +require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ApiDemo + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/samples/server/petstore/rails5/config/boot.rb b/samples/server/petstore/rails5/config/boot.rb new file mode 100644 index 00000000000..30f5120df69 --- /dev/null +++ b/samples/server/petstore/rails5/config/boot.rb @@ -0,0 +1,3 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/samples/server/petstore/rails5/config/cable.yml b/samples/server/petstore/rails5/config/cable.yml new file mode 100644 index 00000000000..aa4e832748c --- /dev/null +++ b/samples/server/petstore/rails5/config/cable.yml @@ -0,0 +1,10 @@ +# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket. +production: + adapter: redis + url: redis://localhost:6379/1 + +development: + adapter: async + +test: + adapter: async diff --git a/samples/server/petstore/rails5/config/config/development.rb b/samples/server/petstore/rails5/config/config/development.rb new file mode 100644 index 00000000000..082a013ab36 --- /dev/null +++ b/samples/server/petstore/rails5/config/config/development.rb @@ -0,0 +1,47 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => 'public, max-age=172800' + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker +end diff --git a/samples/server/petstore/rails5/config/config/production.rb b/samples/server/petstore/rails5/config/config/production.rb new file mode 100644 index 00000000000..6cb0a8fe61c --- /dev/null +++ b/samples/server/petstore/rails5/config/config/production.rb @@ -0,0 +1,80 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Action Cable endpoint configuration + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Don't mount Action Cable in the main server process. + # config.action_cable.mount_path = nil + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment) + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "api_demo_#{Rails.env}" + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/samples/server/petstore/rails5/config/database.yml b/samples/server/petstore/rails5/config/database.yml new file mode 100644 index 00000000000..e536d9f37dc --- /dev/null +++ b/samples/server/petstore/rails5/config/database.yml @@ -0,0 +1,54 @@ +# MySQL. Versions 5.0 and up are supported. +# +# Install the MySQL driver +# gem install mysql2 +# +# Ensure the MySQL gem is defined in your Gemfile +# gem 'mysql2' +# +# And be sure to use new-style password hashing: +# http://dev.mysql.com/doc/refman/5.7/en/old-client.html +# +default: &default + adapter: mysql2 + encoding: utf8 + pool: 5 + username: root + password: + socket: /tmp/mysql.sock + +development: + <<: *default + database: api_demo_development + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: api_demo_test + +# As with config/secrets.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password as a unix environment variable when you boot +# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full rundown on how to provide these environment variables in a +# production deployment. +# +# On Heroku and other platform providers, you may have a full connection URL +# available as an environment variable. For example: +# +# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase" +# +# You can use this database configuration with: +# +# production: +# url: <%= ENV['DATABASE_URL'] %> +# +production: + <<: *default + database: api_demo_production + username: api_demo + password: <%= ENV['API_DEMO_DATABASE_PASSWORD'] %> diff --git a/samples/server/petstore/rails5/config/environment.rb b/samples/server/petstore/rails5/config/environment.rb new file mode 100644 index 00000000000..426333bb469 --- /dev/null +++ b/samples/server/petstore/rails5/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb b/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb new file mode 100644 index 00000000000..f613b40f804 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/active_record_belongs_to_required_by_default.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Require `belongs_to` associations by default. This is a new Rails 5.0 +# default, so it is introduced as a configuration option to ensure that apps +# made on earlier versions of Rails are not affected when upgrading. +Rails.application.config.active_record.belongs_to_required_by_default = true diff --git a/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb b/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb new file mode 100644 index 00000000000..51639b67a00 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/application_controller_renderer.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) diff --git a/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb b/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb new file mode 100644 index 00000000000..59385cdf379 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. +# Rails.backtrace_cleaner.remove_silencers! diff --git a/samples/server/petstore/rails5/config/initializers/callback_terminator.rb b/samples/server/petstore/rails5/config/initializers/callback_terminator.rb new file mode 100644 index 00000000000..649e82280e1 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/callback_terminator.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Do not halt callback chains when a callback returns false. This is a new +# Rails 5.0 default, so it is introduced as a configuration option to ensure +# that apps made with earlier versions of Rails are not affected when upgrading. +ActiveSupport.halt_callback_chains_on_return_false = false diff --git a/samples/server/petstore/rails5/config/initializers/cors.rb b/samples/server/petstore/rails5/config/initializers/cors.rb new file mode 100644 index 00000000000..3b1c1b5ed14 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins 'example.com' +# +# resource '*', +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb b/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb new file mode 100644 index 00000000000..4a994e1e7bb --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/samples/server/petstore/rails5/config/initializers/inflections.rb b/samples/server/petstore/rails5/config/initializers/inflections.rb new file mode 100644 index 00000000000..ac033bf9dc8 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/samples/server/petstore/rails5/config/initializers/mime_types.rb b/samples/server/petstore/rails5/config/initializers/mime_types.rb new file mode 100644 index 00000000000..dc1899682b0 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/samples/server/petstore/rails5/config/initializers/ssl_options.rb b/samples/server/petstore/rails5/config/initializers/ssl_options.rb new file mode 100644 index 00000000000..1775dea1e76 --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/ssl_options.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure SSL options to enable HSTS with subdomains. +Rails.application.config.ssl_options = { hsts: { subdomains: true } } diff --git a/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb b/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb new file mode 100644 index 00000000000..8674be3227e --- /dev/null +++ b/samples/server/petstore/rails5/config/initializers/to_time_preserves_timezone.rb @@ -0,0 +1,10 @@ +# Be sure to restart your server when you modify this file. + +# Preserve the timezone of the receiver when calling to `to_time`. +# Ruby 2.4 will change the behavior of `to_time` to preserve the timezone +# when converting to an instance of `Time` instead of the previous behavior +# of converting to the local system timezone. +# +# Rails 5.0 introduced this config option so that apps made with earlier +# versions of Rails are not affected when upgrading. +ActiveSupport.to_time_preserves_timezone = true diff --git a/samples/server/petstore/rails5/config/locales/en.yml b/samples/server/petstore/rails5/config/locales/en.yml new file mode 100644 index 00000000000..0653957166e --- /dev/null +++ b/samples/server/petstore/rails5/config/locales/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/samples/server/petstore/rails5/config/puma.rb b/samples/server/petstore/rails5/config/puma.rb new file mode 100644 index 00000000000..c7f311f8116 --- /dev/null +++ b/samples/server/petstore/rails5/config/puma.rb @@ -0,0 +1,47 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum, this matches the default thread size of Active Record. +# +threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests, default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked webserver processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. If you use this option +# you need to make sure to reconnect any threads in the `on_worker_boot` +# block. +# +# preload_app! + +# The code in the `on_worker_boot` will be called if you are using +# clustered mode by specifying a number of `workers`. After each worker +# process is booted this block will be run, if you are using `preload_app!` +# option you will want to use this block to reconnect to any threads +# or connections that may have been created at application boot, Ruby +# cannot share connections between processes. +# +# on_worker_boot do +# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) +# end + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/samples/server/petstore/rails5/config/routes.rb b/samples/server/petstore/rails5/config/routes.rb new file mode 100644 index 00000000000..de0b1f61035 --- /dev/null +++ b/samples/server/petstore/rails5/config/routes.rb @@ -0,0 +1,28 @@ +Rails.application.routes.draw do + + def add_swagger_route http_method, path, opts = {} + full_path = path.gsub(/{(.*?)}/, ':\1') + match full_path, to: "#{opts.fetch(:controller_name)}##{opts[:action_name]}", via: http_method + end + + add_swagger_route 'POST', '/v2/pet', controller_name: 'pet', action_name: 'create' + add_swagger_route 'DELETE', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'destroy' + add_swagger_route 'GET', '/v2/pet/findByStatus', controller_name: 'pet', action_name: 'find_pets_by_status' + add_swagger_route 'GET', '/v2/pet/findByTags', controller_name: 'pet', action_name: 'find_pets_by_tags' + add_swagger_route 'GET', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'show' + add_swagger_route 'PUT', '/v2/pet', controller_name: 'pet', action_name: 'update_pet' + add_swagger_route 'POST', '/v2/pet/{petId}', controller_name: 'pet', action_name: 'update_pet_with_form' + add_swagger_route 'POST', '/v2/pet/{petId}/uploadImage', controller_name: 'pet', action_name: 'upload_file' + add_swagger_route 'DELETE', '/v2/store/order/{orderId}', controller_name: 'store', action_name: 'delete_order' + add_swagger_route 'GET', '/v2/store/inventory', controller_name: 'store', action_name: 'get_inventory' + add_swagger_route 'GET', '/v2/store/order/{orderId}', controller_name: 'store', action_name: 'get_order_by_id' + add_swagger_route 'POST', '/v2/store/order', controller_name: 'store', action_name: 'place_order' + add_swagger_route 'POST', '/v2/user', controller_name: 'user', action_name: 'create' + add_swagger_route 'POST', '/v2/user/createWithArray', controller_name: 'user', action_name: 'create_users_with_array_input' + add_swagger_route 'POST', '/v2/user/createWithList', controller_name: 'user', action_name: 'create_users_with_list_input' + add_swagger_route 'DELETE', '/v2/user/{username}', controller_name: 'user', action_name: 'destroy' + add_swagger_route 'GET', '/v2/user/{username}', controller_name: 'user', action_name: 'show' + add_swagger_route 'GET', '/v2/user/login', controller_name: 'user', action_name: 'login_user' + add_swagger_route 'GET', '/v2/user/logout', controller_name: 'user', action_name: 'logout_user' + add_swagger_route 'PUT', '/v2/user/{username}', controller_name: 'user', action_name: 'update' +end diff --git a/samples/server/petstore/rails5/config/secrets.yml b/samples/server/petstore/rails5/config/secrets.yml new file mode 100644 index 00000000000..179b066b84d --- /dev/null +++ b/samples/server/petstore/rails5/config/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: 2e13a003477a557ba3fcc6260c2ec69e411238b9b8b530c3c70e71f7cfc905b5f746f5c195a0282342a77ad6acd4e6ef8949106723200a99414fe83393d67344 + +test: + secret_key_base: fedf54236a94882c00e2fa0af308a4135f50941396437b9fbc38dd340c0a8bcf38cfcf6264cc2abc2af5bda26252293fe48e9a3e90fbfc4d25d6886d6d14b300 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/samples/server/petstore/rails5/config/spring.rb b/samples/server/petstore/rails5/config/spring.rb new file mode 100644 index 00000000000..c9119b40c08 --- /dev/null +++ b/samples/server/petstore/rails5/config/spring.rb @@ -0,0 +1,6 @@ +%w( + .ruby-version + .rbenv-vars + tmp/restart.txt + tmp/caching-dev.txt +).each { |path| Spring.watch(path) } diff --git a/samples/server/petstore/rails5/db/migrate/.keep b/samples/server/petstore/rails5/db/migrate/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/db/schema.rb b/samples/server/petstore/rails5/db/schema.rb new file mode 100644 index 00000000000..4dfbb16804e --- /dev/null +++ b/samples/server/petstore/rails5/db/schema.rb @@ -0,0 +1,16 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 0) do + +end diff --git a/samples/server/petstore/rails5/db/seeds.rb b/samples/server/petstore/rails5/db/seeds.rb new file mode 100644 index 00000000000..1beea2accd7 --- /dev/null +++ b/samples/server/petstore/rails5/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) diff --git a/samples/server/petstore/rails5/lib/tasks/.keep b/samples/server/petstore/rails5/lib/tasks/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/log/.keep b/samples/server/petstore/rails5/log/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/log/development.log b/samples/server/petstore/rails5/log/development.log new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/404.html b/samples/server/petstore/rails5/public/404.html new file mode 100644 index 00000000000..b612547fc21 --- /dev/null +++ b/samples/server/petstore/rails5/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/422.html b/samples/server/petstore/rails5/public/422.html new file mode 100644 index 00000000000..a21f82b3bdb --- /dev/null +++ b/samples/server/petstore/rails5/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/500.html b/samples/server/petstore/rails5/public/500.html new file mode 100644 index 00000000000..061abc587dc --- /dev/null +++ b/samples/server/petstore/rails5/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/samples/server/petstore/rails5/public/apple-touch-icon-precomposed.png b/samples/server/petstore/rails5/public/apple-touch-icon-precomposed.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/apple-touch-icon.png b/samples/server/petstore/rails5/public/apple-touch-icon.png new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/favicon.ico b/samples/server/petstore/rails5/public/favicon.ico new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/public/robots.txt b/samples/server/petstore/rails5/public/robots.txt new file mode 100644 index 00000000000..3c9c7c01f30 --- /dev/null +++ b/samples/server/petstore/rails5/public/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/samples/server/petstore/rails5/test/test_helper.rb b/samples/server/petstore/rails5/test/test_helper.rb new file mode 100644 index 00000000000..92e39b2d78c --- /dev/null +++ b/samples/server/petstore/rails5/test/test_helper.rb @@ -0,0 +1,10 @@ +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +require 'rails/test_help' + +class ActiveSupport::TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/samples/server/petstore/rails5/tmp/cache/.keep b/samples/server/petstore/rails5/tmp/cache/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/pids/.keep b/samples/server/petstore/rails5/tmp/pids/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/restart.txt b/samples/server/petstore/rails5/tmp/restart.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/tmp/sockets/.keep b/samples/server/petstore/rails5/tmp/sockets/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/rails5/vendor/.keep b/samples/server/petstore/rails5/vendor/.keep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/spring-mvc-j8-async/pom.xml b/samples/server/petstore/spring-mvc-j8-async/pom.xml index 1c535f34084..767c386463f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/pom.xml +++ b/samples/server/petstore/spring-mvc-j8-async/pom.xml @@ -163,10 +163,9 @@ 9.2.9.v20150224 1.13 1.6.3 - 1.6.1 4.8.1 2.5 - 2.0.4-SNAPSHOT - 4.0.9.RELEASE + 2.4.0 + 4.2.5.RELEASE \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java index 608a7957017..041a8a204f3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java index 0a2894d0be4..1276b3cfab0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java index 9bc56631d29..4859dc5c6c4 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java index 72ca217e7c0..67027e9eb9e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index c3d4887b35f..363b8deee1d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -3,6 +3,7 @@ package io.swagger.api; import io.swagger.model.*; import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; import java.io.File; import java.util.concurrent.Callable; @@ -34,7 +35,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface PetApi { @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { @@ -46,12 +47,12 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) default Callable> addPet( -@ApiParam(value = "Pet object that needs to be added to the store" ) @RequestBody Pet body +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body ) throws NotFoundException { // do some magic! @@ -68,7 +69,7 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deletePet( @@ -85,7 +86,7 @@ public interface PetApi { } - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -95,10 +96,10 @@ public interface PetApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid status value") }) @RequestMapping(value = "/findByStatus", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status + default Callable>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status ) @@ -108,7 +109,7 @@ public interface PetApi { } - @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -118,10 +119,10 @@ public interface PetApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid tag value") }) @RequestMapping(value = "/findByTags", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable>> findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags + default Callable>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags ) @@ -131,11 +132,7 @@ public interface PetApi { } - @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }), + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") }) @ApiResponses(value = { @@ -143,11 +140,11 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getPetById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId ) throws NotFoundException { @@ -167,12 +164,12 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found"), @ApiResponse(code = 405, message = "Validation exception") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) default Callable> updatePet( -@ApiParam(value = "Pet object that needs to be added to the store" ) @RequestBody Pet body +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body ) throws NotFoundException { // do some magic! @@ -189,11 +186,11 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) default Callable> updatePetWithForm( -@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId , @@ -212,7 +209,7 @@ public interface PetApi { } - @ApiOperation(value = "uploads an image", notes = "", response = Void.class, authorizations = { + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -221,10 +218,10 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/{petId}/uploadImage", - produces = { "application/json", "application/xml" }, + produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - default Callable> uploadFile( + default Callable> uploadFile( @ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId , @@ -239,7 +236,7 @@ public interface PetApi { ) throws NotFoundException { // do some magic! - return () -> new ResponseEntity(HttpStatus.OK); + return () -> new ResponseEntity(HttpStatus.OK); } } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java index 4eb6c73849a..f5c454b68e1 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java @@ -34,7 +34,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @@ -42,7 +42,7 @@ public interface StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deleteOrder( @@ -61,7 +61,7 @@ public interface StoreApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/inventory", - produces = { "application/json", "application/xml" }, + produces = { "application/json" }, method = RequestMethod.GET) default Callable>> getInventory() @@ -77,11 +77,11 @@ public interface StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getOrderById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId ) throws NotFoundException { @@ -95,12 +95,12 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid Order") }) @RequestMapping(value = "/order", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> placeOrder( -@ApiParam(value = "order placed for purchasing the pet" ) @RequestBody Order body +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java index b24082923dc..7141c53284d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java @@ -34,19 +34,19 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public interface UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUser( -@ApiParam(value = "Created user object" ) @RequestBody User body +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body ) throws NotFoundException { // do some magic! @@ -58,12 +58,12 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/createWithArray", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUsersWithArrayInput( -@ApiParam(value = "List of user object" ) @RequestBody List body +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body ) throws NotFoundException { // do some magic! @@ -75,12 +75,12 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/createWithList", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) default Callable> createUsersWithListInput( -@ApiParam(value = "List of user object" ) @RequestBody List body +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body ) throws NotFoundException { // do some magic! @@ -93,7 +93,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) default Callable> deleteUser( @@ -112,7 +112,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> getUserByName( @@ -130,14 +130,14 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid username/password supplied") }) @RequestMapping(value = "/login", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default Callable> loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username + default Callable> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username , - @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password ) @@ -151,7 +151,7 @@ public interface UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/logout", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) default Callable> logoutUser() @@ -166,7 +166,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid user supplied"), @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) default Callable> updateUser( @@ -175,7 +175,7 @@ public interface UserApi { , -@ApiParam(value = "Updated user object" ) @RequestBody User body +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java index 5004845542f..3b3f1c4e719 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -20,18 +20,18 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger Petstore") - .description("This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters") + .description("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.") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .termsOfServiceUrl("") .version("1.0.0") - .contact(new Contact("","", "apiteam@wordnik.com")) + .contact(new Contact("","", "apiteam@swagger.io")) .build(); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index 6b3b305942f..b68e3a5d9f8 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,7 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java index 7e437ae6b14..e99cfea70a2 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,7 +2,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index 40f8a10a438..70ad7190474 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,7 +3,7 @@ package io.swagger.configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java index 18f08f895e1..e9d8c1ffed0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..61d9bc8be58 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,84 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" type: ").append(type).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java index 738a9e81f96..8ea322ac31d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Order { private Long id = null; @@ -23,7 +23,7 @@ public class Order { }; private StatusEnum status = null; - private Boolean complete = null; + private Boolean complete = false; /** **/ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java index 26e4d3c529e..482e8e16097 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java @@ -14,7 +14,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java index 2f39f45a1f8..895fb2a7e1f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java index eee7800acbf..5620b9d4b72 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java @@ -10,7 +10,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-03T13:42:56.594+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2016-05-11T18:25:35.092+08:00") public class User { private Long id = null;